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