gamnit: fix name of parameters visible in free constructor
[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 frame_core_ui_sprites display
403 display.flip
404
405 ui_sprites.remove splash
406 end
407
408 # ---
409 # Support and implementation
410
411 # Main clock used to count each frame `dt`, lapsed for `update` only
412 private var clock = new Clock is lazy
413
414 # Performance clock to for `frame_core_draw` operations
415 private var perf_clock_main = new Clock
416
417 # Second performance clock for smaller operations
418 private var perf_clock_sprites = new Clock is lazy
419
420 redef fun on_create
421 do
422 super
423
424 var display = display
425 assert display != null
426
427 var gl_error = glGetError
428 assert gl_error == gl_NO_ERROR else print_error gl_error
429
430 # Prepare program
431 var program = simple_2d_program
432 program.compile_and_link
433
434 var gamnit_error = program.error
435 assert gamnit_error == null else print_error gamnit_error
436
437 # Enable blending
438 gl.capabilities.blend.enable
439 glBlendFunc(gl_ONE, gl_ONE_MINUS_SRC_ALPHA)
440
441 # Enable depth test
442 gl.capabilities.depth_test.enable
443 glDepthFunc gl_LEQUAL
444 glDepthMask true
445
446 # Prepare viewport and background color
447 glViewport(0, 0, display.width, display.height)
448 glClearColor(0.0, 0.0, 0.0, 1.0)
449
450 gl_error = glGetError
451 assert gl_error == gl_NO_ERROR else print_error gl_error
452
453 # Prepare to draw
454 for tex in all_root_textures do
455 tex.load
456 gamnit_error = tex.error
457 if gamnit_error != null then print_error gamnit_error
458
459 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
460 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
461 end
462 end
463
464 redef fun on_stop
465 do
466 # Clean up
467 simple_2d_program.delete
468
469 # Close gamnit
470 var display = display
471 if display != null then display.close
472 end
473
474 redef fun on_resize(display)
475 do
476 super
477
478 world_camera.mvp_matrix_cache = null
479 ui_camera.mvp_matrix_cache = null
480
481 # Update all sprites in the UI
482 for sprite in ui_sprites do sprite.needs_update
483 end
484
485 redef fun frame_core(display)
486 do
487 # Check errors
488 var gl_error = glGetError
489 assert gl_error == gl_NO_ERROR else print_error gl_error
490
491 # Update game logic and set sprites
492 perf_clock_main.lapse
493 var dt = clock.lapse.to_f
494 update dt
495 frame_dt = dt
496 sys.perfs["gamnit flat update client"].add perf_clock_main.lapse
497
498 # Draw and flip screen
499 frame_core_draw display
500 display.flip
501
502 # Check errors
503 gl_error = glGetError
504 assert gl_error == gl_NO_ERROR else print_error gl_error
505 end
506
507 private var frame_dt = 0.0
508
509 # Draw the whole screen, all `glDraw...` calls should be executed here
510 protected fun frame_core_draw(display: GamnitDisplay)
511 do
512 frame_core_dynamic_resolution_before display
513
514 perf_clock_main.lapse
515 frame_core_world_sprites display
516 perfs["gamnit flat world_sprites"].add perf_clock_main.lapse
517
518 frame_core_ui_sprites display
519 perfs["gamnit flat ui_sprites"].add perf_clock_main.lapse
520
521 frame_core_dynamic_resolution_after display
522 end
523
524 private fun frame_core_sprites(display: GamnitDisplay, sprite_set: SpriteSet, camera: Camera)
525 do
526 var simple_2d_program = app.simple_2d_program
527 simple_2d_program.use
528 simple_2d_program.mvp.uniform camera.mvp_matrix
529
530 sprite_set.time += frame_dt*sprite_set.time_mod
531 simple_2d_program.time.uniform sprite_set.time
532
533 # draw
534 sprite_set.draw
535 end
536
537 # Draw world sprites from `sprites`
538 protected fun frame_core_world_sprites(display: GamnitDisplay)
539 do
540 frame_core_sprites(display, sprites, world_camera)
541 end
542
543 # Draw UI sprites from `ui_sprites`
544 protected fun frame_core_ui_sprites(display: GamnitDisplay)
545 do
546 # Reset only the depth buffer
547 glClear gl_DEPTH_BUFFER_BIT
548
549 frame_core_sprites(display, ui_sprites, ui_camera)
550 end
551 end
552
553 redef class Texture
554
555 # Vertices coordinates of the base geometry
556 #
557 # Defines the default width and height of related sprites.
558 private var vertices: Array[Float] is lazy do
559 var w = width
560 var h = height
561 return [-0.5*w, 0.5*h, 0.0,
562 0.5*w, 0.5*h, 0.0,
563 -0.5*w, -0.5*h, 0.0,
564 0.5*w, -0.5*h, 0.0]
565 end
566
567 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
568 private var texture_coords: Array[Float] is lazy do
569 var l = offset_left
570 var r = offset_right
571 var b = offset_bottom
572 var t = offset_top
573 return [l, t,
574 r, t,
575 l, b,
576 r, b]
577 end
578
579 # Coordinates of this texture on the `root` texture, inverting the X axis
580 private var texture_coords_invert_x: Array[Float] is lazy do
581 var l = offset_left
582 var r = offset_right
583 var b = offset_bottom
584 var t = offset_top
585 return [r, t,
586 l, t,
587 r, b,
588 l, b]
589 end
590
591 # Convert to a sprite animation at `fps` speed with `x` or `y` frames
592 #
593 # The arguments `x` and `y` set the number of frames in the texture.
594 # Use `x` for an horizontal arrangement or `y` for vertical.
595 # One and only one of the arguments must be different than 0,
596 # as an animation can only be on a line and cannot wrap.
597 fun to_animation(fps: Float, x, y: Int): Animation
598 do
599 assert (x == 0) != (y == 0)
600
601 var n_frames = x.max(y)
602 var frames = new Array[Texture]
603
604 var dx = (x/n_frames).to_f/n_frames.to_f
605 var dy = (y/n_frames).to_f/n_frames.to_f
606 var w = if x == 0 then 1.0 else dx
607 var h = if y == 0 then 1.0 else dy
608 var left = 0.0
609 var top = 0.0
610 for i in n_frames.times do
611 frames.add new RelativeSubtexture(root, left, top, left+w, top+h)
612 left += dx
613 top += dy
614 end
615
616 return new Animation(frames, fps)
617 end
618 end
619
620 # Graphic program to display simple models with a texture, translation, rotation and scale
621 private class Simple2dProgram
622 super GamnitProgramFromSource
623
624 redef var vertex_shader_source = """
625 // Vertex coordinates
626 attribute vec4 coord;
627
628 // Vertex color tint
629 attribute vec4 color;
630
631 // Vertex translation
632 attribute vec4 translation;
633
634 // Vertex scaling
635 attribute float scale;
636
637 // Vertex coordinates on textures
638 attribute vec2 tex_coord;
639
640 // Model view projection matrix
641 uniform mat4 mvp;
642
643 // Current world time, in seconds
644 uniform float time;
645
646 // Rotation matrix
647 attribute vec4 rotation_row0;
648 attribute vec4 rotation_row1;
649 attribute vec4 rotation_row2;
650 attribute vec4 rotation_row3;
651
652 // Animation speed, frames per seconds
653 attribute float a_fps;
654
655 // Number of frames in the animation
656 attribute float a_n_frames;
657
658 // World coordinate of the animation (for aspect ratio)
659 attribute vec2 a_coord;
660
661 // Animation texture coordinates of the first frame
662 attribute vec2 a_tex_coord;
663
664 // Animation texture coordinates difference between frames
665 attribute vec2 a_tex_diff;
666
667 // Animation start time, in reference to `time`
668 attribute float a_start;
669
670 // Number of loops to play of the animation
671 attribute float a_loops;
672
673 mat4 rotation()
674 {
675 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
676 }
677
678 // Output to the fragment shader
679 varying vec4 v_color;
680 varying vec2 v_coord;
681
682 // Is there an active animation?
683 varying float v_animated;
684
685 void main()
686 {
687 vec3 c; // coords
688
689 float end = a_start + a_loops/a_fps*a_n_frames;
690 if (a_fps != 0.0 && (a_loops == -1.0 || time < end)) {
691 // in animation
692 float frame = mod(floor((time-a_start)*a_fps), a_n_frames);
693 v_coord = a_tex_coord + a_tex_diff*frame;
694 c = vec3(a_coord, coord.z);
695 v_animated = 1.0;
696 } else {
697 // static
698 v_coord = tex_coord;
699 c = coord.xyz;
700 v_animated = 0.0;
701 }
702
703 gl_Position = (vec4(c * scale, 1.0) * rotation() + translation)* mvp;
704 v_color = vec4(color.rgb*color.a, color.a);
705 }
706 """ @ glsl_vertex_shader
707
708 redef var fragment_shader_source = """
709 precision mediump float;
710
711 // Does this object use a texture?
712 uniform bool use_texture;
713
714 // Texture to apply on this object
715 uniform sampler2D texture0;
716
717 // Texture to apply on this object
718 uniform sampler2D animation;
719
720 // Input from the vertex shader
721 varying vec4 v_color;
722 varying vec2 v_coord;
723 varying float v_animated;
724
725 void main()
726 {
727 if (v_animated > 0.5) {
728 gl_FragColor = v_color * texture2D(animation, v_coord);
729 if (gl_FragColor.a <= 0.01) discard;
730 } else if (use_texture) {
731 gl_FragColor = v_color * texture2D(texture0, v_coord);
732 if (gl_FragColor.a <= 0.01) discard;
733 } else {
734 gl_FragColor = v_color;
735 }
736 }
737 """ @ glsl_fragment_shader
738
739 # Vertices coordinates
740 var coord = attributes["coord"].as(AttributeVec4) is lazy
741
742 # Should this program use the texture `texture`?
743 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
744
745 # Visible texture unit
746 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
747
748 # Coordinates on the textures, per vertex
749 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
750
751 # Color tint per vertex
752 var color = attributes["color"].as(AttributeVec4) is lazy
753
754 # Translation applied to each vertex
755 var translation = attributes["translation"].as(AttributeVec4) is lazy
756
757 # Rotation matrix, row 0
758 var rotation_row0 = attributes["rotation_row0"].as(AttributeVec4) is lazy
759
760 # Rotation matrix, row 1
761 var rotation_row1 = attributes["rotation_row1"].as(AttributeVec4) is lazy
762
763 # Rotation matrix, row 2
764 var rotation_row2 = attributes["rotation_row2"].as(AttributeVec4) is lazy
765
766 # Rotation matrix, row 3
767 var rotation_row3 = attributes["rotation_row3"].as(AttributeVec4) is lazy
768
769 # Scaling per vertex
770 var scale = attributes["scale"].as(AttributeFloat) is lazy
771
772 # Model view projection matrix
773 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
774
775 # World time, in seconds
776 var time = uniforms["time"].as(UniformFloat) is lazy
777
778 # ---
779 # Animations
780
781 # Texture of all the frames of the animation
782 var animation_texture = uniforms["animation"].as(UniformSampler2D) is lazy
783
784 # Frame per second of the animation
785 var animation_fps = attributes["a_fps"].as(AttributeFloat) is lazy
786
787 # Number of frames in the animation
788 var animation_n_frames = attributes["a_n_frames"].as(AttributeFloat) is lazy
789
790 # Coordinates of each frame (mush be shared by all frames)
791 var animation_coord = attributes["a_coord"].as(AttributeVec2) is lazy
792
793 # Texture coordinates of the first frame
794 var animation_tex_coord = attributes["a_tex_coord"].as(AttributeVec2) is lazy
795
796 # Coordinate difference between each frame
797 var animation_tex_diff = attributes["a_tex_diff"].as(AttributeVec2) is lazy
798
799 # Animation start time, in seconds and in reference to `dt`
800 var animation_start = attributes["a_start"].as(AttributeFloat) is lazy
801
802 # Number of loops of the animation, -1 for infinite
803 var animation_loops = attributes["a_loops"].as(AttributeFloat) is lazy
804 end
805
806 redef class Point3d[N]
807 # ---
808 # Associate each point to its sprites
809
810 private var sprites: nullable Array[Sprite] = null
811
812 private fun sprites_add(sprite: Sprite)
813 do
814 var sprites = sprites
815 if sprites == null then
816 sprites = new Array[Sprite]
817 self.sprites = sprites
818 end
819 sprites.add sprite
820 end
821
822 private fun sprites_remove(sprite: Sprite)
823 do
824 var sprites = sprites
825 assert sprites != null
826 sprites.remove sprite
827 end
828
829 # ---
830 # Notify `sprites` on attribute modification
831
832 private fun needs_update
833 do
834 var sprites = sprites
835 if sprites != null then for s in sprites do s.needs_update
836 end
837
838 redef fun x=(v)
839 do
840 if isset _x and v != x then needs_update
841 super
842 end
843
844 redef fun y=(v)
845 do
846 if isset _y and v != y then needs_update
847 super
848 end
849
850 redef fun z=(v)
851 do
852 if isset _z and v != z then needs_update
853 super
854 end
855 end
856
857 redef class OffsetPoint3d
858 redef fun x=(v)
859 do
860 if isset _x and v != x then needs_update
861 super
862 end
863
864 redef fun y=(v)
865 do
866 if isset _y and v != y then needs_update
867 super
868 end
869
870 redef fun z=(v)
871 do
872 if isset _z and v != z then needs_update
873 super
874 end
875 end
876
877 # Set of sprites sorting them into different `SpriteContext`
878 class SpriteSet
879 super HashSet[Sprite]
880
881 # Animation speed multiplier (0.0 to pause, 1.0 for normal speed, etc.)
882 var time_mod = 1.0 is writable
883
884 # Seconds elapsed since the launch of the program, in world time responding to `time_mod`
885 var time = 0.0
886
887 # Map texture then static vs dynamic to a `SpriteContext`
888 private var contexts_map = new HashMap4[RootTexture, nullable RootTexture, Bool, Int, Array[SpriteContext]]
889
890 # Contexts in `contexts_map`, sorted by draw order
891 private var contexts_items = new Array[SpriteContext]
892
893 # Sprites needing resorting in `contexts_map`
894 private var sprites_to_remap = new Array[Sprite]
895
896 # Add a sprite to the appropriate context
897 private fun map_sprite(sprite: Sprite)
898 do
899 assert sprite.context == null else print_error "Sprite {sprite} belongs to another SpriteSet"
900
901 # Sort by texture and animation texture
902 var texture = sprite.texture.root
903 var animation = sprite.animation
904 var animation_texture = if animation != null then
905 animation.frames.first.root else null
906 var draw_order = sprite.draw_order
907 var contexts = contexts_map[texture, animation_texture, sprite.static, draw_order]
908
909 var context = null
910 if contexts != null then
911 for c in contexts.reverse_iterator do
912 var size = c.sprites.length + 1
913 if size * 4 <= 0xffff then
914 context = c
915 break
916 end
917 end
918 end
919
920 if context == null then
921 var usage = if sprite.static then gl_STATIC_DRAW else gl_DYNAMIC_DRAW
922 context = new SpriteContext(texture, animation_texture, usage, draw_order)
923
924 if contexts == null then
925 contexts = new Array[SpriteContext]
926 contexts_map[texture, animation_texture, sprite.static, draw_order] = contexts
927 end
928
929 contexts.add context
930
931 contexts_items.add context
932 sprite_draw_order_sorter.sort(contexts_items)
933 end
934
935 context.sprites.add sprite
936 context.sprites_to_update.add sprite
937 context.last_sprite_to_update = sprite
938
939 sprite.context = context
940 sprite.sprite_set = self
941
942 if animation != null and sprite.animation_start == -1.0 then
943 # Start animation
944 sprite.animation_start = time
945 end
946 end
947
948 # Remove a sprite from its context
949 private fun unmap_sprite(sprite: Sprite)
950 do
951 var context = sprite.context
952 assert context != null
953 context.sprites.remove sprite
954
955 sprite.context = null
956 sprite.sprite_set = null
957 end
958
959 # Draw all sprites by all contexts
960 private fun draw
961 do
962 # Remap sprites that may need to change context
963 for sprite in sprites_to_remap do
964
965 # Skip if it was removed from this set after being modified
966 if sprite.context != self then continue
967
968 unmap_sprite sprite
969 map_sprite sprite
970 end
971 sprites_to_remap.clear
972
973 # Sort by draw order
974 for context in contexts_items do context.draw
975 end
976
977 redef fun add(e)
978 do
979 if contexts_items.has(e.context) then return
980 map_sprite e
981 super
982 end
983
984 redef fun remove(e)
985 do
986 super
987 if e isa Sprite then unmap_sprite e
988 end
989
990 redef fun remove_all(e)
991 do
992 if not has(e) then return
993 remove e
994 end
995
996 redef fun clear
997 do
998 for sprite in self do
999 sprite.context = null
1000 sprite.sprite_set = null
1001 end
1002 super
1003 for c in contexts_items do c.destroy
1004 contexts_map.clear
1005 contexts_items.clear
1006 end
1007 end
1008
1009 # Context for calls to `glDrawElements`
1010 #
1011 # Each context has only one `texture` and `usage`, but many sprites.
1012 private class SpriteContext
1013
1014 # ---
1015 # Context config and state
1016
1017 # Only root texture drawn by this context
1018 var texture: nullable RootTexture
1019
1020 # Only animation texture drawn by this context
1021 var animation_texture: nullable RootTexture
1022
1023 # OpenGL ES usage of `buffer_array` and `buffer_element`
1024 var usage: GLBufferUsage
1025
1026 # Draw order shared by all `sprites`
1027 var draw_order: Int
1028
1029 # Sprites drawn by this context
1030 var sprites = new GroupedSprites
1031
1032 # Sprites to update since last `draw`
1033 var sprites_to_update = new Set[Sprite]
1034
1035 # Cache of the last `Sprite` added to `sprites_to_update` since the last call to `draw`
1036 var last_sprite_to_update: nullable Sprite = null
1037
1038 # Sprites that have been update and for which `needs_update` can be set to false
1039 var updated_sprites = new Array[Sprite]
1040
1041 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
1042 #
1043 # Require: `resize_ratio >= 1.0`
1044 var resize_ratio = 1.2
1045
1046 # ---
1047 # OpenGL ES data
1048
1049 # OpenGL ES buffer name for vertex data
1050 var buffer_array: Int = -1
1051
1052 # OpenGL ES buffer name for indices
1053 var buffer_element: Int = -1
1054
1055 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
1056 var buffer_capacity = 0
1057
1058 # C buffers used to pass the data of a single sprite
1059 var local_data_buffer = new GLfloatArray(float_per_vertex*4) is lazy
1060 var local_indices_buffer = new CUInt16Array(indices_per_sprite) is lazy
1061
1062 # ---
1063 # Constants
1064
1065 # Number of GL_FLOAT per vertex of `Simple2dProgram`
1066 var float_per_vertex: Int is lazy do
1067 return 4 + 4 + 4 + # vec4 translation, vec4 color, vec4 coord,
1068 1 + 2 + 4*4 + # float scale, vec2 tex_coord, vec4 rotation_row*,
1069 1 + 1 + # float a_fps, float a_n_frames,
1070 2 + 2 + 2 + # vec2 a_coord, vec2 a_tex_coord, vec2 a_tex_diff,
1071 1 + 1 # float a_start, float a_loops
1072 end
1073
1074 # Number of bytes per vertex of `Simple2dProgram`
1075 var bytes_per_vertex: Int is lazy do
1076 var fs = 4 # sizeof(GL_FLOAT)
1077 return fs * float_per_vertex
1078 end
1079
1080 # Number of bytes per sprite
1081 var bytes_per_sprite: Int is lazy do return bytes_per_vertex * 4
1082
1083 # Number of vertex indices per sprite draw call (2 triangles)
1084 var indices_per_sprite = 6
1085
1086 # ---
1087 # Main services
1088
1089 # Allocate `buffer_array` and `buffer_element`
1090 fun prepare
1091 do
1092 var bufs = glGenBuffers(2)
1093 buffer_array = bufs[0]
1094 buffer_element = bufs[1]
1095
1096 var gl_error = glGetError
1097 assert gl_error == gl_NO_ERROR else print_error gl_error
1098 end
1099
1100 # Destroy `buffer_array` and `buffer_element`
1101 fun destroy
1102 do
1103 glDeleteBuffers([buffer_array, buffer_element])
1104 var gl_error = glGetError
1105 assert gl_error == gl_NO_ERROR else print_error gl_error
1106
1107 buffer_array = -1
1108 buffer_element = -1
1109 end
1110
1111 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
1112 fun resize
1113 do
1114 app.perf_clock_sprites.lapse
1115
1116 # Allocate a bit more space
1117 var capacity = (sprites.capacity.to_f * resize_ratio).to_i
1118
1119 var array_bytes = capacity * bytes_per_sprite
1120 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1121 assert glIsBuffer(buffer_array)
1122 glBufferData(gl_ARRAY_BUFFER, array_bytes, new Pointer.nul, usage)
1123 var gl_error = glGetError
1124 assert gl_error == gl_NO_ERROR else print_error gl_error
1125
1126 # GL_TRIANGLES 6 vertices * sprite
1127 var n_indices = capacity * indices_per_sprite
1128 var ius = 2 # sizeof(GL_UNSIGNED_SHORT)
1129 var element_bytes = n_indices * ius
1130 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1131 assert glIsBuffer(buffer_element)
1132 glBufferData(gl_ELEMENT_ARRAY_BUFFER, element_bytes, new Pointer.nul, usage)
1133 gl_error = glGetError
1134 assert gl_error == gl_NO_ERROR else print_error gl_error
1135
1136 buffer_capacity = capacity
1137
1138 sys.perfs["gamnit flat gpu resize"].add app.perf_clock_sprites.lapse
1139 end
1140
1141 # Update GPU data of `sprite`
1142 fun update_sprite(sprite: Sprite)
1143 do
1144 var context = sprite.context
1145 if context != self then return
1146
1147 var sprite_index = sprite.context_index
1148 assert sprite_index != -1
1149
1150 # Vertices data
1151
1152 var data = local_data_buffer
1153 var o = 0
1154 for v in [0..4[ do
1155 # vec4 translation
1156 data[o+ 0] = sprite.center.x
1157 data[o+ 1] = sprite.center.y
1158 data[o+ 2] = sprite.center.z
1159 data[o+ 3] = 0.0
1160
1161 # vec4 color
1162 data[o+ 4] = sprite.tint[0]
1163 data[o+ 5] = sprite.tint[1]
1164 data[o+ 6] = sprite.tint[2]
1165 data[o+ 7] = sprite.tint[3]
1166
1167 # float scale
1168 data[o+ 8] = sprite.scale
1169
1170 # vec4 coord
1171 data[o+ 9] = sprite.texture.vertices[v*3+0]
1172 data[o+10] = sprite.texture.vertices[v*3+1]
1173 data[o+11] = sprite.texture.vertices[v*3+2]
1174 data[o+12] = 0.0
1175
1176 # vec2 tex_coord
1177 var texture = texture
1178 if texture != null then
1179 var tc = if sprite.invert_x then
1180 sprite.texture.texture_coords_invert_x
1181 else sprite.texture.texture_coords
1182 data[o+13] = tc[v*2+0]
1183 data[o+14] = tc[v*2+1]
1184 end
1185
1186 # mat4 rotation
1187 var rot
1188 if sprite.rotation == 0.0 then
1189 # Cache the matrix at no rotation
1190 rot = once new Matrix.identity(4)
1191 else
1192 rot = new Matrix.rotation(sprite.rotation, 0.0, 0.0, 1.0)
1193 end
1194 data.fill_from_matrix(rot, o+15)
1195
1196 var animation = sprite.animation
1197 if animation == null then
1198 for i in [31..40] do data[o+i] = 0.0
1199 else
1200 # a_fps
1201 data[o+31] = animation.fps
1202
1203 # a_n_frames
1204 data[o+32] = animation.frames.length.to_f
1205
1206 # a_coord
1207 data[o+33] = animation.frames.first.vertices[v*3+0]
1208 data[o+34] = animation.frames.first.vertices[v*3+1]
1209
1210 # a_tex_coord
1211 var tc = if sprite.invert_x then
1212 animation.frames.first.texture_coords_invert_x
1213 else animation.frames.first.texture_coords
1214 data[o+35] = tc[v*2]
1215 data[o+36] = tc[v*2+1]
1216
1217 # a_tex_diff
1218 var dx = 0.0
1219 var dy = 0.0
1220 if animation.frames.length > 1 then
1221 dx = animation.frames[1].texture_coords[0] - animation.frames[0].texture_coords[0]
1222 dy = animation.frames[1].texture_coords[1] - animation.frames[0].texture_coords[1]
1223 end
1224 data[o+37] = dx
1225 data[o+38] = dy
1226
1227 # a_start
1228 data[o+39] = sprite.animation_start
1229
1230 # a_loops
1231 data[o+40] = sprite.animation_loops
1232 end
1233
1234 o += float_per_vertex
1235 end
1236
1237 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1238 glBufferSubData(gl_ARRAY_BUFFER, sprite_index*bytes_per_sprite, bytes_per_sprite, data.native_array)
1239
1240 var gl_error = glGetError
1241 assert gl_error == gl_NO_ERROR else print_error gl_error
1242
1243 # Element / indices
1244 #
1245 # 0--1
1246 # | /|
1247 # |/ |
1248 # 2--3
1249
1250 var indices = local_indices_buffer
1251 var io = sprite_index*4
1252 indices[0] = io+0
1253 indices[1] = io+2
1254 indices[2] = io+1
1255 indices[3] = io+1
1256 indices[4] = io+2
1257 indices[5] = io+3
1258
1259 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1260 glBufferSubData(gl_ELEMENT_ARRAY_BUFFER, sprite_index*6*2, 6*2, indices.native_array)
1261
1262 gl_error = glGetError
1263 assert gl_error == gl_NO_ERROR else print_error gl_error
1264 end
1265
1266 # Draw all `sprites`
1267 #
1268 # Call `resize` and `update_sprite` as needed before actual draw operation.
1269 #
1270 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
1271 fun draw
1272 do
1273 if buffer_array == -1 then prepare
1274
1275 assert buffer_array > 0 and buffer_element > 0 else
1276 print_error "Internal error: {self} was destroyed"
1277 end
1278
1279 # Setup
1280 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
1281 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
1282
1283 # Resize GPU buffers?
1284 var update_everything = false
1285 if sprites.capacity > buffer_capacity then
1286 # Try to defragment first
1287 var moved = sprites.defragment
1288
1289 if sprites.capacity > buffer_capacity then
1290 # Defragmentation wasn't enough, grow
1291 resize
1292
1293 # We must update everything
1294 update_everything = true
1295 for s in sprites.items do if s != null then sprites_to_update.add s
1296 else
1297 # Just update the moved sprites
1298 for s in moved do sprites_to_update.add s
1299 end
1300 else if sprites.available.not_empty then
1301 # Defragment a bit anyway
1302 # TODO defrag only when there's time left on a frame
1303 var moved = sprites.defragment(1)
1304 for s in moved do sprites_to_update.add s
1305 end
1306
1307 # Update GPU sprites data
1308 if sprites_to_update.not_empty or update_everything then
1309 app.perf_clock_sprites.lapse
1310
1311 if update_everything then
1312 for sprite in sprites.items do if sprite != null then
1313 update_sprite(sprite)
1314 end
1315 else
1316 for sprite in sprites_to_update do update_sprite(sprite)
1317 end
1318
1319 sprites_to_update.clear
1320 last_sprite_to_update = null
1321
1322 sys.perfs["gamnit flat gpu update"].add app.perf_clock_sprites.lapse
1323 end
1324
1325 # Update uniforms specific to this context
1326 var texture = texture
1327 app.simple_2d_program.use_texture.uniform texture != null
1328 if texture != null then
1329 glActiveTexture gl_TEXTURE0
1330 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
1331 app.simple_2d_program.texture.uniform 0
1332 end
1333 var gl_error = glGetError
1334 assert gl_error == gl_NO_ERROR else print_error gl_error
1335
1336 var animation = animation_texture
1337 if animation != null then
1338 glActiveTexture gl_TEXTURE1
1339 glBindTexture(gl_TEXTURE_2D, animation.gl_texture)
1340 app.simple_2d_program.animation_texture.uniform 1
1341 end
1342 gl_error = glGetError
1343 assert gl_error == gl_NO_ERROR else print_error gl_error
1344
1345 # Configure attributes, in order:
1346 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*,
1347 # a_fps, a_n_frames, a_coord, a_tex_coord, a_tex_diff, a_start, a_loops
1348
1349 var offset = 0
1350 var p = app.simple_2d_program
1351 var sizeof_gl_float = 4 # sizeof(GL_FLOAT)
1352
1353 var size = 4 # Number of floats
1354 glEnableVertexAttribArray p.translation.location
1355 glVertexAttribPointeri(p.translation.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1356 offset += size * sizeof_gl_float
1357 gl_error = glGetError
1358 assert gl_error == gl_NO_ERROR else print_error gl_error
1359
1360 size = 4
1361 glEnableVertexAttribArray p.color.location
1362 glVertexAttribPointeri(p.color.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1363 offset += size * sizeof_gl_float
1364 gl_error = glGetError
1365 assert gl_error == gl_NO_ERROR else print_error gl_error
1366
1367 size = 1
1368 glEnableVertexAttribArray p.scale.location
1369 glVertexAttribPointeri(p.scale.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1370 offset += size * sizeof_gl_float
1371 gl_error = glGetError
1372 assert gl_error == gl_NO_ERROR else print_error gl_error
1373
1374 size = 4
1375 glEnableVertexAttribArray p.coord.location
1376 glVertexAttribPointeri(p.coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1377 offset += size * sizeof_gl_float
1378 gl_error = glGetError
1379 assert gl_error == gl_NO_ERROR else print_error gl_error
1380
1381 size = 2
1382 glEnableVertexAttribArray p.tex_coord.location
1383 glVertexAttribPointeri(p.tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1384 offset += size * sizeof_gl_float
1385 gl_error = glGetError
1386 assert gl_error == gl_NO_ERROR else print_error gl_error
1387
1388 size = 4
1389 for r in [p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3] do
1390 if r.is_active then
1391 glEnableVertexAttribArray r.location
1392 glVertexAttribPointeri(r.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1393 end
1394 offset += size * sizeof_gl_float
1395 gl_error = glGetError
1396 assert gl_error == gl_NO_ERROR else print_error gl_error
1397 end
1398
1399 size = 1
1400 glEnableVertexAttribArray p.animation_fps.location
1401 glVertexAttribPointeri(p.animation_fps.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1402 offset += size * sizeof_gl_float
1403 gl_error = glGetError
1404 assert gl_error == gl_NO_ERROR else print_error gl_error
1405
1406 size = 1
1407 glEnableVertexAttribArray p.animation_n_frames.location
1408 glVertexAttribPointeri(p.animation_n_frames.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1409 offset += size * sizeof_gl_float
1410 gl_error = glGetError
1411 assert gl_error == gl_NO_ERROR else print_error gl_error
1412
1413 size = 2
1414 glEnableVertexAttribArray p.animation_coord.location
1415 glVertexAttribPointeri(p.animation_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1416 offset += size * sizeof_gl_float
1417 gl_error = glGetError
1418 assert gl_error == gl_NO_ERROR else print_error gl_error
1419
1420 size = 2
1421 glEnableVertexAttribArray p.animation_tex_coord.location
1422 glVertexAttribPointeri(p.animation_tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1423 offset += size * sizeof_gl_float
1424 gl_error = glGetError
1425 assert gl_error == gl_NO_ERROR else print_error gl_error
1426
1427 size = 2
1428 glEnableVertexAttribArray p.animation_tex_diff.location
1429 glVertexAttribPointeri(p.animation_tex_diff.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1430 offset += size * sizeof_gl_float
1431 gl_error = glGetError
1432 assert gl_error == gl_NO_ERROR else print_error gl_error
1433
1434 size = 1
1435 glEnableVertexAttribArray p.animation_start.location
1436 glVertexAttribPointeri(p.animation_start.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_loops.location
1443 glVertexAttribPointeri(p.animation_loops.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 # Actual draw
1449 for s in sprites.starts, e in sprites.ends do
1450 var l = e-s
1451 glDrawElementsi(gl_TRIANGLES, l*indices_per_sprite, gl_UNSIGNED_SHORT, 2*s*indices_per_sprite)
1452 gl_error = glGetError
1453 assert gl_error == gl_NO_ERROR else print_error gl_error
1454 end
1455
1456 # Take down
1457 for attr in [p.translation, p.color, p.scale, p.coord, p.tex_coord,
1458 p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3: Attribute] do
1459 if not attr.is_active then continue
1460 glDisableVertexAttribArray(attr.location)
1461 gl_error = glGetError
1462 assert gl_error == gl_NO_ERROR else print_error gl_error
1463 end
1464
1465 glBindBuffer(gl_ARRAY_BUFFER, 0)
1466 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, 0)
1467 gl_error = glGetError
1468 assert gl_error == gl_NO_ERROR else print_error gl_error
1469 end
1470 end
1471
1472 # Representation of sprite data on the GPU
1473 #
1474 # The main purpose of this class is to optimize the use of contiguous
1475 # space in GPU memory. Each contiguous memory block can be drawn in a
1476 # single call. The starts index of each block is kept by `starts,
1477 # and the end + 1 by `ends`.
1478 #
1479 # The data can be compressed by a call to `defragment`.
1480 #
1481 # ~~~
1482 # intrude import gamnit::flat
1483 #
1484 # var array = new GroupedArray[String]
1485 # assert array.to_s == ""
1486 #
1487 # array.add "a"
1488 # array.add "b"
1489 # array.add "c"
1490 # array.add "d"
1491 # array.add "e"
1492 # array.add "f"
1493 # assert array.to_s == "[a,b,c,d,e,f]"
1494 # assert array.capacity == 6
1495 #
1496 # array.remove "a"
1497 # assert array.to_s == "[b,c,d,e,f]"
1498 #
1499 # array.remove "b"
1500 # assert array.to_s == "[c,d,e,f]"
1501 #
1502 # array.remove "f"
1503 # assert array.to_s == "[c,d,e]"
1504 #
1505 # array.remove "d"
1506 # assert array.to_s == "[c][e]"
1507 #
1508 # array.add "A"
1509 # assert array.to_s == "[A][c][e]"
1510 #
1511 # array.add "B"
1512 # assert array.to_s == "[A,B,c][e]"
1513 #
1514 # array.remove "e"
1515 # assert array.to_s == "[A,B,c]"
1516 #
1517 # array.add "D"
1518 # assert array.to_s == "[A,B,c,D]"
1519 #
1520 # array.add "E"
1521 # assert array.to_s == "[A,B,c,D,E]"
1522 # assert array.capacity == 6
1523 # assert array.length == 5
1524 #
1525 # array.remove "A"
1526 # array.remove "B"
1527 # array.remove "c"
1528 # array.remove "D"
1529 # array.remove "E"
1530 # assert array.to_s == ""
1531 #
1532 # array.add "a"
1533 # assert array.to_s == "[a]"
1534 # ~~~
1535 private class GroupedArray[E]
1536
1537 # Memory with actual objects, and null in empty slots
1538 var items = new Array[nullable E]
1539
1540 # Number of items in the array
1541 var length = 0
1542
1543 # Number of item slots in the array
1544 fun capacity: Int do return items.length
1545
1546 # List of available slots
1547 var available = new MinHeap[Int].default
1548
1549 # Start index of filled chunks
1550 var starts = new List[Int]
1551
1552 # Index of the spots after filled chunks
1553 var ends = new List[Int]
1554
1555 # Add `item` to the first available slot and return its index
1556 fun add(item: E): Int
1557 do
1558 length += 1
1559
1560 if available.not_empty then
1561 # starts & ends can't be empty
1562
1563 var i = available.take
1564 items[i] = item
1565
1566 if i == starts.first - 1 then
1567 # slot 0 free, 1 taken
1568 starts.first -= 1
1569 else if i == 0 then
1570 # slot 0 and more free
1571 starts.unshift 0
1572 ends.unshift 1
1573 else if starts.length >= 2 and ends.first + 1 == starts[1] then
1574 # merge 2 chunks
1575 ends.remove_at 0
1576 starts.remove_at 1
1577 else
1578 # at end of first chunk
1579 ends.first += 1
1580 end
1581 return i
1582 end
1583
1584 items.add item
1585 if ends.is_empty then
1586 starts.add 0
1587 ends.add 1
1588 else ends.last += 1
1589 return ends.last - 1
1590 end
1591
1592 # Remove the first instance of `item`
1593 fun remove(item: E)
1594 do
1595 var index = items.index_of(item)
1596 remove_at(item, index)
1597 end
1598
1599 # Remove `item` at `index`
1600 fun remove_at(item: E, index: Int)
1601 do
1602 var i = index
1603 length -= 1
1604 items[i] = null
1605
1606 var ii = 0
1607 for s in starts, e in ends do
1608 if s <= i and i < e then
1609 if s == e-1 then
1610 # single item chunk
1611 starts.remove_at ii
1612 ends.remove_at ii
1613
1614 if starts.is_empty then
1615 items.clear
1616 available.clear
1617 return
1618 end
1619 else if e-1 == i then
1620 # last item of chunk
1621 ends[ii] -= 1
1622
1623 else if s == i then
1624 # first item of chunk
1625 starts[ii] += 1
1626 else
1627 # break up chunk
1628 ends.insert(ends[ii], ii+1)
1629 ends[ii] = i
1630 starts.insert(i+1, ii+1)
1631 end
1632
1633 available.add i
1634 return
1635 end
1636 ii += 1
1637 end
1638
1639 abort
1640 end
1641
1642 # Defragment and compress everything into a single chunks beginning at 0
1643 #
1644 # Returns the elements that moved as a list.
1645 #
1646 # ~~~
1647 # intrude import gamnit::flat
1648 #
1649 # var array = new GroupedArray[String]
1650 # array.add "a"
1651 # array.add "b"
1652 # array.add "c"
1653 # array.add "d"
1654 # array.remove "c"
1655 # array.remove "a"
1656 # assert array.to_s == "[b][d]"
1657 #
1658 # var moved = array.defragment
1659 # assert moved.to_s == "[d]"
1660 # assert array.to_s == "[d,b]"
1661 # assert array.length == 2
1662 # assert array.capacity == 2
1663 #
1664 # array.add "e"
1665 # array.add "f"
1666 # assert array.to_s == "[d,b,e,f]"
1667 # ~~~
1668 fun defragment(max: nullable Int): Array[E]
1669 do
1670 app.perf_clock_sprites.lapse
1671 max = max or else length
1672
1673 var moved = new Array[E]
1674 while max > 0 and (starts.length > 1 or starts.first != 0) do
1675 var i = ends.last - 1
1676 var e = items[i]
1677 assert e != null
1678 remove e
1679 add e
1680 moved.add e
1681 max -= 1
1682 end
1683
1684 if starts.length == 1 and starts.first == 0 then
1685 for i in [length..capacity[ do items.pop
1686 available.clear
1687 end
1688
1689 sys.perfs["gamnit flat gpu defrag"].add app.perf_clock_sprites.lapse
1690 return moved
1691 end
1692
1693 redef fun to_s
1694 do
1695 var ss = new Array[String]
1696 for s in starts, e in ends do
1697 ss.add "["
1698 for i in [s..e[ do
1699 var item: nullable Object = items[i]
1700 if item == null then item = "null"
1701 ss.add item.to_s
1702 if i != e-1 then ss.add ","
1703 end
1704 ss.add "]"
1705 end
1706 return ss.join
1707 end
1708 end
1709
1710 # Optimized `GroupedArray` to use `Sprite::context_index` and avoid using `index_of`
1711 private class GroupedSprites
1712 super GroupedArray[Sprite]
1713
1714 redef fun add(item)
1715 do
1716 var index = super
1717 item.context_index = index
1718 return index
1719 end
1720
1721 redef fun remove(item) do remove_at(item, item.context_index)
1722 end
1723
1724 redef class GLfloatArray
1725 private fun fill_from_matrix(matrix: Matrix, dst_offset: nullable Int)
1726 do
1727 dst_offset = dst_offset or else add_index
1728 var mat_len = matrix.width*matrix.height
1729 assert length >= mat_len + dst_offset
1730 native_array.fill_from_matrix_native(matrix.items, dst_offset, mat_len)
1731 add_index += mat_len
1732 end
1733 end
1734
1735 redef class NativeGLfloatArray
1736 private fun fill_from_matrix_native(matrix: matrix::NativeDoubleArray, dst_offset, len: Int) `{
1737 int i;
1738 for (i = 0; i < len; i ++)
1739 self[i+dst_offset] = (GLfloat)matrix[i];
1740 `}
1741 end
1742
1743 redef class Sys
1744 private var sprite_draw_order_sorter = new DrawOrderComparator is lazy
1745 end
1746
1747 # Sort `SpriteContext` by their `draw_order`
1748 private class DrawOrderComparator
1749 super Comparator
1750
1751 # This class can't set COMPARED because
1752 # `the public property cannot contain the private type...`
1753 #redef type COMPARED: SpriteContext
1754
1755 # Require: `a isa SpriteContext and b isa SpriteContext`
1756 redef fun compare(a, b)
1757 do return a.as(SpriteContext).draw_order <=> b.as(SpriteContext).draw_order
1758 end