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