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