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