Merge: nitc: check pkg-config packages availability later
[nit.git] / lib / gamnit / flat / flat_core.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Core services for the `flat` API for 2D games
16 module flat_core
17
18 import glesv2
19 intrude import geometry::points_and_lines # For _x, _y and _z
20 intrude import matrix
21 import matrix::projection
22 import more_collections
23 import performance_analysis
24
25 import gamnit
26 intrude import gamnit::cameras
27 intrude import gamnit::cameras_cache
28 import gamnit::dynamic_resolution
29
30 # Visible 2D entity in the game world or UI
31 #
32 # Similar to `gamnit::Actor` which is in 3D.
33 #
34 # Each sprite associates a `texture` to the position `center`.
35 # The appearance is modified by `rotation`, `invert_x`,
36 # `scale`, `red`, `green`, `blue` and `alpha`.
37 # These values can be changed at any time and will trigger an update
38 # of the data on the GPU side, having a small performance cost.
39 #
40 # For a sprite to be visible, it must be added to either the world `sprites`
41 # or the `ui_sprites`.
42 # However, an instance of `Sprite` can only belong to a single `SpriteSet`
43 # at a time. The final on-screen position depends on the camera associated
44 # to the `SpriteSet`.
45 #
46 # ~~~
47 # # Load texture and create sprite
48 # var texture = new Texture("path/in/assets.png")
49 # var sprite = new Sprite(texture, new Point3d[Float](0.0, 0.0, 0.0))
50 #
51 # # Add sprite to the visible game world
52 # app.sprites.add sprite
53 #
54 # # Extra configuration of the sprite
55 # sprite.rotation = pi/2.0
56 # sprite.scale = 2.0
57 #
58 # # Show only the blue colors
59 # sprite.red = 0.0
60 # sprite.green = 0.0
61 # ~~~
62 #
63 # To add a sprite to the UI it can be anchored to screen borders
64 # with `ui_camera.top_left` and the likes.
65 #
66 # ~~~nitish
67 # # Place it a bit off the top left of the screen
68 # var pos = app.ui_camera.top_left.offset(128.0, -128.0, 0)
69 #
70 # # Load texture and create sprite
71 # var texture = new Texture("path/in/assets.png")
72 # var sprite = new Sprite(texture, pos)
73 #
74 # # Add it to the UI (above world sprites)
75 # app.ui_sprites.add sprite
76 # ~~~
77 class Sprite
78
79 # Texture drawn to screen
80 var texture: Texture is writable(texture_direct=)
81
82 # Texture drawn to screen
83 fun texture=(texture: Texture)
84 do
85 if isset _texture and texture != self.texture then
86 needs_update
87 if texture.root != self.texture.root then needs_remap
88 end
89 texture_direct = texture
90 end
91
92 # Center position of this sprite in world coordinates
93 var center: Point3d[Float] is writable(center_direct=), noautoinit
94
95 # Center position of this sprite in world coordinates
96 fun center=(center: Point3d[Float]) is autoinit do
97 if isset _center and center != self.center then
98 needs_update
99 self.center.sprites_remove self
100 end
101
102 center.sprites_add self
103 center_direct = center
104 end
105
106 # Last animation set with `animate`
107 var animation: nullable Animation = null
108
109 # Animation on the shader, if this changes it `needs_remap`
110 private var shader_animation: nullable Animation = null
111
112 # Animation start time, relative to `sprite_set.time`
113 #
114 # At -1.0 if animation started before being assigned a `sprite_set`.
115 private var animation_start = 0.0
116
117 # Number of loops to show `animation`
118 private var animation_loops = 0.0
119
120 # Start the `animation` for `n_loops`, replacing the static `texture`
121 #
122 # By default, if `n_loops` is not set, the animation plays once.
123 # If `n_loops == -1.0` then the animation loops infinitely.
124 # Otherwise, the animation repeats, e.g. it repeats twice and a half
125 # if `n_loops == 2.5`.
126 #
127 # The animation can be stopped using `animate_stop`.
128 fun animate(animation: Animation, n_loops: nullable Float)
129 do
130 if not animation.valid then print_error "{class_name}::animate: invalid animation {animation}"
131
132 var shader_animation = shader_animation
133 if shader_animation == null or animation.frames.first.root != shader_animation.frames.first.root then
134 # Resort with the new animation texture
135 needs_remap
136 else
137 needs_update
138 end
139
140 var sprite_set = sprite_set
141 animation_start = if sprite_set != null then sprite_set.time else -1.0
142 animation_loops = n_loops or else 1.0
143 self.shader_animation = animation
144 self.animation = animation
145 end
146
147 # Stop any active `animation` to display the static `texture`
148 fun animate_stop
149 do
150 if animation == null then return
151 needs_update
152 animation = null
153 end
154
155 # Rotation on the Z axis, positive values turn counterclockwise
156 var rotation = 0.0 is writable(rotation_direct=)
157
158 # Rotation on the Z axis, positive values turn counterclockwise
159 fun rotation=(value: Float)
160 do
161 if isset _rotation and value != rotation then needs_update
162 rotation_direct = value
163 end
164
165 # Mirror `texture` horizontally, inverting each pixel on the X axis
166 var invert_x = false is writable(invert_x_direct=)
167
168 # Mirror `texture` horizontally, inverting each pixel on the X axis
169 fun invert_x=(value: Bool)
170 do
171 if isset _invert_x and value != invert_x then needs_update
172 invert_x_direct = value
173 end
174
175 # Scale applied to this sprite
176 #
177 # The basic size of `self` depends on the size in pixels of `texture`.
178 var scale = 1.0 is writable(scale_direct=)
179
180 # Scale applied to this sprite
181 #
182 # The basic size of `self` depends on the size in pixels of `texture`.
183 fun scale=(value: Float)
184 do
185 if isset _scale and value != scale then needs_update
186 scale_direct = value
187 end
188
189 # Red tint applied to `texture` on draw
190 fun red: Float do return tint[0]
191
192 # Red tint applied to `texture` on draw
193 fun red=(value: Float)
194 do
195 if isset _tint and value != red then needs_update
196 tint[0] = value
197 end
198
199 # Green tint applied to `texture` on draw
200 fun green: Float do return tint[1]
201
202 # Green tint applied to `texture` on draw
203 fun green=(value: Float)
204 do
205 if isset _tint and value != green then needs_update
206 tint[1] = value
207 end
208
209 # Blue tint applied to `texture` on draw
210 fun blue: Float do return tint[2]
211
212 # Blue tint applied to `texture` on draw
213 fun blue=(value: Float)
214 do
215 if isset _tint and value != blue then needs_update
216 tint[2] = value
217 end
218
219 # Transparency applied to `texture` on draw
220 fun alpha: Float do return tint[3]
221
222 # Transparency applied to `texture` on draw
223 fun alpha=(value: Float)
224 do
225 if isset _tint and value != alpha then needs_update
226 tint[3] = value
227 end
228
229 # Tint applied to `texture` on draw
230 #
231 # Alternative to the accessors `red, green, blue & alpha`.
232 # Changes inside the array do not automatically set `needs_update`.
233 #
234 # Require: `tint.length == 4`
235 var tint: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct=)
236
237 # Tint applied to `texture` on draw, see `tint`
238 fun tint=(value: Array[Float])
239 do
240 if isset _tint and value != tint then needs_update
241 tint_direct = value
242 end
243
244 # Draw order, higher values cause this sprite to be drawn latter
245 #
246 # Change this value to avoid artifacts when drawing non-opaque sprites.
247 # In general, sprites with a non-opaque `texture` and sprites closer to
248 # the camera should have a higher value to be drawn last.
249 #
250 # Sprites sharing a `draw_order` are drawn in the same pass.
251 # The sprite to sprite draw order is undefined and may change when adding
252 # and removing sprites, or changing their attributes.
253 #
254 # ### Warning
255 #
256 # Changing this value may have a negative performance impact if there are
257 # many different `draw_order` values across many sprites.
258 # Sprites sharing some attributes are drawn as group to reduce
259 # the communication overhead between the CPU and GPU,
260 # and changing `draw_order` may break up large groups into smaller groups.
261 var draw_order = 0 is writable(draw_order_direct=)
262
263 # Set draw order, see `draw_order`
264 fun draw_order=(value: Int)
265 do
266 if isset _draw_order and value != draw_order then needs_remap
267 draw_order_direct = value
268 end
269
270 # Is this sprite static and added in bulk?
271 #
272 # Set to `true` to give a hint to the framework that this sprite won't
273 # change often and that it is added in bulk with other static sprites.
274 # This value can be ignored in the prototyping phase of a game and
275 # added only when better performance are needed.
276 var static = false is writable(static_direct=)
277
278 # Is this sprite static and added in bulk? see `static`
279 fun static=(value: Bool)
280 do
281 if isset _static and value != static then needs_remap
282 static_direct = value
283 end
284
285 # Request an update on the CPU
286 #
287 # This is called automatically on modification of any value of `Sprite`.
288 # However, it can still be set manually if a modification can't be
289 # detected or by subclasses.
290 fun needs_update
291 do
292 var c = context
293 if c == null then return
294 if c.last_sprite_to_update == self then return
295 c.sprites_to_update.add self
296 c.last_sprite_to_update = self
297 end
298
299 # Request a resorting of this sprite in its sprite list
300 #
301 # Resorting is required when `static` or the root of `texture` changes.
302 # This is called automatically when such changes are detected.
303 # However, it can still be set manually if a modification can't be
304 # detected or by subclasses.
305 fun needs_remap
306 do
307 var l = sprite_set
308 if l != null then l.sprites_to_remap.add self
309 end
310
311 # Current context to which `self` was sorted
312 private var context: nullable SpriteContext = null
313
314 # Index in `context`
315 private var context_index: Int = -1
316
317 # Current context to which `self` belongs
318 private var sprite_set: nullable SpriteSet = null
319 end
320
321 # Animation for sprites, set with `Sprite.animate`
322 #
323 # Two main services create animations:
324 # * The constructors accepts an array of textures and the number of frames per
325 # seconds: `new Animation(array_of_subtextures, 10.0)`
326 # * The method `Texture::to_animation` uses the whole texture
327 # dividing it in frames either on X or Y:
328 # `new Texture("path/in/assets.png").to_animation(30.0, 0, 12)`
329 class Animation
330
331 # Frames composing this animation
332 #
333 # All frames must share the same `Texture::root`, be on a vertical or
334 # horizontal line, be spaced equally and share the same dimensions.
335 var frames: SequenceRead[Texture]
336
337 # Frames per seconds, a higher value makes this animation faster
338 #
339 # The animation speed is also affected by `SpriteSet::time_mod`.
340 var fps: Float
341
342 # Are the `frames` valid for an animation? (see the requirements in `frames`)
343 var valid: Bool is lazy do
344 var r: nullable RootTexture = null
345 for f in frames do
346 if r == null then
347 r = f.root
348 else
349 if r != f.root then return false
350 end
351 end
352
353 # TODO check for line, constant distance, and same aspect ratio.
354
355 return true
356 end
357 end
358
359 redef class App
360 # Default graphic program to draw `sprites`
361 private var simple_2d_program = new Simple2dProgram is lazy
362
363 # Camera for world `sprites` and `depth::actors` with perspective
364 #
365 # By default, the camera is configured to a height of 1080 units
366 # of world coordinates at `z == 0.0`.
367 var world_camera: EulerCamera is lazy do
368 var camera = new EulerCamera(app.display.as(not null))
369
370 # Aim for full HD pixel resolution at level 0
371 camera.reset_height 1080.0
372 camera.near = 10.0
373
374 return camera
375 end
376
377 # Camera for `ui_sprites` using an orthogonal view
378 var ui_camera = new UICamera(app.display.as(not null)) is lazy
379
380 # World sprites drawn as seen by `world_camera`
381 var sprites = new SpriteSet
382
383 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
384 var ui_sprites = new SpriteSet
385
386 # Main method to refine in clients to update game logic and `sprites`
387 fun update(dt: Float) do end
388
389 # Display `texture` as a splash screen
390 #
391 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
392 fun show_splash_screen(texture: Texture)
393 do
394 texture.load
395
396 var splash = new Sprite(texture, ui_camera.center.offset(0.0, 0.0, 0.0))
397 ui_sprites.add splash
398
399 var display = display
400 assert display != null
401 glClear gl_COLOR_BUFFER_BIT
402
403 ui_camera.reset_height 1080.0
404 glViewport(0, 0, display.width, display.height)
405 frame_core_ui_sprites display
406 display.flip
407
408 ui_sprites.remove splash
409 end
410
411 # ---
412 # Support and implementation
413
414 # Main clock used to count each frame `dt`, lapsed for `update` only
415 private var clock = new Clock is lazy
416
417 # Performance clock to for `frame_core_draw` operations
418 private var perf_clock_main = new Clock
419
420 # Second performance clock for smaller operations
421 private var perf_clock_sprites = new Clock is lazy
422
423 redef fun create_gamnit
424 do
425 super
426 create_flat
427 end
428
429 # Prepare the flat framework services
430 fun create_flat
431 do
432 var display = display
433 assert display != null
434
435 var gl_error = glGetError
436 assert gl_error == gl_NO_ERROR else print_error gl_error
437
438 # Prepare program
439 var program = simple_2d_program
440 program.compile_and_link
441
442 var gamnit_error = program.error
443 assert gamnit_error == null else print_error gamnit_error
444
445 # Enable blending
446 gl.capabilities.blend.enable
447 glBlendFunc(gl_ONE, gl_ONE_MINUS_SRC_ALPHA)
448
449 # Enable depth test
450 gl.capabilities.depth_test.enable
451 glDepthFunc gl_LEQUAL
452 glDepthMask true
453
454 # Prepare viewport and background color
455 glViewport(0, 0, display.width, display.height)
456 glClearColor(0.0, 0.0, 0.0, 1.0)
457
458 gl_error = glGetError
459 assert gl_error == gl_NO_ERROR else print_error gl_error
460
461 # Prepare to draw
462 for tex in all_root_textures do
463 tex.load
464 gamnit_error = tex.error
465 if gamnit_error != null then print_error gamnit_error
466
467 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
468 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
469 end
470
471 sprites.reset
472 ui_sprites.reset
473 end
474
475 redef fun on_stop
476 do
477 super
478
479 # Close gamnit
480 var display = display
481 if display != null then display.close
482 end
483
484 redef fun on_resize(display)
485 do
486 super
487
488 world_camera.mvp_matrix_cache = null
489 ui_camera.mvp_matrix_cache = null
490
491 # Update all sprites in the UI
492 for sprite in ui_sprites do sprite.needs_update
493 end
494
495 redef fun on_resume
496 do
497 clock.lapse
498 super
499 end
500
501 redef fun frame_core(display)
502 do
503 # Check errors
504 var gl_error = glGetError
505 assert gl_error == gl_NO_ERROR else print_error gl_error
506
507 # Update game logic and set sprites
508 perf_clock_main.lapse
509 var dt = clock.lapse.to_f
510 update dt
511 frame_dt = dt
512 sys.perfs["gamnit flat update client"].add perf_clock_main.lapse
513
514 # Draw and flip screen
515 frame_core_draw display
516 display.flip
517
518 # Check errors
519 gl_error = glGetError
520 assert gl_error == gl_NO_ERROR else print_error gl_error
521 end
522
523 private var frame_dt = 0.0
524
525 # Draw the whole screen, all `glDraw...` calls should be executed here
526 protected fun frame_core_draw(display: GamnitDisplay)
527 do
528 frame_core_dynamic_resolution_before display
529
530 perf_clock_main.lapse
531 frame_core_world_sprites display
532 perfs["gamnit flat world_sprites"].add perf_clock_main.lapse
533
534 frame_core_ui_sprites display
535 perfs["gamnit flat ui_sprites"].add perf_clock_main.lapse
536
537 frame_core_dynamic_resolution_after display
538 end
539
540 private fun frame_core_sprites(display: GamnitDisplay, sprite_set: SpriteSet, camera: Camera)
541 do
542 var simple_2d_program = app.simple_2d_program
543 simple_2d_program.use
544 simple_2d_program.mvp.uniform camera.mvp_matrix
545
546 sprite_set.time += frame_dt*sprite_set.time_mod
547 simple_2d_program.time.uniform sprite_set.time
548
549 # draw
550 sprite_set.draw
551
552 assert glGetError == gl_NO_ERROR
553 end
554
555 # Draw world sprites from `sprites`
556 protected fun frame_core_world_sprites(display: GamnitDisplay)
557 do
558 frame_core_sprites(display, sprites, world_camera)
559 end
560
561 # Draw UI sprites from `ui_sprites`
562 protected fun frame_core_ui_sprites(display: GamnitDisplay)
563 do
564 # Reset only the depth buffer
565 glClear gl_DEPTH_BUFFER_BIT
566
567 frame_core_sprites(display, ui_sprites, ui_camera)
568 end
569 end
570
571 redef class Texture
572
573 # Vertices coordinates of the base geometry
574 #
575 # Defines the default width and height of related sprites.
576 private var vertices: Array[Float] is lazy do
577 var w = width
578 var h = height
579 return [-0.5*w, 0.5*h, 0.0,
580 0.5*w, 0.5*h, 0.0,
581 -0.5*w, -0.5*h, 0.0,
582 0.5*w, -0.5*h, 0.0]
583 end
584
585 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
586 private var texture_coords: Array[Float] is lazy do
587 var l = offset_left
588 var r = offset_right
589 var b = offset_bottom
590 var t = offset_top
591 return [l, t,
592 r, t,
593 l, b,
594 r, b]
595 end
596
597 # Coordinates of this texture on the `root` texture, inverting the X axis
598 private var texture_coords_invert_x: Array[Float] is lazy do
599 var l = offset_left
600 var r = offset_right
601 var b = offset_bottom
602 var t = offset_top
603 return [r, t,
604 l, t,
605 r, b,
606 l, b]
607 end
608
609 # Convert to a sprite animation at `fps` speed with `x` or `y` frames
610 #
611 # The arguments `x` and `y` set the number of frames in the texture.
612 # Use `x` for an horizontal arrangement or `y` for vertical.
613 # One and only one of the arguments must be different than 0,
614 # as an animation can only be on a line and cannot wrap.
615 fun to_animation(fps: Float, x, y: Int): Animation
616 do
617 assert (x == 0) != (y == 0)
618
619 var n_frames = x.max(y)
620 var frames = new Array[Texture]
621
622 var dx = (x/n_frames).to_f/n_frames.to_f
623 var dy = (y/n_frames).to_f/n_frames.to_f
624 var w = if x == 0 then 1.0 else dx
625 var h = if y == 0 then 1.0 else dy
626 var left = 0.0
627 var top = 0.0
628 for i in n_frames.times do
629 frames.add new RelativeSubtexture(root, left, top, left+w, top+h)
630 left += dx
631 top += dy
632 end
633
634 return new Animation(frames, fps)
635 end
636 end
637
638 # Graphic program to display simple models with a texture, translation, rotation and scale
639 private class Simple2dProgram
640 super GamnitProgramFromSource
641
642 redef var vertex_shader_source = """
643 // Vertex coordinates
644 attribute vec4 coord;
645
646 // Vertex color tint
647 attribute vec4 color;
648
649 // Vertex translation
650 attribute vec4 translation;
651
652 // Vertex scaling
653 attribute float scale;
654
655 // Vertex coordinates on textures
656 attribute vec2 tex_coord;
657
658 // Model view projection matrix
659 uniform mat4 mvp;
660
661 // Current world time, in seconds
662 uniform float time;
663
664 // Rotation matrix
665 attribute vec4 rotation_row0;
666 attribute vec4 rotation_row1;
667 attribute vec4 rotation_row2;
668 attribute vec4 rotation_row3;
669
670 // Animation speed, frames per seconds
671 attribute float a_fps;
672
673 // Number of frames in the animation
674 attribute float a_n_frames;
675
676 // World coordinate of the animation (for aspect ratio)
677 attribute vec2 a_coord;
678
679 // Animation texture coordinates of the first frame
680 attribute vec2 a_tex_coord;
681
682 // Animation texture coordinates difference between frames
683 attribute vec2 a_tex_diff;
684
685 // Animation start time, in reference to `time`
686 attribute float a_start;
687
688 // Number of loops to play of the animation
689 attribute float a_loops;
690
691 mat4 rotation()
692 {
693 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
694 }
695
696 // Output to the fragment shader
697 varying vec4 v_color;
698 varying vec2 v_coord;
699
700 // Is there an active animation?
701 varying float v_animated;
702
703 void main()
704 {
705 vec3 c; // coords
706
707 float end = a_start + a_loops/a_fps*a_n_frames;
708 if (a_fps != 0.0 && (a_loops == -1.0 || time < end)) {
709 // in animation
710 float frame = mod(floor((time-a_start)*a_fps), a_n_frames);
711 v_coord = a_tex_coord + a_tex_diff*frame;
712 c = vec3(a_coord, coord.z);
713 v_animated = 1.0;
714 } else {
715 // static
716 v_coord = tex_coord;
717 c = coord.xyz;
718 v_animated = 0.0;
719 }
720
721 gl_Position = (vec4(c * scale, 1.0) * rotation() + translation)* mvp;
722 v_color = vec4(color.rgb*color.a, color.a);
723 }
724 """ @ glsl_vertex_shader
725
726 redef var fragment_shader_source = """
727 precision mediump float;
728
729 // Does this object use a texture?
730 uniform bool use_texture;
731
732 // Texture to apply on this object
733 uniform sampler2D texture0;
734
735 // Texture to apply on this object
736 uniform sampler2D animation;
737
738 // Input from the vertex shader
739 varying vec4 v_color;
740 varying vec2 v_coord;
741 varying float v_animated;
742
743 void main()
744 {
745 if (v_animated > 0.5) {
746 gl_FragColor = v_color * texture2D(animation, v_coord);
747 if (gl_FragColor.a <= 0.01) discard;
748 } else if (use_texture) {
749 gl_FragColor = v_color * texture2D(texture0, v_coord);
750 if (gl_FragColor.a <= 0.01) discard;
751 } else {
752 gl_FragColor = v_color;
753 }
754 }
755 """ @ glsl_fragment_shader
756
757 # Vertices coordinates
758 var coord = attributes["coord"].as(AttributeVec4) is lazy
759
760 # Should this program use the texture `texture`?
761 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
762
763 # Visible texture unit
764 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
765
766 # Coordinates on the textures, per vertex
767 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
768
769 # Color tint per vertex
770 var color = attributes["color"].as(AttributeVec4) is lazy
771
772 # Translation applied to each vertex
773 var translation = attributes["translation"].as(AttributeVec4) is lazy
774
775 # Rotation matrix, row 0
776 var rotation_row0 = attributes["rotation_row0"].as(AttributeVec4) is lazy
777
778 # Rotation matrix, row 1
779 var rotation_row1 = attributes["rotation_row1"].as(AttributeVec4) is lazy
780
781 # Rotation matrix, row 2
782 var rotation_row2 = attributes["rotation_row2"].as(AttributeVec4) is lazy
783
784 # Rotation matrix, row 3
785 var rotation_row3 = attributes["rotation_row3"].as(AttributeVec4) is lazy
786
787 # Scaling per vertex
788 var scale = attributes["scale"].as(AttributeFloat) is lazy
789
790 # Model view projection matrix
791 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
792
793 # World time, in seconds
794 var time = uniforms["time"].as(UniformFloat) is lazy
795
796 # ---
797 # Animations
798
799 # Texture of all the frames of the animation
800 var animation_texture = uniforms["animation"].as(UniformSampler2D) is lazy
801
802 # Frame per second of the animation
803 var animation_fps = attributes["a_fps"].as(AttributeFloat) is lazy
804
805 # Number of frames in the animation
806 var animation_n_frames = attributes["a_n_frames"].as(AttributeFloat) is lazy
807
808 # Coordinates of each frame (mush be shared by all frames)
809 var animation_coord = attributes["a_coord"].as(AttributeVec2) is lazy
810
811 # Texture coordinates of the first frame
812 var animation_tex_coord = attributes["a_tex_coord"].as(AttributeVec2) is lazy
813
814 # Coordinate difference between each frame
815 var animation_tex_diff = attributes["a_tex_diff"].as(AttributeVec2) is lazy
816
817 # Animation start time, in seconds and in reference to `dt`
818 var animation_start = attributes["a_start"].as(AttributeFloat) is lazy
819
820 # Number of loops of the animation, -1 for infinite
821 var animation_loops = attributes["a_loops"].as(AttributeFloat) is lazy
822 end
823
824 redef class Point3d[N]
825 # ---
826 # Associate each point to its sprites
827
828 private var sprites: nullable Array[Sprite] = null
829
830 private fun sprites_add(sprite: Sprite)
831 do
832 var sprites = sprites
833 if sprites == null then
834 sprites = new Array[Sprite]
835 self.sprites = sprites
836 end
837 sprites.add sprite
838 end
839
840 private fun sprites_remove(sprite: Sprite)
841 do
842 var sprites = sprites
843 assert sprites != null
844 sprites.remove sprite
845 end
846
847 # ---
848 # Notify `sprites` on attribute modification
849
850 private fun needs_update
851 do
852 var sprites = sprites
853 if sprites != null then for s in sprites do s.needs_update
854 end
855
856 redef fun x=(v)
857 do
858 if isset _x and v != x then needs_update
859 super
860 end
861
862 redef fun y=(v)
863 do
864 if isset _y and v != y then needs_update
865 super
866 end
867
868 redef fun z=(v)
869 do
870 if isset _z and v != z then needs_update
871 super
872 end
873 end
874
875 redef class OffsetPoint3d
876 redef fun x=(v)
877 do
878 if isset _x and v != x then needs_update
879 super
880 end
881
882 redef fun y=(v)
883 do
884 if isset _y and v != y then needs_update
885 super
886 end
887
888 redef fun z=(v)
889 do
890 if isset _z and v != z then needs_update
891 super
892 end
893 end
894
895 # Set of sprites sorting them into different `SpriteContext`
896 class SpriteSet
897 super HashSet[Sprite]
898
899 # Animation speed multiplier (0.0 to pause, 1.0 for normal speed, etc.)
900 var time_mod = 1.0 is writable
901
902 # Seconds elapsed since the launch of the program, in world time responding to `time_mod`
903 var time = 0.0
904
905 # Map texture then static vs dynamic to a `SpriteContext`
906 private var contexts_map = new HashMap4[RootTexture, nullable RootTexture, Bool, Int, Array[SpriteContext]]
907
908 # Contexts in `contexts_map`, sorted by draw order
909 private var contexts_items = new Array[SpriteContext]
910
911 # Sprites needing resorting in `contexts_map`
912 private var sprites_to_remap = new Array[Sprite]
913
914 # Add a sprite to the appropriate context
915 private fun map_sprite(sprite: Sprite)
916 do
917 assert sprite.context == null else print_error "Sprite {sprite} belongs to another SpriteSet"
918
919 # Sort by texture and animation texture
920 var texture = sprite.texture.root
921 var animation = sprite.animation
922 var animation_texture = if animation != null then
923 animation.frames.first.root else null
924 var draw_order = sprite.draw_order
925 var contexts = contexts_map[texture, animation_texture, sprite.static, draw_order]
926
927 var context = null
928 if contexts != null then
929 for c in contexts.reverse_iterator do
930 var size = c.sprites.length + 1
931 if size * 4 <= 0xffff then
932 context = c
933 break
934 end
935 end
936 end
937
938 if context == null then
939 var usage = if sprite.static then gl_STATIC_DRAW else gl_DYNAMIC_DRAW
940 context = new SpriteContext(texture, animation_texture, usage, draw_order)
941
942 if contexts == null then
943 contexts = new Array[SpriteContext]
944 contexts_map[texture, animation_texture, sprite.static, draw_order] = contexts
945 end
946
947 contexts.add context
948
949 contexts_items.add context
950 sprite_draw_order_sorter.sort(contexts_items)
951 end
952
953 context.sprites.add sprite
954 context.sprites_to_update.add sprite
955 context.last_sprite_to_update = sprite
956
957 sprite.context = context
958 sprite.sprite_set = self
959
960 if animation != null and sprite.animation_start == -1.0 then
961 # Start animation
962 sprite.animation_start = time
963 end
964 end
965
966 # Remove a sprite from its context
967 private fun unmap_sprite(sprite: Sprite)
968 do
969 var context = sprite.context
970 assert context != null
971 context.sprites.remove sprite
972
973 sprite.context = null
974 sprite.sprite_set = null
975 end
976
977 # Draw all sprites by all contexts
978 private fun draw
979 do
980 # Remap sprites that may need to change context
981 for sprite in sprites_to_remap do
982
983 # Skip if it was removed from this set after being modified
984 if sprite.sprite_set != self then continue
985
986 unmap_sprite sprite
987 map_sprite sprite
988 end
989 sprites_to_remap.clear
990
991 # Sort by draw order
992 for context in contexts_items do context.draw
993 end
994
995 redef fun add(e)
996 do
997 if contexts_items.has(e.context) then return
998 map_sprite e
999 super
1000 end
1001
1002 redef fun remove(e)
1003 do
1004 super
1005 if e isa Sprite then unmap_sprite e
1006 end
1007
1008 redef fun remove_all(e)
1009 do
1010 if not has(e) then return
1011 remove e
1012 end
1013
1014 redef fun clear
1015 do
1016 for sprite in self do
1017 sprite.context = null
1018 sprite.sprite_set = null
1019 end
1020 super
1021 for c in contexts_items do c.destroy
1022 contexts_map.clear
1023 contexts_items.clear
1024 sprites_to_remap.clear
1025 end
1026
1027 private fun reset
1028 do
1029 for sprite in self do
1030 sprite.context = null
1031 end
1032
1033 for c in contexts_items do c.destroy
1034 contexts_map.clear
1035 contexts_items.clear
1036 sprites_to_remap.clear
1037
1038 for sprite in self do
1039 map_sprite sprite
1040 end
1041 end
1042 end
1043
1044 # Context for calls to `glDrawElements`
1045 #
1046 # Each context has only one `texture` and `usage`, but many sprites.
1047 private class SpriteContext
1048
1049 # ---
1050 # Context config and state
1051
1052 # Only root texture drawn by this context
1053 var texture: nullable RootTexture
1054
1055 # Only animation texture drawn by this context
1056 var animation_texture: nullable RootTexture
1057
1058 # OpenGL ES usage of `buffer_array` and `buffer_element`
1059 var usage: GLBufferUsage
1060
1061 # Draw order shared by all `sprites`
1062 var draw_order: Int
1063
1064 # Sprites drawn by this context
1065 var sprites = new GroupedSprites
1066
1067 # Sprites to update since last `draw`
1068 var sprites_to_update = new Set[Sprite]
1069
1070 # Cache of the last `Sprite` added to `sprites_to_update` since the last call to `draw`
1071 var last_sprite_to_update: nullable Sprite = null
1072
1073 # Sprites that have been update and for which `needs_update` can be set to false
1074 var updated_sprites = new Array[Sprite]
1075
1076 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
1077 #
1078 # Require: `resize_ratio >= 1.0`
1079 var resize_ratio = 1.2
1080
1081 # ---
1082 # OpenGL ES data
1083
1084 # OpenGL ES buffer name for vertex data
1085 var buffer_array: Int = -1
1086
1087 # OpenGL ES buffer name for indices
1088 var buffer_element: Int = -1
1089
1090 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
1091 var buffer_capacity = 0
1092
1093 # C buffers used to pass the data of a single sprite
1094 var local_data_buffer = new GLfloatArray(float_per_vertex*4) is lazy
1095 var local_indices_buffer = new CUInt16Array(indices_per_sprite) is lazy
1096
1097 # ---
1098 # Constants
1099
1100 # Number of GL_FLOAT per vertex of `Simple2dProgram`
1101 var float_per_vertex: Int is lazy do
1102 return 4 + 4 + 4 + # vec4 translation, vec4 color, vec4 coord,
1103 1 + 2 + 4*4 + # float scale, vec2 tex_coord, vec4 rotation_row*,
1104 1 + 1 + # float a_fps, float a_n_frames,
1105 2 + 2 + 2 + # vec2 a_coord, vec2 a_tex_coord, vec2 a_tex_diff,
1106 1 + 1 # float a_start, float a_loops
1107 end
1108
1109 # Number of bytes per vertex of `Simple2dProgram`
1110 var bytes_per_vertex: Int is lazy do
1111 var fs = 4 # sizeof(GL_FLOAT)
1112 return fs * float_per_vertex
1113 end
1114
1115 # Number of bytes per sprite
1116 var bytes_per_sprite: Int is lazy do return bytes_per_vertex * 4
1117
1118 # Number of vertex indices per sprite draw call (2 triangles)
1119 var indices_per_sprite = 6
1120
1121 # ---
1122 # Main services
1123
1124 # Allocate `buffer_array` and `buffer_element`
1125 fun prepare
1126 do
1127 var bufs = glGenBuffers(2)
1128 buffer_array = bufs[0]
1129 buffer_element = bufs[1]
1130
1131 var gl_error = glGetError
1132 assert gl_error == gl_NO_ERROR else print_error gl_error
1133 end
1134
1135 # Destroy `buffer_array` and `buffer_element`
1136 fun destroy
1137 do
1138 glDeleteBuffers([buffer_array, buffer_element])
1139 var gl_error = glGetError
1140 assert gl_error == gl_NO_ERROR else print_error gl_error
1141
1142 buffer_array = -1
1143 buffer_element = -1
1144 end
1145
1146 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
1147 fun resize
1148 do
1149 app.perf_clock_sprites.lapse
1150
1151 # Allocate a bit more space
1152 var capacity = (sprites.capacity.to_f * resize_ratio).to_i
1153
1154 var array_bytes = capacity * bytes_per_sprite
1155 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1156 assert glIsBuffer(buffer_array)
1157 glBufferData(gl_ARRAY_BUFFER, array_bytes, new Pointer.nul, usage)
1158 var gl_error = glGetError
1159 assert gl_error == gl_NO_ERROR else print_error gl_error
1160
1161 # GL_TRIANGLES 6 vertices * sprite
1162 var n_indices = capacity * indices_per_sprite
1163 var ius = 2 # sizeof(GL_UNSIGNED_SHORT)
1164 var element_bytes = n_indices * ius
1165 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1166 assert glIsBuffer(buffer_element)
1167 glBufferData(gl_ELEMENT_ARRAY_BUFFER, element_bytes, new Pointer.nul, usage)
1168 gl_error = glGetError
1169 assert gl_error == gl_NO_ERROR else print_error gl_error
1170
1171 buffer_capacity = capacity
1172
1173 sys.perfs["gamnit flat gpu resize"].add app.perf_clock_sprites.lapse
1174 end
1175
1176 # Update GPU data of `sprite`
1177 fun update_sprite(sprite: Sprite)
1178 do
1179 var context = sprite.context
1180 if context != self then return
1181
1182 var sprite_index = sprite.context_index
1183 assert sprite_index != -1
1184
1185 # Vertices data
1186
1187 var data = local_data_buffer
1188 var o = 0
1189 for v in [0..4[ do
1190 # vec4 translation
1191 data[o+ 0] = sprite.center.x
1192 data[o+ 1] = sprite.center.y
1193 data[o+ 2] = sprite.center.z
1194 data[o+ 3] = 0.0
1195
1196 # vec4 color
1197 data[o+ 4] = sprite.tint[0]
1198 data[o+ 5] = sprite.tint[1]
1199 data[o+ 6] = sprite.tint[2]
1200 data[o+ 7] = sprite.tint[3]
1201
1202 # float scale
1203 data[o+ 8] = sprite.scale
1204
1205 # vec4 coord
1206 data[o+ 9] = sprite.texture.vertices[v*3+0]
1207 data[o+10] = sprite.texture.vertices[v*3+1]
1208 data[o+11] = sprite.texture.vertices[v*3+2]
1209 data[o+12] = 0.0
1210
1211 # vec2 tex_coord
1212 var texture = texture
1213 if texture != null then
1214 var tc = if sprite.invert_x then
1215 sprite.texture.texture_coords_invert_x
1216 else sprite.texture.texture_coords
1217 data[o+13] = tc[v*2+0]
1218 data[o+14] = tc[v*2+1]
1219 end
1220
1221 # mat4 rotation
1222 var rot
1223 if sprite.rotation == 0.0 then
1224 # Cache the matrix at no rotation
1225 rot = once new Matrix.identity(4)
1226 else
1227 rot = new Matrix.rotation(sprite.rotation, 0.0, 0.0, 1.0)
1228 end
1229 data.fill_from_matrix(rot, o+15)
1230
1231 var animation = sprite.animation
1232 if animation == null then
1233 for i in [31..40] do data[o+i] = 0.0
1234 else
1235 # a_fps
1236 data[o+31] = animation.fps
1237
1238 # a_n_frames
1239 data[o+32] = animation.frames.length.to_f
1240
1241 # a_coord
1242 data[o+33] = animation.frames.first.vertices[v*3+0]
1243 data[o+34] = animation.frames.first.vertices[v*3+1]
1244
1245 # a_tex_coord
1246 var tc = if sprite.invert_x then
1247 animation.frames.first.texture_coords_invert_x
1248 else animation.frames.first.texture_coords
1249 data[o+35] = tc[v*2]
1250 data[o+36] = tc[v*2+1]
1251
1252 # a_tex_diff
1253 var dx = 0.0
1254 var dy = 0.0
1255 if animation.frames.length > 1 then
1256 dx = animation.frames[1].texture_coords[0] - animation.frames[0].texture_coords[0]
1257 dy = animation.frames[1].texture_coords[1] - animation.frames[0].texture_coords[1]
1258 end
1259 data[o+37] = dx
1260 data[o+38] = dy
1261
1262 # a_start
1263 data[o+39] = sprite.animation_start
1264
1265 # a_loops
1266 data[o+40] = sprite.animation_loops
1267 end
1268
1269 o += float_per_vertex
1270 end
1271
1272 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1273 glBufferSubData(gl_ARRAY_BUFFER, sprite_index*bytes_per_sprite, bytes_per_sprite, data.native_array)
1274
1275 var gl_error = glGetError
1276 assert gl_error == gl_NO_ERROR else print_error gl_error
1277
1278 # Element / indices
1279 #
1280 # 0--1
1281 # | /|
1282 # |/ |
1283 # 2--3
1284
1285 var indices = local_indices_buffer
1286 var io = sprite_index*4
1287 indices[0] = io+0
1288 indices[1] = io+2
1289 indices[2] = io+1
1290 indices[3] = io+1
1291 indices[4] = io+2
1292 indices[5] = io+3
1293
1294 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1295 glBufferSubData(gl_ELEMENT_ARRAY_BUFFER, sprite_index*6*2, 6*2, indices.native_array)
1296
1297 gl_error = glGetError
1298 assert gl_error == gl_NO_ERROR else print_error gl_error
1299 end
1300
1301 # Draw all `sprites`
1302 #
1303 # Call `resize` and `update_sprite` as needed before actual draw operation.
1304 #
1305 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
1306 fun draw
1307 do
1308 if buffer_array == -1 then prepare
1309
1310 assert buffer_array > 0 and buffer_element > 0 else
1311 print_error "Internal error: {self} was destroyed"
1312 end
1313
1314 # Setup
1315 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1316 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1317
1318 # Resize GPU buffers?
1319 var update_everything = false
1320 if sprites.capacity > buffer_capacity then
1321 # Try to defragment first
1322 var moved = sprites.defragment
1323
1324 if sprites.capacity > buffer_capacity then
1325 # Defragmentation wasn't enough, grow
1326 resize
1327
1328 # We must update everything
1329 update_everything = true
1330 for s in sprites.items do if s != null then sprites_to_update.add s
1331 else
1332 # Just update the moved sprites
1333 for s in moved do sprites_to_update.add s
1334 end
1335 else if sprites.available.not_empty then
1336 # Defragment a bit anyway
1337 # TODO defrag only when there's time left on a frame
1338 var moved = sprites.defragment(1)
1339 for s in moved do sprites_to_update.add s
1340 end
1341
1342 # Update GPU sprites data
1343 if sprites_to_update.not_empty or update_everything then
1344 app.perf_clock_sprites.lapse
1345
1346 if update_everything then
1347 for sprite in sprites.items do if sprite != null then
1348 update_sprite(sprite)
1349 end
1350 else
1351 for sprite in sprites_to_update do update_sprite(sprite)
1352 end
1353
1354 sprites_to_update.clear
1355 last_sprite_to_update = null
1356
1357 sys.perfs["gamnit flat gpu update"].add app.perf_clock_sprites.lapse
1358 end
1359
1360 # Update uniforms specific to this context
1361 var texture = texture
1362 app.simple_2d_program.use_texture.uniform texture != null
1363 if texture != null then
1364 glActiveTexture gl_TEXTURE0
1365 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
1366 app.simple_2d_program.texture.uniform 0
1367 end
1368 var gl_error = glGetError
1369 assert gl_error == gl_NO_ERROR else print_error gl_error
1370
1371 var animation = animation_texture
1372 if animation != null then
1373 glActiveTexture gl_TEXTURE1
1374 glBindTexture(gl_TEXTURE_2D, animation.gl_texture)
1375 app.simple_2d_program.animation_texture.uniform 1
1376 end
1377 gl_error = glGetError
1378 assert gl_error == gl_NO_ERROR else print_error gl_error
1379
1380 # Configure attributes, in order:
1381 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*,
1382 # a_fps, a_n_frames, a_coord, a_tex_coord, a_tex_diff, a_start, a_loops
1383
1384 var offset = 0
1385 var p = app.simple_2d_program
1386 var sizeof_gl_float = 4 # sizeof(GL_FLOAT)
1387
1388 var size = 4 # Number of floats
1389 glEnableVertexAttribArray p.translation.location
1390 glVertexAttribPointeri(p.translation.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1391 offset += size * sizeof_gl_float
1392 gl_error = glGetError
1393 assert gl_error == gl_NO_ERROR else print_error gl_error
1394
1395 size = 4
1396 glEnableVertexAttribArray p.color.location
1397 glVertexAttribPointeri(p.color.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1398 offset += size * sizeof_gl_float
1399 gl_error = glGetError
1400 assert gl_error == gl_NO_ERROR else print_error gl_error
1401
1402 size = 1
1403 glEnableVertexAttribArray p.scale.location
1404 glVertexAttribPointeri(p.scale.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1405 offset += size * sizeof_gl_float
1406 gl_error = glGetError
1407 assert gl_error == gl_NO_ERROR else print_error gl_error
1408
1409 size = 4
1410 glEnableVertexAttribArray p.coord.location
1411 glVertexAttribPointeri(p.coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1412 offset += size * sizeof_gl_float
1413 gl_error = glGetError
1414 assert gl_error == gl_NO_ERROR else print_error gl_error
1415
1416 size = 2
1417 glEnableVertexAttribArray p.tex_coord.location
1418 glVertexAttribPointeri(p.tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1419 offset += size * sizeof_gl_float
1420 gl_error = glGetError
1421 assert gl_error == gl_NO_ERROR else print_error gl_error
1422
1423 size = 4
1424 for r in [p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3] do
1425 if r.is_active then
1426 glEnableVertexAttribArray r.location
1427 glVertexAttribPointeri(r.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1428 end
1429 offset += size * sizeof_gl_float
1430 gl_error = glGetError
1431 assert gl_error == gl_NO_ERROR else print_error gl_error
1432 end
1433
1434 size = 1
1435 glEnableVertexAttribArray p.animation_fps.location
1436 glVertexAttribPointeri(p.animation_fps.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1437 offset += size * sizeof_gl_float
1438 gl_error = glGetError
1439 assert gl_error == gl_NO_ERROR else print_error gl_error
1440
1441 size = 1
1442 glEnableVertexAttribArray p.animation_n_frames.location
1443 glVertexAttribPointeri(p.animation_n_frames.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1444 offset += size * sizeof_gl_float
1445 gl_error = glGetError
1446 assert gl_error == gl_NO_ERROR else print_error gl_error
1447
1448 size = 2
1449 glEnableVertexAttribArray p.animation_coord.location
1450 glVertexAttribPointeri(p.animation_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1451 offset += size * sizeof_gl_float
1452 gl_error = glGetError
1453 assert gl_error == gl_NO_ERROR else print_error gl_error
1454
1455 size = 2
1456 glEnableVertexAttribArray p.animation_tex_coord.location
1457 glVertexAttribPointeri(p.animation_tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1458 offset += size * sizeof_gl_float
1459 gl_error = glGetError
1460 assert gl_error == gl_NO_ERROR else print_error gl_error
1461
1462 size = 2
1463 glEnableVertexAttribArray p.animation_tex_diff.location
1464 glVertexAttribPointeri(p.animation_tex_diff.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1465 offset += size * sizeof_gl_float
1466 gl_error = glGetError
1467 assert gl_error == gl_NO_ERROR else print_error gl_error
1468
1469 size = 1
1470 glEnableVertexAttribArray p.animation_start.location
1471 glVertexAttribPointeri(p.animation_start.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1472 offset += size * sizeof_gl_float
1473 gl_error = glGetError
1474 assert gl_error == gl_NO_ERROR else print_error gl_error
1475
1476 size = 1
1477 glEnableVertexAttribArray p.animation_loops.location
1478 glVertexAttribPointeri(p.animation_loops.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1479 offset += size * sizeof_gl_float
1480 gl_error = glGetError
1481 assert gl_error == gl_NO_ERROR else print_error gl_error
1482
1483 # Actual draw
1484 for s in sprites.starts, e in sprites.ends do
1485 var l = e-s
1486 glDrawElementsi(gl_TRIANGLES, l*indices_per_sprite, gl_UNSIGNED_SHORT, 2*s*indices_per_sprite)
1487 gl_error = glGetError
1488 assert gl_error == gl_NO_ERROR else print_error gl_error
1489 end
1490
1491 # Take down
1492 for attr in [p.translation, p.color, p.scale, p.coord, p.tex_coord,
1493 p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3: Attribute] do
1494 if not attr.is_active then continue
1495 glDisableVertexAttribArray(attr.location)
1496 gl_error = glGetError
1497 assert gl_error == gl_NO_ERROR else print_error gl_error
1498 end
1499
1500 glBindBuffer(gl_ARRAY_BUFFER, 0)
1501 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, 0)
1502 gl_error = glGetError
1503 assert gl_error == gl_NO_ERROR else print_error gl_error
1504 end
1505 end
1506
1507 # Representation of sprite data on the GPU
1508 #
1509 # The main purpose of this class is to optimize the use of contiguous
1510 # space in GPU memory. Each contiguous memory block can be drawn in a
1511 # single call. The starts index of each block is kept by `starts,
1512 # and the end + 1 by `ends`.
1513 #
1514 # The data can be compressed by a call to `defragment`.
1515 #
1516 # ~~~
1517 # intrude import gamnit::flat
1518 #
1519 # var array = new GroupedArray[String]
1520 # assert array.to_s == ""
1521 #
1522 # array.add "a"
1523 # array.add "b"
1524 # array.add "c"
1525 # array.add "d"
1526 # array.add "e"
1527 # array.add "f"
1528 # assert array.to_s == "[a,b,c,d,e,f]"
1529 # assert array.capacity == 6
1530 #
1531 # array.remove "a"
1532 # assert array.to_s == "[b,c,d,e,f]"
1533 #
1534 # array.remove "b"
1535 # assert array.to_s == "[c,d,e,f]"
1536 #
1537 # array.remove "f"
1538 # assert array.to_s == "[c,d,e]"
1539 #
1540 # array.remove "d"
1541 # assert array.to_s == "[c][e]"
1542 #
1543 # array.add "A"
1544 # assert array.to_s == "[A][c][e]"
1545 #
1546 # array.add "B"
1547 # assert array.to_s == "[A,B,c][e]"
1548 #
1549 # array.remove "e"
1550 # assert array.to_s == "[A,B,c]"
1551 #
1552 # array.add "D"
1553 # assert array.to_s == "[A,B,c,D]"
1554 #
1555 # array.add "E"
1556 # assert array.to_s == "[A,B,c,D,E]"
1557 # assert array.capacity == 6
1558 # assert array.length == 5
1559 #
1560 # array.remove "A"
1561 # array.remove "B"
1562 # array.remove "c"
1563 # array.remove "D"
1564 # array.remove "E"
1565 # assert array.to_s == ""
1566 #
1567 # array.add "a"
1568 # assert array.to_s == "[a]"
1569 # ~~~
1570 private class GroupedArray[E]
1571
1572 # Memory with actual objects, and null in empty slots
1573 var items = new Array[nullable E]
1574
1575 # Number of items in the array
1576 var length = 0
1577
1578 # Number of item slots in the array
1579 fun capacity: Int do return items.length
1580
1581 # List of available slots
1582 var available = new MinHeap[Int].default
1583
1584 # Start index of filled chunks
1585 var starts = new List[Int]
1586
1587 # Index of the spots after filled chunks
1588 var ends = new List[Int]
1589
1590 # Add `item` to the first available slot and return its index
1591 fun add(item: E): Int
1592 do
1593 length += 1
1594
1595 if available.not_empty then
1596 # starts & ends can't be empty
1597
1598 var i = available.take
1599 items[i] = item
1600
1601 if i == starts.first - 1 then
1602 # slot 0 free, 1 taken
1603 starts.first -= 1
1604 else if i == 0 then
1605 # slot 0 and more free
1606 starts.unshift 0
1607 ends.unshift 1
1608 else if starts.length >= 2 and ends.first + 1 == starts[1] then
1609 # merge 2 chunks
1610 ends.remove_at 0
1611 starts.remove_at 1
1612 else
1613 # at end of first chunk
1614 ends.first += 1
1615 end
1616 return i
1617 end
1618
1619 items.add item
1620 if ends.is_empty then
1621 starts.add 0
1622 ends.add 1
1623 else ends.last += 1
1624 return ends.last - 1
1625 end
1626
1627 # Remove the first instance of `item`
1628 fun remove(item: E)
1629 do
1630 var index = items.index_of(item)
1631 remove_at(item, index)
1632 end
1633
1634 # Remove `item` at `index`
1635 fun remove_at(item: E, index: Int)
1636 do
1637 var i = index
1638 length -= 1
1639 items[i] = null
1640
1641 var ii = 0
1642 for s in starts, e in ends do
1643 if s <= i and i < e then
1644 if s == e-1 then
1645 # single item chunk
1646 starts.remove_at ii
1647 ends.remove_at ii
1648
1649 if starts.is_empty then
1650 items.clear
1651 available.clear
1652 return
1653 end
1654 else if e-1 == i then
1655 # last item of chunk
1656 ends[ii] -= 1
1657
1658 else if s == i then
1659 # first item of chunk
1660 starts[ii] += 1
1661 else
1662 # break up chunk
1663 ends.insert(ends[ii], ii+1)
1664 ends[ii] = i
1665 starts.insert(i+1, ii+1)
1666 end
1667
1668 available.add i
1669 return
1670 end
1671 ii += 1
1672 end
1673
1674 abort
1675 end
1676
1677 # Defragment and compress everything into a single chunks beginning at 0
1678 #
1679 # Returns the elements that moved as a list.
1680 #
1681 # ~~~
1682 # intrude import gamnit::flat
1683 #
1684 # var array = new GroupedArray[String]
1685 # array.add "a"
1686 # array.add "b"
1687 # array.add "c"
1688 # array.add "d"
1689 # array.remove "c"
1690 # array.remove "a"
1691 # assert array.to_s == "[b][d]"
1692 #
1693 # var moved = array.defragment
1694 # assert moved.to_s == "[d]"
1695 # assert array.to_s == "[d,b]"
1696 # assert array.length == 2
1697 # assert array.capacity == 2
1698 #
1699 # array.add "e"
1700 # array.add "f"
1701 # assert array.to_s == "[d,b,e,f]"
1702 # ~~~
1703 fun defragment(max: nullable Int): Array[E]
1704 do
1705 app.perf_clock_sprites.lapse
1706 max = max or else length
1707
1708 var moved = new Array[E]
1709 while max > 0 and (starts.length > 1 or starts.first != 0) do
1710 var i = ends.last - 1
1711 var e = items[i]
1712 assert e != null
1713 remove e
1714 add e
1715 moved.add e
1716 max -= 1
1717 end
1718
1719 if starts.length == 1 and starts.first == 0 then
1720 for i in [length..capacity[ do items.pop
1721 available.clear
1722 end
1723
1724 sys.perfs["gamnit flat gpu defrag"].add app.perf_clock_sprites.lapse
1725 return moved
1726 end
1727
1728 redef fun to_s
1729 do
1730 var ss = new Array[String]
1731 for s in starts, e in ends do
1732 ss.add "["
1733 for i in [s..e[ do
1734 var item: nullable Object = items[i]
1735 if item == null then item = "null"
1736 ss.add item.to_s
1737 if i != e-1 then ss.add ","
1738 end
1739 ss.add "]"
1740 end
1741 return ss.join
1742 end
1743 end
1744
1745 # Optimized `GroupedArray` to use `Sprite::context_index` and avoid using `index_of`
1746 private class GroupedSprites
1747 super GroupedArray[Sprite]
1748
1749 redef fun add(item)
1750 do
1751 var index = super
1752 item.context_index = index
1753 return index
1754 end
1755
1756 redef fun remove(item) do remove_at(item, item.context_index)
1757 end
1758
1759 redef class GLfloatArray
1760 private fun fill_from_matrix(matrix: Matrix, dst_offset: nullable Int)
1761 do
1762 dst_offset = dst_offset or else add_index
1763 var mat_len = matrix.width*matrix.height
1764 assert length >= mat_len + dst_offset
1765 native_array.fill_from_matrix_native(matrix.items, dst_offset, mat_len)
1766 add_index += mat_len
1767 end
1768 end
1769
1770 redef class NativeGLfloatArray
1771 private fun fill_from_matrix_native(matrix: matrix::NativeDoubleArray, dst_offset, len: Int) `{
1772 int i;
1773 for (i = 0; i < len; i ++)
1774 self[i+dst_offset] = (GLfloat)matrix[i];
1775 `}
1776 end
1777
1778 redef class Sys
1779 private var sprite_draw_order_sorter = new DrawOrderComparator is lazy
1780 end
1781
1782 # Sort `SpriteContext` by their `draw_order`
1783 private class DrawOrderComparator
1784 super Comparator
1785
1786 # This class can't set COMPARED because
1787 # `the public property cannot contain the private type...`
1788 #redef type COMPARED: SpriteContext
1789
1790 # Require: `a isa SpriteContext and b isa SpriteContext`
1791 redef fun compare(a, b)
1792 do return a.as(SpriteContext).draw_order <=> b.as(SpriteContext).draw_order
1793 end