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