gamnit: cache the last sprite added to `sprites_to_update`
[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 # Rotation on the Z axis, positive values turn counterclockwise
127 var rotation = 0.0 is writable(rotation_direct=)
128
129 # Rotation on the Z axis, positive values turn counterclockwise
130 fun rotation=(value: Float)
131 do
132 if isset _rotation and value != rotation then needs_update
133 rotation_direct = value
134 end
135
136 # Mirror `texture` horizontally, inverting each pixel on the X axis
137 var invert_x = false is writable(invert_x_direct=)
138
139 # Mirror `texture` horizontally, inverting each pixel on the X axis
140 fun invert_x=(value: Bool)
141 do
142 if isset _invert_x and value != invert_x then needs_update
143 invert_x_direct = value
144 end
145
146 # Scale applied to this sprite
147 #
148 # The basic size of `self` depends on the size in pixels of `texture`.
149 var scale = 1.0 is writable(scale_direct=)
150
151 # Scale applied to this sprite
152 #
153 # The basic size of `self` depends on the size in pixels of `texture`.
154 fun scale=(value: Float)
155 do
156 if isset _scale and value != scale then needs_update
157 scale_direct = value
158 end
159
160 # Red tint applied to `texture` on draw
161 fun red: Float do return tint[0]
162
163 # Red tint applied to `texture` on draw
164 fun red=(value: Float)
165 do
166 if isset _tint and value != red then needs_update
167 tint[0] = value
168 end
169
170 # Green tint applied to `texture` on draw
171 fun green: Float do return tint[1]
172
173 # Green tint applied to `texture` on draw
174 fun green=(value: Float)
175 do
176 if isset _tint and value != green then needs_update
177 tint[1] = value
178 end
179
180 # Blue tint applied to `texture` on draw
181 fun blue: Float do return tint[2]
182
183 # Blue tint applied to `texture` on draw
184 fun blue=(value: Float)
185 do
186 if isset _tint and value != blue then needs_update
187 tint[2] = value
188 end
189
190 # Transparency applied to `texture` on draw
191 fun alpha: Float do return tint[3]
192
193 # Transparency applied to `texture` on draw
194 fun alpha=(value: Float)
195 do
196 if isset _tint and value != alpha then needs_update
197 tint[3] = value
198 end
199
200 # Tint applied to `texture` on draw
201 #
202 # Alternative to the accessors `red, green, blue & alpha`.
203 # Changes inside the array do not automatically set `needs_update`.
204 #
205 # Require: `tint.length == 4`
206 var tint: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct=)
207
208 # Tint applied to `texture` on draw, see `tint`
209 fun tint=(value: Array[Float])
210 do
211 if isset _tint and value != tint then needs_update
212 tint_direct = value
213 end
214
215 # Is this sprite static and added in bulk?
216 #
217 # Set to `true` to give a hint to the framework that this sprite won't
218 # change often and that it is added in bulk with other static sprites.
219 # This value can be ignored in the prototyping phase of a game and
220 # added only when better performance are needed.
221 var static = false is writable(static_direct=)
222
223 # Is this sprite static and added in bulk? see `static`
224 fun static=(value: Bool)
225 do
226 if isset _static and value != static then needs_remap
227 static_direct = value
228 end
229
230 # Request an update on the CPU
231 #
232 # This is called automatically on modification of any value of `Sprite`.
233 # However, it can still be set manually if a modification can't be
234 # detected or by subclasses.
235 fun needs_update
236 do
237 var c = context
238 if c == null then return
239 if c.last_sprite_to_update == self then return
240 c.sprites_to_update.add self
241 c.last_sprite_to_update = self
242 end
243
244 # Request a resorting of this sprite in its sprite list
245 #
246 # Resorting is required when `static` or the root of `texture` changes.
247 # This is called automatically when such changes are detected.
248 # However, it can still be set manually if a modification can't be
249 # detected or by subclasses.
250 fun needs_remap
251 do
252 var l = sprite_set
253 if l != null then l.sprites_to_remap.add self
254 end
255
256 # Current context to which `self` was sorted
257 private var context: nullable SpriteContext = null
258
259 # Index in `context`
260 private var context_index: Int = -1
261
262 # Current context to which `self` belongs
263 private var sprite_set: nullable SpriteSet = null
264 end
265
266 redef class App
267 # Default graphic program to draw `sprites`
268 private var simple_2d_program = new Simple2dProgram is lazy
269
270 # Camera for world `sprites` and `depth::actors` with perspective
271 #
272 # By default, the camera is configured to a height of 1080 units
273 # of world coordinates at `z == 0.0`.
274 var world_camera: EulerCamera is lazy do
275 var camera = new EulerCamera(app.display.as(not null))
276
277 # Aim for full HD pixel resolution at level 0
278 camera.reset_height 1080.0
279 camera.near = 10.0
280
281 return camera
282 end
283
284 # Camera for `ui_sprites` using an orthogonal view
285 var ui_camera = new UICamera(app.display.as(not null)) is lazy
286
287 # World sprites drawn as seen by `world_camera`
288 var sprites: Set[Sprite] = new SpriteSet
289
290 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
291 var ui_sprites: Set[Sprite] = new SpriteSet
292
293 # Main method to refine in clients to update game logic and `sprites`
294 fun update(dt: Float) do end
295
296 # Display `texture` as a splash screen
297 #
298 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
299 fun show_splash_screen(texture: Texture)
300 do
301 texture.load
302
303 var splash = new Sprite(texture, ui_camera.center.offset(0.0, 0.0, 0.0))
304 ui_sprites.add splash
305
306 var display = display
307 assert display != null
308 glClear gl_COLOR_BUFFER_BIT
309 frame_core_ui_sprites display
310 display.flip
311
312 ui_sprites.remove splash
313 end
314
315 # ---
316 # Support and implementation
317
318 # Main clock used to count each frame `dt`, lapsed for `update` only
319 private var clock = new Clock is lazy
320
321 # Performance clock to for `frame_core_draw` operations
322 private var perf_clock_main = new Clock
323
324 # Second performance clock for smaller operations
325 private var perf_clock_sprites = new Clock is lazy
326
327 redef fun on_create
328 do
329 super
330
331 var display = display
332 assert display != null
333
334 var gl_error = glGetError
335 assert gl_error == gl_NO_ERROR else print_error gl_error
336
337 # Prepare program
338 var program = simple_2d_program
339 program.compile_and_link
340
341 var gamnit_error = program.error
342 assert gamnit_error == null else print_error gamnit_error
343
344 # Enable blending
345 gl.capabilities.blend.enable
346 glBlendFunc(gl_SRC_ALPHA, gl_ONE_MINUS_SRC_ALPHA)
347
348 # Enable depth test
349 gl.capabilities.depth_test.enable
350 glDepthFunc gl_LEQUAL
351 glDepthMask true
352
353 # Prepare viewport and background color
354 glViewport(0, 0, display.width, display.height)
355 glClearColor(0.0, 0.0, 0.0, 1.0)
356
357 gl_error = glGetError
358 assert gl_error == gl_NO_ERROR else print_error gl_error
359
360 # Prepare to draw
361 for tex in all_root_textures do
362 tex.load
363 gamnit_error = tex.error
364 if gamnit_error != null then print_error gamnit_error
365
366 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
367 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
368 end
369 end
370
371 redef fun on_stop
372 do
373 # Clean up
374 simple_2d_program.delete
375
376 # Close gamnit
377 var display = display
378 if display != null then display.close
379 end
380
381 redef fun on_resize(display)
382 do
383 super
384
385 world_camera.mvp_matrix_cache = null
386 ui_camera.mvp_matrix_cache = null
387
388 # Update all sprites in the UI
389 for sprite in ui_sprites do sprite.needs_update
390 end
391
392 redef fun frame_core(display)
393 do
394 # Check errors
395 var gl_error = glGetError
396 assert gl_error == gl_NO_ERROR else print_error gl_error
397
398 # Update game logic and set sprites
399 perf_clock_main.lapse
400 var dt = clock.lapse.to_f
401 update dt
402 sys.perfs["gamnit flat update client"].add perf_clock_main.lapse
403
404 # Draw and flip screen
405 frame_core_draw display
406 display.flip
407
408 # Check errors
409 gl_error = glGetError
410 assert gl_error == gl_NO_ERROR else print_error gl_error
411 end
412
413 # Draw the whole screen, all `glDraw...` calls should be executed here
414 protected fun frame_core_draw(display: GamnitDisplay)
415 do
416 frame_core_dynamic_resolution_before display
417
418 perf_clock_main.lapse
419 frame_core_world_sprites display
420 perfs["gamnit flat world_sprites"].add perf_clock_main.lapse
421
422 frame_core_ui_sprites display
423 perfs["gamnit flat ui_sprites"].add perf_clock_main.lapse
424
425 frame_core_dynamic_resolution_after display
426 end
427
428 private fun frame_core_sprites(display: GamnitDisplay, sprite_set: SpriteSet, camera: Camera)
429 do
430 var simple_2d_program = app.simple_2d_program
431 simple_2d_program.use
432 simple_2d_program.mvp.uniform camera.mvp_matrix
433
434 # draw
435 sprite_set.draw
436 end
437
438 # Draw world sprites from `sprites`
439 protected fun frame_core_world_sprites(display: GamnitDisplay)
440 do
441 frame_core_sprites(display, sprites.as(SpriteSet), world_camera)
442 end
443
444 # Draw UI sprites from `ui_sprites`
445 protected fun frame_core_ui_sprites(display: GamnitDisplay)
446 do
447 # Reset only the depth buffer
448 glClear gl_DEPTH_BUFFER_BIT
449
450 frame_core_sprites(display, ui_sprites.as(SpriteSet), ui_camera)
451 end
452 end
453
454 redef class Texture
455
456 # Vertices coordinates of the base geometry
457 #
458 # Defines the default width and height of related sprites.
459 private var vertices: Array[Float] is lazy do
460 var w = width
461 var h = height
462 return [-0.5*w, 0.5*h, 0.0,
463 0.5*w, 0.5*h, 0.0,
464 -0.5*w, -0.5*h, 0.0,
465 0.5*w, -0.5*h, 0.0]
466 end
467
468 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
469 private var texture_coords: Array[Float] is lazy do
470 var l = offset_left
471 var r = offset_right
472 var b = offset_bottom
473 var t = offset_top
474 return [l, t,
475 r, t,
476 l, b,
477 r, b]
478 end
479
480 # Coordinates of this texture on the `root` texture, inverting the X axis
481 private var texture_coords_invert_x: Array[Float] is lazy do
482 var l = offset_left
483 var r = offset_right
484 var b = offset_bottom
485 var t = offset_top
486 return [r, t,
487 l, t,
488 r, b,
489 l, b]
490 end
491 end
492
493 # Graphic program to display simple models with a texture, translation, rotation and scale
494 private class Simple2dProgram
495 super GamnitProgramFromSource
496
497 redef var vertex_shader_source = """
498 // Vertex coordinates
499 attribute vec4 coord;
500
501 // Vertex color tint
502 attribute vec4 color;
503
504 // Vertex translation
505 attribute vec4 translation;
506
507 // Vertex scaling
508 attribute float scale;
509
510 // Vertex coordinates on textures
511 attribute vec2 tex_coord;
512
513 // Model view projection matrix
514 uniform mat4 mvp;
515
516 // Rotation matrix
517 attribute vec4 rotation_row0;
518 attribute vec4 rotation_row1;
519 attribute vec4 rotation_row2;
520 attribute vec4 rotation_row3;
521
522 mat4 rotation()
523 {
524 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
525 }
526
527 // Output to the fragment shader
528 varying vec4 v_color;
529 varying vec2 v_coord;
530
531 void main()
532 {
533 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation() + translation)* mvp;
534 v_color = color;
535 v_coord = tex_coord;
536 }
537 """ @ glsl_vertex_shader
538
539 redef var fragment_shader_source = """
540 precision mediump float;
541
542 // Does this object use a texture?
543 uniform bool use_texture;
544
545 // Texture to apply on this object
546 uniform sampler2D texture0;
547
548 // Input from the vertex shader
549 varying vec4 v_color;
550 varying vec2 v_coord;
551
552 void main()
553 {
554 if(use_texture) {
555 gl_FragColor = v_color * texture2D(texture0, v_coord);
556 if (gl_FragColor.a <= 0.01) discard;
557 } else {
558 gl_FragColor = v_color;
559 }
560 }
561 """ @ glsl_fragment_shader
562
563 # Vertices coordinates
564 var coord = attributes["coord"].as(AttributeVec4) is lazy
565
566 # Should this program use the texture `texture`?
567 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
568
569 # Visible texture unit
570 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
571
572 # Coordinates on the textures, per vertex
573 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
574
575 # Color tint per vertex
576 var color = attributes["color"].as(AttributeVec4) is lazy
577
578 # Translation applied to each vertex
579 var translation = attributes["translation"].as(AttributeVec4) is lazy
580
581 # Rotation matrix, row 0
582 var rotation_row0 = attributes["rotation_row0"].as(AttributeVec4) is lazy
583
584 # Rotation matrix, row 1
585 var rotation_row1 = attributes["rotation_row1"].as(AttributeVec4) is lazy
586
587 # Rotation matrix, row 2
588 var rotation_row2 = attributes["rotation_row2"].as(AttributeVec4) is lazy
589
590 # Rotation matrix, row 3
591 var rotation_row3 = attributes["rotation_row3"].as(AttributeVec4) is lazy
592
593 # Scaling per vertex
594 var scale = attributes["scale"].as(AttributeFloat) is lazy
595
596 # Model view projection matrix
597 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
598 end
599
600 redef class Point3d[N]
601 # ---
602 # Associate each point to its sprites
603
604 private var sprites: nullable Array[Sprite] = null
605
606 private fun sprites_add(sprite: Sprite)
607 do
608 var sprites = sprites
609 if sprites == null then
610 sprites = new Array[Sprite]
611 self.sprites = sprites
612 end
613 sprites.add sprite
614 end
615
616 private fun sprites_remove(sprite: Sprite)
617 do
618 var sprites = sprites
619 assert sprites != null
620 sprites.remove sprite
621 end
622
623 # ---
624 # Notify `sprites` on attribute modification
625
626 private fun needs_update
627 do
628 var sprites = sprites
629 if sprites != null then for s in sprites do s.needs_update
630 end
631
632 redef fun x=(v)
633 do
634 if isset _x and v != x then needs_update
635 super
636 end
637
638 redef fun y=(v)
639 do
640 if isset _y and v != y then needs_update
641 super
642 end
643
644 redef fun z=(v)
645 do
646 if isset _z and v != z then needs_update
647 super
648 end
649 end
650
651 redef class OffsetPoint3d
652 redef fun x=(v)
653 do
654 if isset _x and v != x then needs_update
655 super
656 end
657
658 redef fun y=(v)
659 do
660 if isset _y and v != y then needs_update
661 super
662 end
663
664 redef fun z=(v)
665 do
666 if isset _z and v != z then needs_update
667 super
668 end
669 end
670
671 # Set of sprites sorting them into different `SpriteContext`
672 private class SpriteSet
673 super HashSet[Sprite]
674
675 # Map texture then static vs dynamic to a `SpriteContext`
676 var contexts_map = new HashMap2[RootTexture, Bool, SpriteContext]
677
678 # Contexts in `contexts_map`
679 var contexts_items = new Array[SpriteContext]
680
681 # Sprites needing resorting in `contexts_map`
682 var sprites_to_remap = new Array[Sprite]
683
684 # Add a sprite to the appropriate context
685 fun map_sprite(sprite: Sprite)
686 do
687 assert sprite.context == null else print_error "Sprite {sprite} belongs to another SpriteSet"
688
689 var texture = sprite.texture.root
690 var context = contexts_map[texture, sprite.static]
691
692 if context == null then
693 var usage = if sprite.static then gl_STATIC_DRAW else gl_DYNAMIC_DRAW
694 context = new SpriteContext(texture, usage)
695
696 contexts_map[texture, sprite.static] = context
697 contexts_items.add context
698 end
699
700 context.sprites.add sprite
701 context.sprites_to_update.add sprite
702 context.last_sprite_to_update = sprite
703
704 sprite.context = context
705 sprite.sprite_set = self
706 end
707
708 # Remove a sprite from its context
709 fun unmap_sprite(sprite: Sprite)
710 do
711 var context = sprite.context
712 assert context != null
713 context.sprites.remove sprite
714
715 sprite.context = null
716 sprite.sprite_set = null
717 end
718
719 # Draw all sprites by all contexts
720 fun draw
721 do
722 for sprite in sprites_to_remap do
723 unmap_sprite sprite
724 map_sprite sprite
725 end
726 sprites_to_remap.clear
727
728 for context in contexts_items do context.draw
729 end
730
731 redef fun add(e)
732 do
733 if contexts_items.has(e.context) then return
734 map_sprite e
735 super
736 end
737
738 redef fun remove(e)
739 do
740 super
741 if e isa Sprite then unmap_sprite e
742 end
743
744 redef fun remove_all(e)
745 do
746 if not has(e) then return
747 remove e
748 end
749
750 redef fun clear
751 do
752 for sprite in self do
753 sprite.context = null
754 sprite.sprite_set = null
755 end
756 super
757 for c in contexts_items do c.destroy
758 contexts_map.clear
759 contexts_items.clear
760 end
761 end
762
763 # Context for calls to `glDrawElements`
764 #
765 # Each context has only one `texture` and `usage`, but many sprites.
766 private class SpriteContext
767
768 # ---
769 # Context config and state
770
771 # Only root texture drawn by this context
772 var texture: nullable RootTexture
773
774 # OpenGL ES usage of `buffer_array` and `buffer_element`
775 var usage: GLBufferUsage
776
777 # Sprites drawn by this context
778 var sprites = new GroupedSprites
779
780 # Sprites to update since last `draw`
781 var sprites_to_update = new Set[Sprite]
782
783 # Cache of the last `Sprite` added to `sprites_to_update` since the last call to `draw`
784 var last_sprite_to_update: nullable Sprite = null
785
786 # Sprites that have been update and for which `needs_update` can be set to false
787 var updated_sprites = new Array[Sprite]
788
789 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
790 #
791 # Require: `resize_ratio >= 1.0`
792 var resize_ratio = 1.2
793
794 # ---
795 # OpenGL ES data
796
797 # OpenGL ES buffer name for vertex data
798 var buffer_array: Int = -1
799
800 # OpenGL ES buffer name for indices
801 var buffer_element: Int = -1
802
803 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
804 var buffer_capacity = 0
805
806 # C buffers used to pass the data of a single sprite
807 var local_data_buffer = new GLfloatArray(float_per_vertex*4) is lazy
808 var local_indices_buffer = new CUInt16Array(indices_per_sprite) is lazy
809
810 # ---
811 # Constants
812
813 # Number of GL_FLOAT per vertex of `Simple2dProgram`
814 var float_per_vertex: Int is lazy do
815 # vec4 translation, vec4 color, vec4 coord,
816 # float scale, vec2 tex_coord, vec4 rotation_row*
817 return 4 + 4 + 4 +
818 1 + 2 + 4*4
819 end
820
821 # Number of bytes per vertex of `Simple2dProgram`
822 var bytes_per_vertex: Int is lazy do
823 var fs = 4 # sizeof(GL_FLOAT)
824 return fs * float_per_vertex
825 end
826
827 # Number of bytes per sprite
828 var bytes_per_sprite: Int is lazy do return bytes_per_vertex * 4
829
830 # Number of vertex indices per sprite draw call (2 triangles)
831 var indices_per_sprite = 6
832
833 # ---
834 # Main services
835
836 # Allocate `buffer_array` and `buffer_element`
837 fun prepare
838 do
839 var bufs = glGenBuffers(2)
840 buffer_array = bufs[0]
841 buffer_element = bufs[1]
842
843 var gl_error = glGetError
844 assert gl_error == gl_NO_ERROR else print_error gl_error
845 end
846
847 # Destroy `buffer_array` and `buffer_element`
848 fun destroy
849 do
850 glDeleteBuffers([buffer_array, buffer_element])
851 var gl_error = glGetError
852 assert gl_error == gl_NO_ERROR else print_error gl_error
853
854 buffer_array = -1
855 buffer_element = -1
856 end
857
858 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
859 fun resize
860 do
861 app.perf_clock_sprites.lapse
862
863 # Allocate a bit more space
864 var capacity = (sprites.capacity.to_f * resize_ratio).to_i
865
866 var array_bytes = capacity * bytes_per_sprite
867 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
868 assert glIsBuffer(buffer_array)
869 glBufferData(gl_ARRAY_BUFFER, array_bytes, new Pointer.nul, usage)
870 var gl_error = glGetError
871 assert gl_error == gl_NO_ERROR else print_error gl_error
872
873 # GL_TRIANGLES 6 vertices * sprite
874 var n_indices = capacity * indices_per_sprite
875 var ius = 2 # sizeof(GL_UNSIGNED_SHORT)
876 var element_bytes = n_indices * ius
877 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
878 assert glIsBuffer(buffer_element)
879 glBufferData(gl_ELEMENT_ARRAY_BUFFER, element_bytes, new Pointer.nul, usage)
880 gl_error = glGetError
881 assert gl_error == gl_NO_ERROR else print_error gl_error
882
883 buffer_capacity = capacity
884
885 sys.perfs["gamnit flat gpu resize"].add app.perf_clock_sprites.lapse
886 end
887
888 # Update GPU data of `sprite`
889 fun update_sprite(sprite: Sprite)
890 do
891 var context = sprite.context
892 if context != self then return
893
894 var sprite_index = sprite.context_index
895 assert sprite_index != -1
896
897 # Vertices data
898
899 var data = local_data_buffer
900 var o = 0
901 for v in [0..4[ do
902 # vec4 translation
903 data[o+ 0] = sprite.center.x
904 data[o+ 1] = sprite.center.y
905 data[o+ 2] = sprite.center.z
906 data[o+ 3] = 0.0
907
908 # vec4 color
909 data[o+ 4] = sprite.tint[0]
910 data[o+ 5] = sprite.tint[1]
911 data[o+ 6] = sprite.tint[2]
912 data[o+ 7] = sprite.tint[3]
913
914 # float scale
915 data[o+ 8] = sprite.scale
916
917 # vec4 coord
918 data[o+ 9] = sprite.texture.vertices[v*3+0]
919 data[o+10] = sprite.texture.vertices[v*3+1]
920 data[o+11] = sprite.texture.vertices[v*3+2]
921 data[o+12] = 0.0
922
923 # vec2 tex_coord
924 var texture = texture
925 if texture != null then
926 var tc = if sprite.invert_x then
927 sprite.texture.texture_coords_invert_x
928 else sprite.texture.texture_coords
929 data[o+13] = tc[v*2+0]
930 data[o+14] = tc[v*2+1]
931 end
932
933 # mat4 rotation
934 var rot
935 if sprite.rotation == 0.0 then
936 # Cache the matrix at no rotation
937 rot = once new Matrix.identity(4)
938 else
939 rot = new Matrix.rotation(sprite.rotation, 0.0, 0.0, 1.0)
940 end
941 data.fill_from_matrix(rot, o+15)
942
943 o += float_per_vertex
944 end
945
946 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
947 glBufferSubData(gl_ARRAY_BUFFER, sprite_index*bytes_per_sprite, bytes_per_sprite, data.native_array)
948
949 var gl_error = glGetError
950 assert gl_error == gl_NO_ERROR else print_error gl_error
951
952 # Element / indices
953 #
954 # 0--1
955 # | /|
956 # |/ |
957 # 2--3
958
959 var indices = local_indices_buffer
960 var io = sprite_index*4
961 indices[0] = io+0
962 indices[1] = io+2
963 indices[2] = io+1
964 indices[3] = io+1
965 indices[4] = io+2
966 indices[5] = io+3
967
968 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
969 glBufferSubData(gl_ELEMENT_ARRAY_BUFFER, sprite_index*6*2, 6*2, indices.native_array)
970
971 gl_error = glGetError
972 assert gl_error == gl_NO_ERROR else print_error gl_error
973 end
974
975 # Draw all `sprites`
976 #
977 # Call `resize` and `update_sprite` as needed before actual draw operation.
978 #
979 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
980 fun draw
981 do
982 if buffer_array == -1 then prepare
983
984 assert buffer_array > 0 and buffer_element > 0 else
985 print_error "Internal error: {self} was destroyed"
986 end
987
988 # Setup
989 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
990 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
991
992 # Resize GPU buffers?
993 if sprites.capacity > buffer_capacity then
994 # Try to defragment first
995 var moved = sprites.defragment
996
997 if sprites.capacity > buffer_capacity then
998 # Defragmentation wasn't enough, grow
999 resize
1000
1001 # We must update everything
1002 for s in sprites.items do if s != null then sprites_to_update.add s
1003 else
1004 # Just update the moved sprites
1005 for s in moved do sprites_to_update.add s
1006 end
1007 else if sprites.available.not_empty then
1008 # Defragment a bit anyway
1009 # TODO defrag only when there's time left on a frame
1010 var moved = sprites.defragment(1)
1011 for s in moved do sprites_to_update.add s
1012 end
1013
1014 # Update GPU sprites data
1015 if sprites_to_update.not_empty then
1016 app.perf_clock_sprites.lapse
1017
1018 for sprite in sprites_to_update do update_sprite(sprite)
1019 sprites_to_update.clear
1020 last_sprite_to_update = null
1021
1022 sys.perfs["gamnit flat gpu update"].add app.perf_clock_sprites.lapse
1023 end
1024
1025 # Update uniforms specific to this context
1026 var texture = texture
1027 app.simple_2d_program.use_texture.uniform texture != null
1028 if texture != null then
1029 glActiveTexture gl_TEXTURE0
1030 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
1031 app.simple_2d_program.texture.uniform 0
1032 end
1033 var gl_error = glGetError
1034 assert gl_error == gl_NO_ERROR else print_error gl_error
1035
1036 # Configure attributes, in order:
1037 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*
1038 var offset = 0
1039 var p = app.simple_2d_program
1040 var sizeof_gl_float = 4 # sizeof(GL_FLOAT)
1041
1042 var size = 4 # Number of floats
1043 glEnableVertexAttribArray p.translation.location
1044 glVertexAttribPointeri(p.translation.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1045 offset += size * sizeof_gl_float
1046 gl_error = glGetError
1047 assert gl_error == gl_NO_ERROR else print_error gl_error
1048
1049 size = 4
1050 glEnableVertexAttribArray p.color.location
1051 glVertexAttribPointeri(p.color.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1052 offset += size * sizeof_gl_float
1053 gl_error = glGetError
1054 assert gl_error == gl_NO_ERROR else print_error gl_error
1055
1056 size = 1
1057 glEnableVertexAttribArray p.scale.location
1058 glVertexAttribPointeri(p.scale.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1059 offset += size * sizeof_gl_float
1060 gl_error = glGetError
1061 assert gl_error == gl_NO_ERROR else print_error gl_error
1062
1063 size = 4
1064 glEnableVertexAttribArray p.coord.location
1065 glVertexAttribPointeri(p.coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1066 offset += size * sizeof_gl_float
1067 gl_error = glGetError
1068 assert gl_error == gl_NO_ERROR else print_error gl_error
1069
1070 size = 2
1071 glEnableVertexAttribArray p.tex_coord.location
1072 glVertexAttribPointeri(p.tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1073 offset += size * sizeof_gl_float
1074 gl_error = glGetError
1075 assert gl_error == gl_NO_ERROR else print_error gl_error
1076
1077 size = 4
1078 for r in [p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3] do
1079 if r.is_active then
1080 glEnableVertexAttribArray r.location
1081 glVertexAttribPointeri(r.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1082 end
1083 offset += size * sizeof_gl_float
1084 gl_error = glGetError
1085 assert gl_error == gl_NO_ERROR else print_error gl_error
1086 end
1087
1088 # Actual draw
1089 for s in sprites.starts, e in sprites.ends do
1090 var l = e-s
1091 glDrawElementsi(gl_TRIANGLES, l*indices_per_sprite, gl_UNSIGNED_SHORT, 2*s*indices_per_sprite)
1092 gl_error = glGetError
1093 assert gl_error == gl_NO_ERROR else print_error gl_error
1094 end
1095
1096 # Take down
1097 for attr in [p.translation, p.color, p.scale, p.coord, p.tex_coord,
1098 p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3: Attribute] do
1099 if not attr.is_active then continue
1100 glDisableVertexAttribArray(attr.location)
1101 gl_error = glGetError
1102 assert gl_error == gl_NO_ERROR else print_error gl_error
1103 end
1104
1105 glBindBuffer(gl_ARRAY_BUFFER, 0)
1106 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, 0)
1107 gl_error = glGetError
1108 assert gl_error == gl_NO_ERROR else print_error gl_error
1109 end
1110 end
1111
1112 # Representation of sprite data on the GPU
1113 #
1114 # The main purpose of this class is to optimize the use of contiguous
1115 # space in GPU memory. Each contiguous memory block can be drawn in a
1116 # single call. The starts index of each block is kept by `starts,
1117 # and the end + 1 by `ends`.
1118 #
1119 # The data can be compressed by a call to `defragment`.
1120 #
1121 # ~~~
1122 # intrude import gamnit::flat
1123 #
1124 # var array = new GroupedArray[String]
1125 # assert array.to_s == ""
1126 #
1127 # array.add "a"
1128 # array.add "b"
1129 # array.add "c"
1130 # array.add "d"
1131 # array.add "e"
1132 # array.add "f"
1133 # assert array.to_s == "[a,b,c,d,e,f]"
1134 # assert array.capacity == 6
1135 #
1136 # array.remove "a"
1137 # assert array.to_s == "[b,c,d,e,f]"
1138 #
1139 # array.remove "b"
1140 # assert array.to_s == "[c,d,e,f]"
1141 #
1142 # array.remove "f"
1143 # assert array.to_s == "[c,d,e]"
1144 #
1145 # array.remove "d"
1146 # assert array.to_s == "[c][e]"
1147 #
1148 # array.add "A"
1149 # assert array.to_s == "[A][c][e]"
1150 #
1151 # array.add "B"
1152 # assert array.to_s == "[A,B,c][e]"
1153 #
1154 # array.remove "e"
1155 # assert array.to_s == "[A,B,c]"
1156 #
1157 # array.add "D"
1158 # assert array.to_s == "[A,B,c,D]"
1159 #
1160 # array.add "E"
1161 # assert array.to_s == "[A,B,c,D,E]"
1162 # assert array.capacity == 6
1163 # assert array.length == 5
1164 #
1165 # array.remove "A"
1166 # array.remove "B"
1167 # array.remove "c"
1168 # array.remove "D"
1169 # array.remove "E"
1170 # assert array.to_s == ""
1171 #
1172 # array.add "a"
1173 # assert array.to_s == "[a]"
1174 # ~~~
1175 private class GroupedArray[E]
1176
1177 # Memory with actual objects, and null in empty slots
1178 var items = new Array[nullable E]
1179
1180 # Number of items in the array
1181 var length = 0
1182
1183 # Number of item slots in the array
1184 fun capacity: Int do return items.length
1185
1186 # List of available slots
1187 var available = new MinHeap[Int].default
1188
1189 # Start index of filled chunks
1190 var starts = new List[Int]
1191
1192 # Index of the spots after filled chunks
1193 var ends = new List[Int]
1194
1195 # Add `item` to the first available slot and return its index
1196 fun add(item: E): Int
1197 do
1198 length += 1
1199
1200 if available.not_empty then
1201 # starts & ends can't be empty
1202
1203 var i = available.take
1204 items[i] = item
1205
1206 if i == starts.first - 1 then
1207 # slot 0 free, 1 taken
1208 starts.first -= 1
1209 else if i == 0 then
1210 # slot 0 and more free
1211 starts.unshift 0
1212 ends.unshift 1
1213 else if starts.length >= 2 and ends.first + 1 == starts[1] then
1214 # merge 2 chunks
1215 ends.remove_at 0
1216 starts.remove_at 1
1217 else
1218 # at end of first chunk
1219 ends.first += 1
1220 end
1221 return i
1222 end
1223
1224 items.add item
1225 if ends.is_empty then
1226 starts.add 0
1227 ends.add 1
1228 else ends.last += 1
1229 return ends.last - 1
1230 end
1231
1232 # Remove the first instance of `item`
1233 fun remove(item: E)
1234 do
1235 var index = items.index_of(item)
1236 remove_at(item, index)
1237 end
1238
1239 # Remove `item` at `index`
1240 fun remove_at(item: E, index: Int)
1241 do
1242 var i = index
1243 length -= 1
1244 items[i] = null
1245
1246 var ii = 0
1247 for s in starts, e in ends do
1248 if s <= i and i < e then
1249 if s == e-1 then
1250 # single item chunk
1251 starts.remove_at ii
1252 ends.remove_at ii
1253
1254 if starts.is_empty then
1255 items.clear
1256 available.clear
1257 return
1258 end
1259 else if e-1 == i then
1260 # last item of chunk
1261 ends[ii] -= 1
1262
1263 else if s == i then
1264 # first item of chunk
1265 starts[ii] += 1
1266 else
1267 # break up chunk
1268 ends.insert(ends[ii], ii+1)
1269 ends[ii] = i
1270 starts.insert(i+1, ii+1)
1271 end
1272
1273 available.add i
1274 return
1275 end
1276 ii += 1
1277 end
1278
1279 abort
1280 end
1281
1282 # Defragment and compress everything into a single chunks beginning at 0
1283 #
1284 # Returns the elements that moved as a list.
1285 #
1286 # ~~~
1287 # intrude import gamnit::flat
1288 #
1289 # var array = new GroupedArray[String]
1290 # array.add "a"
1291 # array.add "b"
1292 # array.add "c"
1293 # array.add "d"
1294 # array.remove "c"
1295 # array.remove "a"
1296 # assert array.to_s == "[b][d]"
1297 #
1298 # var moved = array.defragment
1299 # assert moved.to_s == "[d]"
1300 # assert array.to_s == "[d,b]"
1301 # assert array.length == 2
1302 # assert array.capacity == 2
1303 #
1304 # array.add "e"
1305 # array.add "f"
1306 # assert array.to_s == "[d,b,e,f]"
1307 # ~~~
1308 fun defragment(max: nullable Int): Array[E]
1309 do
1310 app.perf_clock_sprites.lapse
1311 max = max or else length
1312
1313 var moved = new Array[E]
1314 while max > 0 and (starts.length > 1 or starts.first != 0) do
1315 var i = ends.last - 1
1316 var e = items[i]
1317 assert e != null
1318 remove e
1319 add e
1320 moved.add e
1321 max -= 1
1322 end
1323
1324 if starts.length == 1 and starts.first == 0 then
1325 for i in [length..capacity[ do items.pop
1326 available.clear
1327 end
1328
1329 sys.perfs["gamnit flat gpu defrag"].add app.perf_clock_sprites.lapse
1330 return moved
1331 end
1332
1333 redef fun to_s
1334 do
1335 var ss = new Array[String]
1336 for s in starts, e in ends do
1337 ss.add "["
1338 for i in [s..e[ do
1339 var item: nullable Object = items[i]
1340 if item == null then item = "null"
1341 ss.add item.to_s
1342 if i != e-1 then ss.add ","
1343 end
1344 ss.add "]"
1345 end
1346 return ss.join
1347 end
1348 end
1349
1350 # Optimized `GroupedArray` to use `Sprite::context_index` and avoid using `index_of`
1351 private class GroupedSprites
1352 super GroupedArray[Sprite]
1353
1354 redef fun add(item)
1355 do
1356 var index = super
1357 item.context_index = index
1358 return index
1359 end
1360
1361 redef fun remove(item) do remove_at(item, item.context_index)
1362 end
1363
1364 redef class GLfloatArray
1365 private fun fill_from_matrix(matrix: Matrix, dst_offset: nullable Int)
1366 do
1367 dst_offset = dst_offset or else 0
1368 var mat_len = matrix.width*matrix.height
1369 assert length >= mat_len + dst_offset
1370 native_array.fill_from_matrix_native(matrix.items, dst_offset, mat_len)
1371 end
1372 end
1373
1374 redef class NativeGLfloatArray
1375 private fun fill_from_matrix_native(matrix: matrix::NativeDoubleArray, dst_offset, len: Int) `{
1376 int i;
1377 for (i = 0; i < len; i ++)
1378 self[i+dst_offset] = (GLfloat)matrix[i];
1379 `}
1380 end