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