cafac8a98af95c187c8a05b64ab3bca9d3c52517
[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 import gamnit::cameras_cache
45 intrude import gamnit::cameras
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 c.sprites_to_update.add self
239 end
240
241 # Request a resorting of this sprite in its sprite list
242 #
243 # Resorting is required when `static` or the root of `texture` changes.
244 # This is called automatically when such changes are detected.
245 # However, it can still be set manually if a modification can't be
246 # detected or by subclasses.
247 fun needs_remap
248 do
249 var l = sprite_set
250 if l != null then l.sprites_to_remap.add self
251 end
252
253 # Current context to which `self` was sorted
254 private var context: nullable SpriteContext = null
255
256 # Current context to which `self` belongs
257 private var sprite_set: nullable SpriteSet = null
258 end
259
260 redef class App
261 # Default graphic program to draw `sprites`
262 private var simple_2d_program = new Simple2dProgram is lazy
263
264 # Camera for world `sprites` and `depth::actors` with perspective
265 #
266 # By default, the camera is configured to a height of 1080 units
267 # of world coordinates at `z == 0.0`.
268 var world_camera: EulerCamera is lazy do
269 var camera = new EulerCamera(app.display.as(not null))
270
271 # Aim for full HD pixel resolution at level 0
272 camera.reset_height 1080.0
273 camera.near = 10.0
274
275 return camera
276 end
277
278 # Camera for `ui_sprites` using an orthogonal view
279 var ui_camera = new UICamera(app.display.as(not null)) is lazy
280
281 # World sprites drawn as seen by `world_camera`
282 var sprites: Set[Sprite] = new SpriteSet
283
284 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
285 var ui_sprites: Set[Sprite] = new SpriteSet
286
287 # Main method to refine in clients to update game logic and `sprites`
288 fun update(dt: Float) do end
289
290 # Display `texture` as a splash screen
291 #
292 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
293 fun show_splash_screen(texture: Texture)
294 do
295 texture.load
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 # ---
588 # Associate each point to its sprites
589
590 private var sprites: nullable Array[Sprite] = null
591
592 private fun sprites_add(sprite: Sprite)
593 do
594 var sprites = sprites
595 if sprites == null then
596 sprites = new Array[Sprite]
597 self.sprites = sprites
598 end
599 sprites.add sprite
600 end
601
602 private fun sprites_remove(sprite: Sprite)
603 do
604 var sprites = sprites
605 assert sprites != null
606 sprites.remove sprite
607 end
608
609 # ---
610 # Notify `sprites` on attribute modification
611
612 private fun needs_update
613 do
614 var sprites = sprites
615 if sprites != null then for s in sprites do s.needs_update
616 end
617
618 redef fun x=(v)
619 do
620 if isset _x and v != x then needs_update
621 super
622 end
623
624 redef fun y=(v)
625 do
626 if isset _y and v != y then needs_update
627 super
628 end
629
630 redef fun z=(v)
631 do
632 if isset _z and v != z then needs_update
633 super
634 end
635 end
636
637 redef class OffsetPoint3d
638 redef fun x=(v)
639 do
640 if isset _x and v != x then needs_update
641 super
642 end
643
644 redef fun y=(v)
645 do
646 if isset _y and v != y then needs_update
647 super
648 end
649
650 redef fun z=(v)
651 do
652 if isset _z and v != z then needs_update
653 super
654 end
655 end
656
657 # Set of sprites sorting them into different `SpriteContext`
658 private class SpriteSet
659 super HashSet[Sprite]
660
661 # Map texture then static vs dynamic to a `SpriteContext`
662 var contexts_map = new HashMap2[RootTexture, Bool, SpriteContext]
663
664 # Contexts in `contexts_map`
665 var contexts_items = new Array[SpriteContext]
666
667 # Sprites needing resorting in `contexts_map`
668 var sprites_to_remap = new Array[Sprite]
669
670 # Add a sprite to the appropriate context
671 fun map_sprite(sprite: Sprite)
672 do
673 assert sprite.context == null else print_error "Sprite {sprite} belongs to another SpriteSet"
674
675 var texture = sprite.texture.root
676 var context = contexts_map[texture, sprite.static]
677
678 if context == null then
679 var usage = if sprite.static then gl_STATIC_DRAW else gl_DYNAMIC_DRAW
680 context = new SpriteContext(texture, usage)
681
682 contexts_map[texture, sprite.static] = context
683 contexts_items.add context
684 end
685
686 context.sprites.add sprite
687 context.sprites_to_update.add sprite
688
689 sprite.context = context
690 sprite.sprite_set = self
691 end
692
693 # Remove a sprite from its context
694 fun unmap_sprite(sprite: Sprite)
695 do
696 var context = sprite.context
697 assert context != null
698 context.sprites.remove sprite
699
700 sprite.context = null
701 sprite.sprite_set = null
702 end
703
704 # Draw all sprites by all contexts
705 fun draw
706 do
707 for sprite in sprites_to_remap do
708 unmap_sprite sprite
709 map_sprite sprite
710 end
711 sprites_to_remap.clear
712
713 for context in contexts_items do context.draw
714 end
715
716 redef fun add(e)
717 do
718 if contexts_items.has(e.context) then return
719 map_sprite e
720 super
721 end
722
723 redef fun remove(e)
724 do
725 super
726 if e isa Sprite then unmap_sprite e
727 end
728
729 redef fun remove_all(e)
730 do
731 if not has(e) then return
732 remove e
733 end
734
735 redef fun clear
736 do
737 for sprite in self do
738 sprite.context = null
739 sprite.sprite_set = null
740 end
741 super
742 for c in contexts_items do c.destroy
743 contexts_map.clear
744 contexts_items.clear
745 end
746 end
747
748 # Context for calls to `glDrawElements`
749 #
750 # Each context has only one `texture` and `usage`, but many sprites.
751 private class SpriteContext
752
753 # ---
754 # Context config and state
755
756 # Only root texture drawn by this context
757 var texture: nullable RootTexture
758
759 # OpenGL ES usage of `buffer_array` and `buffer_element`
760 var usage: GLBufferUsage
761
762 # Sprites drawn by this context
763 var sprites = new GroupedArray[Sprite]
764
765 # Sprites to update since last `draw`
766 var sprites_to_update = new Set[Sprite]
767
768 # Sprites that have been update and for which `needs_update` can be set to false
769 var updated_sprites = new Array[Sprite]
770
771 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
772 #
773 # Require: `resize_ratio >= 1.0`
774 var resize_ratio = 1.2
775
776 # ---
777 # OpenGL ES data
778
779 # OpenGL ES buffer name for vertex data
780 var buffer_array: Int = -1
781
782 # OpenGL ES buffer name for indices
783 var buffer_element: Int = -1
784
785 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
786 var buffer_capacity = 0
787
788 # C buffers used to pass the data of a single sprite
789 var local_data_buffer = new GLfloatArray(float_per_vertex*4) is lazy
790 var local_indices_buffer = new CUInt16Array(indices_per_sprite) is lazy
791
792 # ---
793 # Constants
794
795 # Number of GL_FLOAT per vertex of `Simple2dProgram`
796 var float_per_vertex: Int is lazy do
797 # vec4 translation, vec4 color, vec4 coord,
798 # float scale, vec2 tex_coord, vec4 rotation_row*
799 return 4 + 4 + 4 +
800 1 + 2 + 4*4
801 end
802
803 # Number of bytes per vertex of `Simple2dProgram`
804 var bytes_per_vertex: Int is lazy do
805 var fs = 4 # sizeof(GL_FLOAT)
806 return fs * float_per_vertex
807 end
808
809 # Number of bytes per sprite
810 var bytes_per_sprite: Int is lazy do return bytes_per_vertex * 4
811
812 # Number of vertex indices per sprite draw call (2 triangles)
813 var indices_per_sprite = 6
814
815 # ---
816 # Main services
817
818 # Allocate `buffer_array` and `buffer_element`
819 fun prepare
820 do
821 var bufs = glGenBuffers(2)
822 buffer_array = bufs[0]
823 buffer_element = bufs[1]
824
825 var gl_error = glGetError
826 assert gl_error == gl_NO_ERROR else print_error gl_error
827 end
828
829 # Destroy `buffer_array` and `buffer_element`
830 fun destroy
831 do
832 glDeleteBuffers([buffer_array, buffer_element])
833 var gl_error = glGetError
834 assert gl_error == gl_NO_ERROR else print_error gl_error
835
836 buffer_array = -1
837 buffer_element = -1
838 end
839
840 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
841 fun resize
842 do
843 app.perf_clock_sprites.lapse
844
845 # Allocate a bit more space
846 var capacity = (sprites.capacity.to_f * resize_ratio).to_i
847
848 var array_bytes = capacity * bytes_per_sprite
849 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
850 assert glIsBuffer(buffer_array)
851 glBufferData(gl_ARRAY_BUFFER, array_bytes, new Pointer.nul, usage)
852 var gl_error = glGetError
853 assert gl_error == gl_NO_ERROR else print_error gl_error
854
855 # GL_TRIANGLES 6 vertices * sprite
856 var n_indices = capacity * indices_per_sprite
857 var ius = 2 # sizeof(GL_UNSIGNED_SHORT)
858 var element_bytes = n_indices * ius
859 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
860 assert glIsBuffer(buffer_element)
861 glBufferData(gl_ELEMENT_ARRAY_BUFFER, element_bytes, new Pointer.nul, usage)
862 gl_error = glGetError
863 assert gl_error == gl_NO_ERROR else print_error gl_error
864
865 buffer_capacity = capacity
866
867 sys.perfs["gamnit flat gpu resize"].add app.perf_clock_sprites.lapse
868 end
869
870 # Update GPU data of `sprite`
871 fun update_sprite(sprite: Sprite)
872 do
873 var sprite_index = sprites.index_of(sprite)
874 if sprite_index == -1 then return
875
876 # Vertices data
877
878 var data = local_data_buffer
879 var o = 0
880 for v in [0..4[ do
881 # vec4 translation
882 data[o+ 0] = sprite.center.x
883 data[o+ 1] = sprite.center.y
884 data[o+ 2] = sprite.center.z
885 data[o+ 3] = 0.0
886
887 # vec4 color
888 data[o+ 4] = sprite.tint[0]
889 data[o+ 5] = sprite.tint[1]
890 data[o+ 6] = sprite.tint[2]
891 data[o+ 7] = sprite.tint[3]
892
893 # float scale
894 data[o+ 8] = sprite.scale
895
896 # vec4 coord
897 data[o+ 9] = sprite.texture.vertices[v*3+0]
898 data[o+10] = sprite.texture.vertices[v*3+1]
899 data[o+11] = sprite.texture.vertices[v*3+2]
900 data[o+12] = 0.0
901
902 # vec2 tex_coord
903 var texture = texture
904 if texture != null then
905 var tc = if sprite.invert_x then
906 sprite.texture.texture_coords_invert_x
907 else sprite.texture.texture_coords
908 data[o+13] = tc[v*2+0]
909 data[o+14] = tc[v*2+1]
910 end
911
912 # mat4 rotation
913 var rot
914 if sprite.rotation == 0.0 then
915 # Cache the matrix at no rotation
916 rot = once new Matrix.identity(4)
917 else
918 rot = new Matrix.rotation(sprite.rotation, 0.0, 0.0, 1.0)
919 end
920 data.fill_from_matrix(rot, o+15)
921
922 o += float_per_vertex
923 end
924
925 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
926 glBufferSubData(gl_ARRAY_BUFFER, sprite_index*bytes_per_sprite, bytes_per_sprite, data.native_array)
927
928 var gl_error = glGetError
929 assert gl_error == gl_NO_ERROR else print_error gl_error
930
931 # Element / indices
932 #
933 # 0--1
934 # | /|
935 # |/ |
936 # 2--3
937
938 var indices = local_indices_buffer
939 var io = sprite_index*4
940 indices[0] = io+0
941 indices[1] = io+2
942 indices[2] = io+1
943 indices[3] = io+1
944 indices[4] = io+2
945 indices[5] = io+3
946
947 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
948 glBufferSubData(gl_ELEMENT_ARRAY_BUFFER, sprite_index*6*2, 6*2, indices.native_array)
949
950 gl_error = glGetError
951 assert gl_error == gl_NO_ERROR else print_error gl_error
952 end
953
954 # Draw all `sprites`
955 #
956 # Call `resize` and `update_sprite` as needed before actual draw operation.
957 #
958 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
959 fun draw
960 do
961 if buffer_array == -1 then prepare
962
963 assert buffer_array > 0 and buffer_element > 0 else
964 print_error "Internal error: {self} was destroyed"
965 end
966
967 # Setup
968 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
969 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
970
971 # Resize GPU buffers?
972 if sprites.capacity > buffer_capacity then
973 # Try to defragment first
974 var moved = sprites.defragment
975
976 if sprites.capacity > buffer_capacity then
977 # Defragmentation wasn't enough, grow
978 resize
979
980 # We must update everything
981 for s in sprites.items do if s != null then sprites_to_update.add s
982 else
983 # Just update the moved sprites
984 for s in moved do sprites_to_update.add s
985 end
986 else if sprites.available.not_empty then
987 # Defragment a bit anyway
988 # TODO defrag only when there's time left on a frame
989 var moved = sprites.defragment(1)
990 for s in moved do sprites_to_update.add s
991 end
992
993 # Update GPU sprites data
994 if sprites_to_update.not_empty then
995 app.perf_clock_sprites.lapse
996
997 for sprite in sprites_to_update do update_sprite(sprite)
998 sprites_to_update.clear
999
1000 sys.perfs["gamnit flat gpu update"].add app.perf_clock_sprites.lapse
1001 end
1002
1003 # Update uniforms specific to this context
1004 var texture = texture
1005 app.simple_2d_program.use_texture.uniform texture != null
1006 if texture != null then
1007 glActiveTexture gl_TEXTURE0
1008 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
1009 app.simple_2d_program.texture.uniform 0
1010 end
1011 var gl_error = glGetError
1012 assert gl_error == gl_NO_ERROR else print_error gl_error
1013
1014 # Configure attributes, in order:
1015 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*
1016 var offset = 0
1017 var p = app.simple_2d_program
1018 var sizeof_gl_float = 4 # sizeof(GL_FLOAT)
1019
1020 var size = 4 # Number of floats
1021 glEnableVertexAttribArray p.translation.location
1022 glVertexAttribPointeri(p.translation.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.color.location
1029 glVertexAttribPointeri(p.color.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 = 1
1035 glEnableVertexAttribArray p.scale.location
1036 glVertexAttribPointeri(p.scale.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 glEnableVertexAttribArray p.coord.location
1043 glVertexAttribPointeri(p.coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1044 offset += size * sizeof_gl_float
1045 gl_error = glGetError
1046 assert gl_error == gl_NO_ERROR else print_error gl_error
1047
1048 size = 2
1049 glEnableVertexAttribArray p.tex_coord.location
1050 glVertexAttribPointeri(p.tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1051 offset += size * sizeof_gl_float
1052 gl_error = glGetError
1053 assert gl_error == gl_NO_ERROR else print_error gl_error
1054
1055 size = 4
1056 for r in [p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3] do
1057 if r.is_active then
1058 glEnableVertexAttribArray r.location
1059 glVertexAttribPointeri(r.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
1060 end
1061 offset += size * sizeof_gl_float
1062 gl_error = glGetError
1063 assert gl_error == gl_NO_ERROR else print_error gl_error
1064 end
1065
1066 # Actual draw
1067 for s in sprites.starts, e in sprites.ends do
1068 var l = e-s
1069 glDrawElementsi(gl_TRIANGLES, l*indices_per_sprite, gl_UNSIGNED_SHORT, 2*s*indices_per_sprite)
1070 gl_error = glGetError
1071 assert gl_error == gl_NO_ERROR else print_error gl_error
1072 end
1073
1074 # Take down
1075 for attr in [p.translation, p.color, p.scale, p.coord, p.tex_coord,
1076 p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3: Attribute] do
1077 if not attr.is_active then continue
1078 glDisableVertexAttribArray(attr.location)
1079 gl_error = glGetError
1080 assert gl_error == gl_NO_ERROR else print_error gl_error
1081 end
1082
1083 glBindBuffer(gl_ARRAY_BUFFER, 0)
1084 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, 0)
1085 gl_error = glGetError
1086 assert gl_error == gl_NO_ERROR else print_error gl_error
1087 end
1088 end
1089
1090 # Representation of sprite data on the GPU
1091 #
1092 # The main purpose of this class is to optimize the use of contiguous
1093 # space in GPU memory. Each contiguous memory block can be drawn in a
1094 # single call. The starts index of each block is kept by `starts,
1095 # and the end + 1 by `ends`.
1096 #
1097 # The data can be compressed by a call to `defragment`.
1098 #
1099 # ~~~
1100 # intrude import gamnit::flat
1101 #
1102 # var array = new GroupedArray[String]
1103 # assert array.to_s == ""
1104 #
1105 # array.add "a"
1106 # array.add "b"
1107 # array.add "c"
1108 # array.add "d"
1109 # array.add "e"
1110 # array.add "f"
1111 # assert array.to_s == "[a,b,c,d,e,f]"
1112 # assert array.capacity == 6
1113 #
1114 # array.remove "a"
1115 # assert array.to_s == "[b,c,d,e,f]"
1116 #
1117 # array.remove "b"
1118 # assert array.to_s == "[c,d,e,f]"
1119 #
1120 # array.remove "f"
1121 # assert array.to_s == "[c,d,e]"
1122 #
1123 # array.remove "d"
1124 # assert array.to_s == "[c][e]"
1125 #
1126 # array.add "A"
1127 # assert array.to_s == "[A][c][e]"
1128 #
1129 # array.add "B"
1130 # assert array.to_s == "[A,B,c][e]"
1131 #
1132 # array.remove "e"
1133 # assert array.to_s == "[A,B,c]"
1134 #
1135 # array.add "D"
1136 # assert array.to_s == "[A,B,c,D]"
1137 #
1138 # array.add "E"
1139 # assert array.to_s == "[A,B,c,D,E]"
1140 # assert array.capacity == 6
1141 # assert array.length == 5
1142 #
1143 # array.remove "A"
1144 # array.remove "B"
1145 # array.remove "c"
1146 # array.remove "D"
1147 # array.remove "E"
1148 # assert array.to_s == ""
1149 #
1150 # array.add "a"
1151 # assert array.to_s == "[a]"
1152 # ~~~
1153 private class GroupedArray[E]
1154
1155 # Memory with actual objects, and null in empty slots
1156 var items = new Array[nullable E]
1157
1158 # Number of items in the array
1159 var length = 0
1160
1161 # Number of item slots in the array
1162 fun capacity: Int do return items.length
1163
1164 # Index of `item`
1165 fun index_of(item: E): Int do return items.index_of(item)
1166
1167 # List of available slots
1168 var available = new MinHeap[Int].default
1169
1170 # Start index of filled chunks
1171 var starts = new List[Int]
1172
1173 # Index of the spots after filled chunks
1174 var ends = new List[Int]
1175
1176 # Add `item` to the first available slot
1177 fun add(item: E)
1178 do
1179 length += 1
1180
1181 if available.not_empty then
1182 # starts & ends can't be empty
1183
1184 var i = available.take
1185 items[i] = item
1186
1187 if i == starts.first - 1 then
1188 # slot 0 free, 1 taken
1189 starts.first -= 1
1190 else if i == 0 then
1191 # slot 0 and more free
1192 starts.unshift 0
1193 ends.unshift 1
1194 else if starts.length >= 2 and ends.first + 1 == starts[1] then
1195 # merge 2 chunks
1196 ends.remove_at 0
1197 starts.remove_at 1
1198 else
1199 # at end of first chunk
1200 ends.first += 1
1201 end
1202 return
1203 end
1204
1205 items.add item
1206 if ends.is_empty then
1207 starts.add 0
1208 ends.add 1
1209 else ends.last += 1
1210 end
1211
1212 # Remove the first instance of `item`
1213 fun remove(item: E)
1214 do
1215 var i = items.index_of(item)
1216 assert i != -1
1217 length -= 1
1218 items[i] = null
1219
1220 var ii = 0
1221 for s in starts, e in ends do
1222 if s <= i and i < e then
1223 if s == e-1 then
1224 # single item chunk
1225 starts.remove_at ii
1226 ends.remove_at ii
1227
1228 if starts.is_empty then
1229 items.clear
1230 available.clear
1231 return
1232 end
1233 else if e-1 == i then
1234 # last item of chunk
1235 ends[ii] -= 1
1236
1237 else if s == i then
1238 # first item of chunk
1239 starts[ii] += 1
1240 else
1241 # break up chunk
1242 ends.insert(ends[ii], ii+1)
1243 ends[ii] = i
1244 starts.insert(i+1, ii+1)
1245 end
1246
1247 available.add i
1248 return
1249 end
1250 ii += 1
1251 end
1252
1253 abort
1254 end
1255
1256 # Defragment and compress everything into a single chunks beginning at 0
1257 #
1258 # Returns the elements that moved as a list.
1259 #
1260 # ~~~
1261 # intrude import gamnit::flat
1262 #
1263 # var array = new GroupedArray[String]
1264 # array.add "a"
1265 # array.add "b"
1266 # array.add "c"
1267 # array.add "d"
1268 # array.remove "c"
1269 # array.remove "a"
1270 # assert array.to_s == "[b][d]"
1271 #
1272 # var moved = array.defragment
1273 # assert moved.to_s == "[d]"
1274 # assert array.to_s == "[d,b]"
1275 # assert array.length == 2
1276 # assert array.capacity == 2
1277 #
1278 # array.add "e"
1279 # array.add "f"
1280 # assert array.to_s == "[d,b,e,f]"
1281 # ~~~
1282 fun defragment(max: nullable Int): Array[E]
1283 do
1284 app.perf_clock_sprites.lapse
1285 max = max or else length
1286
1287 var moved = new Array[E]
1288 while max > 0 and (starts.length > 1 or starts.first != 0) do
1289 var i = ends.last - 1
1290 var e = items[i]
1291 remove e
1292 add e
1293 moved.add e
1294 max -= 1
1295 end
1296
1297 if starts.length == 1 and starts.first == 0 then
1298 for i in [length..capacity[ do items.pop
1299 available.clear
1300 end
1301
1302 sys.perfs["gamnit flat gpu defrag"].add app.perf_clock_sprites.lapse
1303 return moved
1304 end
1305
1306 redef fun to_s
1307 do
1308 var ss = new Array[String]
1309 for s in starts, e in ends do
1310 ss.add "["
1311 for i in [s..e[ do
1312 var item: nullable Object = items[i]
1313 if item == null then item = "null"
1314 ss.add item.to_s
1315 if i != e-1 then ss.add ","
1316 end
1317 ss.add "]"
1318 end
1319 return ss.join
1320 end
1321 end
1322
1323 redef class GLfloatArray
1324 private fun fill_from_matrix(matrix: Matrix, dst_offset: nullable Int)
1325 do
1326 dst_offset = dst_offset or else 0
1327 var mat_len = matrix.width*matrix.height
1328 assert length >= mat_len + dst_offset
1329 native_array.fill_from_matrix_native(matrix.items, dst_offset, mat_len)
1330 end
1331 end
1332
1333 redef class NativeGLfloatArray
1334 private fun fill_from_matrix_native(matrix: matrix::NativeDoubleArray, dst_offset, len: Int) `{
1335 int i;
1336 for (i = 0; i < len; i ++)
1337 self[i+dst_offset] = (GLfloat)matrix[i];
1338 `}
1339 end