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