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