1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Simple API for 2D games, built around `Sprite` and `App::update`
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.
21 # This system relies on two cameras `App::world_camera` and `App::ui_camera`.
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`.
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`.
32 # See the sample game at `contrib/asteronits/` and the basic project template
33 # at `lib/gamnit/examples/template/`.
37 intrude import geometry
::points_and_lines
# For _x, _y and _z
39 import matrix
::projection
40 import more_collections
41 import performance_analysis
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
50 # Visible 2D entity in the game world or UI
52 # Similar to `gamnit::Actor` which is in 3D.
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.
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
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))
71 # # Add sprite to the visible game world
72 # app.sprites.add sprite
74 # # Extra configuration of the sprite
75 # sprite.rotation = pi/2.0
78 # # Show only the blue colors
83 # To add a sprite to the UI it can be anchored to screen borders
84 # with `ui_camera.top_left` and the likes.
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)
90 # # Load texture and create sprite
91 # var texture = new Texture("path/in/assets.png")
92 # var sprite = new Sprite(texture, pos)
94 # # Add it to the UI (above world sprites)
95 # app.ui_sprites.add sprite
99 # Texture drawn to screen
100 var texture
: Texture is writable(texture_direct
=)
102 # Texture drawn to screen
103 fun texture
=(value
: Texture)
105 if isset _texture
and value
!= texture
then
107 if value
.root
!= texture
.root
then needs_remap
109 texture_direct
= value
112 # Center position of this sprite in world coordinates
113 var center
: Point3d[Float] is writable(center_direct
=), noautoinit
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
119 center
.sprites_remove
self
122 value
.sprites_add
self
123 center_direct
= value
126 # Last animation set with `animate`
127 var animation
: nullable Animation = null
129 # Animation on the shader, if this changes it `needs_remap`
130 private var shader_animation
: nullable Animation = null
132 # Animation start time, relative to `sprite_set.time`
134 # At -1.0 if animation started before being assigned a `sprite_set`.
135 private var animation_start
= 0.0
137 # Number of loops to show `animation`
138 private var animation_loops
= 0.0
140 # Start the `animation` for `n_loops`, replacing the static `texture`
142 # By default, if `n_loops` is not set, the animation plays once.
143 # If `n_loops == -1.0` then the animation loops infinitely.
144 # Otherwise, the animation repeats, e.g. it repeats twice and a half
145 # if `n_loops == 2.5`.
147 # The animation can be stopped using `animate_stop`.
148 fun animate
(animation
: Animation, n_loops
: nullable Float)
150 if not animation
.valid
then print_error
"{class_name}::animate: invalid animation {animation}"
152 var shader_animation
= shader_animation
153 if shader_animation
== null or animation
.frames
.first
.root
!= shader_animation
.frames
.first
.root
then
154 # Resort with the new animation texture
160 var sprite_set
= sprite_set
161 animation_start
= if sprite_set
!= null then sprite_set
.time
else -1.0
162 animation_loops
= n_loops
or else 1.0
163 self.shader_animation
= animation
164 self.animation
= animation
167 # Stop any active `animation` to display the static `texture`
170 if animation
== null then return
175 # Rotation on the Z axis, positive values turn counterclockwise
176 var rotation
= 0.0 is writable(rotation_direct
=)
178 # Rotation on the Z axis, positive values turn counterclockwise
179 fun rotation
=(value
: Float)
181 if isset _rotation
and value
!= rotation
then needs_update
182 rotation_direct
= value
185 # Mirror `texture` horizontally, inverting each pixel on the X axis
186 var invert_x
= false is writable(invert_x_direct
=)
188 # Mirror `texture` horizontally, inverting each pixel on the X axis
189 fun invert_x
=(value
: Bool)
191 if isset _invert_x
and value
!= invert_x
then needs_update
192 invert_x_direct
= value
195 # Scale applied to this sprite
197 # The basic size of `self` depends on the size in pixels of `texture`.
198 var scale
= 1.0 is writable(scale_direct
=)
200 # Scale applied to this sprite
202 # The basic size of `self` depends on the size in pixels of `texture`.
203 fun scale
=(value
: Float)
205 if isset _scale
and value
!= scale
then needs_update
209 # Red tint applied to `texture` on draw
210 fun red
: Float do return tint
[0]
212 # Red tint applied to `texture` on draw
213 fun red
=(value
: Float)
215 if isset _tint
and value
!= red
then needs_update
219 # Green tint applied to `texture` on draw
220 fun green
: Float do return tint
[1]
222 # Green tint applied to `texture` on draw
223 fun green
=(value
: Float)
225 if isset _tint
and value
!= green
then needs_update
229 # Blue tint applied to `texture` on draw
230 fun blue
: Float do return tint
[2]
232 # Blue tint applied to `texture` on draw
233 fun blue
=(value
: Float)
235 if isset _tint
and value
!= blue
then needs_update
239 # Transparency applied to `texture` on draw
240 fun alpha
: Float do return tint
[3]
242 # Transparency applied to `texture` on draw
243 fun alpha
=(value
: Float)
245 if isset _tint
and value
!= alpha
then needs_update
249 # Tint applied to `texture` on draw
251 # Alternative to the accessors `red, green, blue & alpha`.
252 # Changes inside the array do not automatically set `needs_update`.
254 # Require: `tint.length == 4`
255 var tint
: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct
=)
257 # Tint applied to `texture` on draw, see `tint`
258 fun tint
=(value
: Array[Float])
260 if isset _tint
and value
!= tint
then needs_update
264 # Is this sprite static and added in bulk?
266 # Set to `true` to give a hint to the framework that this sprite won't
267 # change often and that it is added in bulk with other static sprites.
268 # This value can be ignored in the prototyping phase of a game and
269 # added only when better performance are needed.
270 var static
= false is writable(static_direct
=)
272 # Is this sprite static and added in bulk? see `static`
273 fun static
=(value
: Bool)
275 if isset _static
and value
!= static
then needs_remap
276 static_direct
= value
279 # Request an update on the CPU
281 # This is called automatically on modification of any value of `Sprite`.
282 # However, it can still be set manually if a modification can't be
283 # detected or by subclasses.
287 if c
== null then return
288 if c
.last_sprite_to_update
== self then return
289 c
.sprites_to_update
.add
self
290 c
.last_sprite_to_update
= self
293 # Request a resorting of this sprite in its sprite list
295 # Resorting is required when `static` or the root of `texture` changes.
296 # This is called automatically when such changes are detected.
297 # However, it can still be set manually if a modification can't be
298 # detected or by subclasses.
302 if l
!= null then l
.sprites_to_remap
.add
self
305 # Current context to which `self` was sorted
306 private var context
: nullable SpriteContext = null
309 private var context_index
: Int = -1
311 # Current context to which `self` belongs
312 private var sprite_set
: nullable SpriteSet = null
315 # Animation for sprites, set with `Sprite.animate`
317 # Two main services create animations:
318 # * The constructors accepts an array of textures and the number of frames per
319 # seconds: `new Animation(array_of_subtextures, 10.0)`
320 # * The method `Texture::to_animation` uses the whole texture
321 # dividing it in frames either on X or Y:
322 # `new Texture("path/in/assets.png").to_animation(30.0, 0, 12)`
325 # Frames composing this animation
327 # All frames must share the same `Texture::root`, be on a vertical or
328 # horizontal line, be spaced equally and share the same dimensions.
329 var frames
: SequenceRead[Texture]
331 # Frames per seconds, a higher value makes this animation faster
333 # The animation speed is also affected by `SpriteSet::time_mod`.
336 # Are the `frames` valid for an animation? (see the requirements in `frames`)
337 var valid
: Bool is lazy
do
338 var r
: nullable RootTexture = null
343 if r
!= f
.root
then return false
347 # TODO check for line, constant distance, and same aspect ratio.
354 # Default graphic program to draw `sprites`
355 private var simple_2d_program
= new Simple2dProgram is lazy
357 # Camera for world `sprites` and `depth::actors` with perspective
359 # By default, the camera is configured to a height of 1080 units
360 # of world coordinates at `z == 0.0`.
361 var world_camera
: EulerCamera is lazy
do
362 var camera
= new EulerCamera(app
.display
.as(not null))
364 # Aim for full HD pixel resolution at level 0
365 camera
.reset_height
1080.0
371 # Camera for `ui_sprites` using an orthogonal view
372 var ui_camera
= new UICamera(app
.display
.as(not null)) is lazy
374 # World sprites drawn as seen by `world_camera`
375 var sprites
: Set[Sprite] = new SpriteSet
377 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
378 var ui_sprites
: Set[Sprite] = new SpriteSet
380 # Main method to refine in clients to update game logic and `sprites`
381 fun update
(dt
: Float) do end
383 # Display `texture` as a splash screen
385 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
386 fun show_splash_screen
(texture
: Texture)
390 var splash
= new Sprite(texture
, ui_camera
.center
.offset
(0.0, 0.0, 0.0))
391 ui_sprites
.add splash
393 var display
= display
394 assert display
!= null
395 glClear gl_COLOR_BUFFER_BIT
396 frame_core_ui_sprites display
399 ui_sprites
.remove splash
403 # Support and implementation
405 # Main clock used to count each frame `dt`, lapsed for `update` only
406 private var clock
= new Clock is lazy
408 # Performance clock to for `frame_core_draw` operations
409 private var perf_clock_main
= new Clock
411 # Second performance clock for smaller operations
412 private var perf_clock_sprites
= new Clock is lazy
418 var display
= display
419 assert display
!= null
421 var gl_error
= glGetError
422 assert gl_error
== gl_NO_ERROR
else print_error gl_error
425 var program
= simple_2d_program
426 program
.compile_and_link
428 var gamnit_error
= program
.error
429 assert gamnit_error
== null else print_error gamnit_error
432 gl
.capabilities
.blend
.enable
433 glBlendFunc
(gl_SRC_ALPHA
, gl_ONE_MINUS_SRC_ALPHA
)
436 gl
.capabilities
.depth_test
.enable
437 glDepthFunc gl_LEQUAL
440 # Prepare viewport and background color
441 glViewport
(0, 0, display
.width
, display
.height
)
442 glClearColor
(0.0, 0.0, 0.0, 1.0)
444 gl_error
= glGetError
445 assert gl_error
== gl_NO_ERROR
else print_error gl_error
448 for tex
in all_root_textures
do
450 gamnit_error
= tex
.error
451 if gamnit_error
!= null then print_error gamnit_error
453 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MIN_FILTER
, gl_LINEAR
)
454 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MAG_FILTER
, gl_LINEAR
)
461 simple_2d_program
.delete
464 var display
= display
465 if display
!= null then display
.close
468 redef fun on_resize
(display
)
472 world_camera
.mvp_matrix_cache
= null
473 ui_camera
.mvp_matrix_cache
= null
475 # Update all sprites in the UI
476 for sprite
in ui_sprites
do sprite
.needs_update
479 redef fun frame_core
(display
)
482 var gl_error
= glGetError
483 assert gl_error
== gl_NO_ERROR
else print_error gl_error
485 # Update game logic and set sprites
486 perf_clock_main
.lapse
487 var dt
= clock
.lapse
.to_f
490 sys
.perfs
["gamnit flat update client"].add perf_clock_main
.lapse
492 # Draw and flip screen
493 frame_core_draw display
497 gl_error
= glGetError
498 assert gl_error
== gl_NO_ERROR
else print_error gl_error
501 private var frame_dt
= 0.0
503 # Draw the whole screen, all `glDraw...` calls should be executed here
504 protected fun frame_core_draw
(display
: GamnitDisplay)
506 frame_core_dynamic_resolution_before display
508 perf_clock_main
.lapse
509 frame_core_world_sprites display
510 perfs
["gamnit flat world_sprites"].add perf_clock_main
.lapse
512 frame_core_ui_sprites display
513 perfs
["gamnit flat ui_sprites"].add perf_clock_main
.lapse
515 frame_core_dynamic_resolution_after display
518 private fun frame_core_sprites
(display
: GamnitDisplay, sprite_set
: SpriteSet, camera
: Camera)
520 var simple_2d_program
= app
.simple_2d_program
521 simple_2d_program
.use
522 simple_2d_program
.mvp
.uniform camera
.mvp_matrix
524 sprite_set
.time
+= frame_dt
*sprite_set
.time_mod
525 simple_2d_program
.time
.uniform sprite_set
.time
531 # Draw world sprites from `sprites`
532 protected fun frame_core_world_sprites
(display
: GamnitDisplay)
534 frame_core_sprites
(display
, sprites
.as(SpriteSet), world_camera
)
537 # Draw UI sprites from `ui_sprites`
538 protected fun frame_core_ui_sprites
(display
: GamnitDisplay)
540 # Reset only the depth buffer
541 glClear gl_DEPTH_BUFFER_BIT
543 frame_core_sprites
(display
, ui_sprites
.as(SpriteSet), ui_camera
)
549 # Vertices coordinates of the base geometry
551 # Defines the default width and height of related sprites.
552 private var vertices
: Array[Float] is lazy
do
555 return [-0.5*w
, 0.5*h
, 0.0,
561 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
562 private var texture_coords
: Array[Float] is lazy
do
565 var b
= offset_bottom
573 # Coordinates of this texture on the `root` texture, inverting the X axis
574 private var texture_coords_invert_x
: Array[Float] is lazy
do
577 var b
= offset_bottom
585 # Convert to a sprite animation at `fps` speed with `x` or `y` frames
587 # The arguments `x` and `y` set the number of frames in the texture.
588 # Use `x` for an horizontal arrangement or `y` for vertical.
589 # One and only one of the arguments must be different than 0,
590 # as an animation can only be on a line and cannot wrap.
591 fun to_animation
(fps
: Float, x
, y
: Int): Animation
593 assert (x
== 0) != (y
== 0)
595 var n_frames
= x
.max
(y
)
596 var frames
= new Array[Texture]
598 var dx
= (x
/n_frames
).to_f
/n_frames
.to_f
599 var dy
= (y
/n_frames
).to_f
/n_frames
.to_f
600 var w
= if x
== 0 then 1.0 else dx
601 var h
= if y
== 0 then 1.0 else dy
604 for i
in n_frames
.times
do
605 frames
.add
new RelativeSubtexture(root
, left
, top
, left
+w
, top
+h
)
610 return new Animation(frames
, fps
)
614 # Graphic program to display simple models with a texture, translation, rotation and scale
615 private class Simple2dProgram
616 super GamnitProgramFromSource
618 redef var vertex_shader_source
= """
619 // Vertex coordinates
620 attribute vec4 coord;
623 attribute vec4 color;
625 // Vertex translation
626 attribute vec4 translation;
629 attribute float scale;
631 // Vertex coordinates on textures
632 attribute vec2 tex_coord;
634 // Model view projection matrix
637 // Current world time, in seconds
641 attribute vec4 rotation_row0;
642 attribute vec4 rotation_row1;
643 attribute vec4 rotation_row2;
644 attribute vec4 rotation_row3;
646 // Animation speed, frames per seconds
647 attribute float a_fps;
649 // Number of frames in the animation
650 attribute float a_n_frames;
652 // World coordinate of the animation (for aspect ratio)
653 attribute vec2 a_coord;
655 // Animation texture coordinates of the first frame
656 attribute vec2 a_tex_coord;
658 // Animation texture coordinates difference between frames
659 attribute vec2 a_tex_diff;
661 // Animation start time, in reference to `time`
662 attribute float a_start;
664 // Number of loops to play of the animation
665 attribute float a_loops;
669 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
672 // Output to the fragment shader
673 varying vec4 v_color;
674 varying vec2 v_coord;
676 // Is there an active animation?
677 varying float v_animated;
683 float end = a_start + a_loops/a_fps*a_n_frames;
684 if (a_loops == -1.0 || time < end) {
686 float frame = mod(floor((time-a_start)*a_fps), a_n_frames);
687 v_coord = a_tex_coord + a_tex_diff*frame;
688 c = vec3(a_coord, coord.z);
697 gl_Position = (vec4(c * scale, 1.0) * rotation() + translation)* mvp;
700 """ @ glsl_vertex_shader
702 redef var fragment_shader_source
= """
703 precision mediump float;
705 // Does this object use a texture?
706 uniform bool use_texture;
708 // Texture to apply on this object
709 uniform sampler2D texture0;
711 // Texture to apply on this object
712 uniform sampler2D animation;
714 // Input from the vertex shader
715 varying vec4 v_color;
716 varying vec2 v_coord;
717 varying float v_animated;
721 if (v_animated > 0.5) {
722 gl_FragColor = v_color * texture2D(animation, v_coord);
723 if (gl_FragColor.a <= 0.01) discard;
724 } else if (use_texture) {
725 gl_FragColor = v_color * texture2D(texture0, v_coord);
726 if (gl_FragColor.a <= 0.01) discard;
728 gl_FragColor = v_color;
731 """ @ glsl_fragment_shader
733 # Vertices coordinates
734 var coord
= attributes
["coord"].as(AttributeVec4) is lazy
736 # Should this program use the texture `texture`?
737 var use_texture
= uniforms
["use_texture"].as(UniformBool) is lazy
739 # Visible texture unit
740 var texture
= uniforms
["texture0"].as(UniformSampler2D) is lazy
742 # Coordinates on the textures, per vertex
743 var tex_coord
= attributes
["tex_coord"].as(AttributeVec2) is lazy
745 # Color tint per vertex
746 var color
= attributes
["color"].as(AttributeVec4) is lazy
748 # Translation applied to each vertex
749 var translation
= attributes
["translation"].as(AttributeVec4) is lazy
751 # Rotation matrix, row 0
752 var rotation_row0
= attributes
["rotation_row0"].as(AttributeVec4) is lazy
754 # Rotation matrix, row 1
755 var rotation_row1
= attributes
["rotation_row1"].as(AttributeVec4) is lazy
757 # Rotation matrix, row 2
758 var rotation_row2
= attributes
["rotation_row2"].as(AttributeVec4) is lazy
760 # Rotation matrix, row 3
761 var rotation_row3
= attributes
["rotation_row3"].as(AttributeVec4) is lazy
764 var scale
= attributes
["scale"].as(AttributeFloat) is lazy
766 # Model view projection matrix
767 var mvp
= uniforms
["mvp"].as(UniformMat4) is lazy
769 # World time, in seconds
770 var time
= uniforms
["time"].as(UniformFloat) is lazy
775 # Texture of all the frames of the animation
776 var animation_texture
= uniforms
["animation"].as(UniformSampler2D) is lazy
778 # Frame per second of the animation
779 var animation_fps
= attributes
["a_fps"].as(AttributeFloat) is lazy
781 # Number of frames in the animation
782 var animation_n_frames
= attributes
["a_n_frames"].as(AttributeFloat) is lazy
784 # Coordinates of each frame (mush be shared by all frames)
785 var animation_coord
= attributes
["a_coord"].as(AttributeVec2) is lazy
787 # Texture coordinates of the first frame
788 var animation_tex_coord
= attributes
["a_tex_coord"].as(AttributeVec2) is lazy
790 # Coordinate difference between each frame
791 var animation_tex_diff
= attributes
["a_tex_diff"].as(AttributeVec2) is lazy
793 # Animation start time, in seconds and in reference to `dt`
794 var animation_start
= attributes
["a_start"].as(AttributeFloat) is lazy
796 # Number of loops of the animation, -1 for infinite
797 var animation_loops
= attributes
["a_loops"].as(AttributeFloat) is lazy
800 redef class Point3d[N
]
802 # Associate each point to its sprites
804 private var sprites
: nullable Array[Sprite] = null
806 private fun sprites_add
(sprite
: Sprite)
808 var sprites
= sprites
809 if sprites
== null then
810 sprites
= new Array[Sprite]
811 self.sprites
= sprites
816 private fun sprites_remove
(sprite
: Sprite)
818 var sprites
= sprites
819 assert sprites
!= null
820 sprites
.remove sprite
824 # Notify `sprites` on attribute modification
826 private fun needs_update
828 var sprites
= sprites
829 if sprites
!= null then for s
in sprites
do s
.needs_update
834 if isset _x
and v
!= x
then needs_update
840 if isset _y
and v
!= y
then needs_update
846 if isset _z
and v
!= z
then needs_update
851 redef class OffsetPoint3d
854 if isset _x
and v
!= x
then needs_update
860 if isset _y
and v
!= y
then needs_update
866 if isset _z
and v
!= z
then needs_update
871 # Set of sprites sorting them into different `SpriteContext`
872 private class SpriteSet
873 super HashSet[Sprite]
875 # Map texture then static vs dynamic to a `SpriteContext`
876 var contexts_map
= new HashMap3[RootTexture, nullable RootTexture, Bool, SpriteContext]
878 # Contexts in `contexts_map`
879 var contexts_items
= new Array[SpriteContext]
881 # Sprites needing resorting in `contexts_map`
882 var sprites_to_remap
= new Array[Sprite]
884 # Animation speed multiplier (0.0 to pause, 1.0 for normal speed, etc.)
885 var time_mod
= 1.0 is writable
887 # Seconds elapsed since the launch of the program, in world time responding to `time_mod`
890 # Add a sprite to the appropriate context
891 fun map_sprite
(sprite
: Sprite)
893 assert sprite
.context
== null else print_error
"Sprite {sprite} belongs to another SpriteSet"
895 # Sort by texture and animation texture
896 var texture
= sprite
.texture
.root
897 var animation
= sprite
.animation
898 var animation_texture
= if animation
!= null then
899 animation
.frames
.first
.root
else null
900 var context
= contexts_map
[texture
, animation_texture
, sprite
.static
]
902 if context
== null then
903 var usage
= if sprite
.static
then gl_STATIC_DRAW
else gl_DYNAMIC_DRAW
904 context
= new SpriteContext(texture
, animation_texture
, usage
)
906 contexts_map
[texture
, animation_texture
, sprite
.static
] = context
907 contexts_items
.add context
910 context
.sprites
.add sprite
911 context
.sprites_to_update
.add sprite
912 context
.last_sprite_to_update
= sprite
914 sprite
.context
= context
915 sprite
.sprite_set
= self
917 if animation
!= null and sprite
.animation_start
== -1.0 then
919 sprite
.animation_start
= time
923 # Remove a sprite from its context
924 fun unmap_sprite
(sprite
: Sprite)
926 var context
= sprite
.context
927 assert context
!= null
928 context
.sprites
.remove sprite
930 sprite
.context
= null
931 sprite
.sprite_set
= null
934 # Draw all sprites by all contexts
937 for sprite
in sprites_to_remap
do
941 sprites_to_remap
.clear
943 for context
in contexts_items
do context
.draw
948 if contexts_items
.has
(e
.context
) then return
956 if e
isa Sprite then unmap_sprite e
959 redef fun remove_all
(e
)
961 if not has
(e
) then return
967 for sprite
in self do
968 sprite
.context
= null
969 sprite
.sprite_set
= null
972 for c
in contexts_items
do c
.destroy
978 # Context for calls to `glDrawElements`
980 # Each context has only one `texture` and `usage`, but many sprites.
981 private class SpriteContext
984 # Context config and state
986 # Only root texture drawn by this context
987 var texture
: nullable RootTexture
989 # Only animation texture drawn by this context
990 var animation_texture
: nullable RootTexture
992 # OpenGL ES usage of `buffer_array` and `buffer_element`
993 var usage
: GLBufferUsage
995 # Sprites drawn by this context
996 var sprites
= new GroupedSprites
998 # Sprites to update since last `draw`
999 var sprites_to_update
= new Set[Sprite]
1001 # Cache of the last `Sprite` added to `sprites_to_update` since the last call to `draw`
1002 var last_sprite_to_update
: nullable Sprite = null
1004 # Sprites that have been update and for which `needs_update` can be set to false
1005 var updated_sprites
= new Array[Sprite]
1007 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
1009 # Require: `resize_ratio >= 1.0`
1010 var resize_ratio
= 1.2
1015 # OpenGL ES buffer name for vertex data
1016 var buffer_array
: Int = -1
1018 # OpenGL ES buffer name for indices
1019 var buffer_element
: Int = -1
1021 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
1022 var buffer_capacity
= 0
1024 # C buffers used to pass the data of a single sprite
1025 var local_data_buffer
= new GLfloatArray(float_per_vertex
*4) is lazy
1026 var local_indices_buffer
= new CUInt16Array(indices_per_sprite
) is lazy
1031 # Number of GL_FLOAT per vertex of `Simple2dProgram`
1032 var float_per_vertex
: Int is lazy
do
1033 return 4 + 4 + 4 + # vec4 translation, vec4 color, vec4 coord,
1034 1 + 2 + 4*4 + # float scale, vec2 tex_coord, vec4 rotation_row*,
1035 1 + 1 + # float a_fps, float a_n_frames,
1036 2 + 2 + 2 + # vec2 a_coord, vec2 a_tex_coord, vec2 a_tex_diff,
1037 1 + 1 # float a_start, float a_loops
1040 # Number of bytes per vertex of `Simple2dProgram`
1041 var bytes_per_vertex
: Int is lazy
do
1042 var fs
= 4 # sizeof(GL_FLOAT)
1043 return fs
* float_per_vertex
1046 # Number of bytes per sprite
1047 var bytes_per_sprite
: Int is lazy
do return bytes_per_vertex
* 4
1049 # Number of vertex indices per sprite draw call (2 triangles)
1050 var indices_per_sprite
= 6
1055 # Allocate `buffer_array` and `buffer_element`
1058 var bufs
= glGenBuffers
(2)
1059 buffer_array
= bufs
[0]
1060 buffer_element
= bufs
[1]
1062 var gl_error
= glGetError
1063 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1066 # Destroy `buffer_array` and `buffer_element`
1069 glDeleteBuffers
([buffer_array
, buffer_element
])
1070 var gl_error
= glGetError
1071 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1077 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
1080 app
.perf_clock_sprites
.lapse
1082 # Allocate a bit more space
1083 var capacity
= (sprites
.capacity
.to_f
* resize_ratio
).to_i
1085 var array_bytes
= capacity
* bytes_per_sprite
1086 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
1087 assert glIsBuffer
(buffer_array
)
1088 glBufferData
(gl_ARRAY_BUFFER
, array_bytes
, new Pointer.nul
, usage
)
1089 var gl_error
= glGetError
1090 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1092 # GL_TRIANGLES 6 vertices * sprite
1093 var n_indices
= capacity
* indices_per_sprite
1094 var ius
= 2 # sizeof(GL_UNSIGNED_SHORT)
1095 var element_bytes
= n_indices
* ius
1096 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
1097 assert glIsBuffer
(buffer_element
)
1098 glBufferData
(gl_ELEMENT_ARRAY_BUFFER
, element_bytes
, new Pointer.nul
, usage
)
1099 gl_error
= glGetError
1100 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1102 buffer_capacity
= capacity
1104 sys
.perfs
["gamnit flat gpu resize"].add app
.perf_clock_sprites
.lapse
1107 # Update GPU data of `sprite`
1108 fun update_sprite
(sprite
: Sprite)
1110 var context
= sprite
.context
1111 if context
!= self then return
1113 var sprite_index
= sprite
.context_index
1114 assert sprite_index
!= -1
1118 var data
= local_data_buffer
1122 data
[o
+ 0] = sprite
.center
.x
1123 data
[o
+ 1] = sprite
.center
.y
1124 data
[o
+ 2] = sprite
.center
.z
1128 data
[o
+ 4] = sprite
.tint
[0]
1129 data
[o
+ 5] = sprite
.tint
[1]
1130 data
[o
+ 6] = sprite
.tint
[2]
1131 data
[o
+ 7] = sprite
.tint
[3]
1134 data
[o
+ 8] = sprite
.scale
1137 data
[o
+ 9] = sprite
.texture
.vertices
[v
*3+0]
1138 data
[o
+10] = sprite
.texture
.vertices
[v
*3+1]
1139 data
[o
+11] = sprite
.texture
.vertices
[v
*3+2]
1143 var texture
= texture
1144 if texture
!= null then
1145 var tc
= if sprite
.invert_x
then
1146 sprite
.texture
.texture_coords_invert_x
1147 else sprite
.texture
.texture_coords
1148 data
[o
+13] = tc
[v
*2+0]
1149 data
[o
+14] = tc
[v
*2+1]
1154 if sprite
.rotation
== 0.0 then
1155 # Cache the matrix at no rotation
1156 rot
= once
new Matrix.identity
(4)
1158 rot
= new Matrix.rotation
(sprite
.rotation
, 0.0, 0.0, 1.0)
1160 data
.fill_from_matrix
(rot
, o
+15)
1162 var animation
= sprite
.animation
1163 if animation
== null then
1164 for i
in [31..40] do data
[o
+i
] = 0.0
1167 data
[o
+31] = animation
.fps
1170 data
[o
+32] = animation
.frames
.length
.to_f
1173 data
[o
+33] = animation
.frames
.first
.vertices
[v
*3+0]
1174 data
[o
+34] = animation
.frames
.first
.vertices
[v
*3+1]
1177 var tc
= if sprite
.invert_x
then
1178 animation
.frames
.first
.texture_coords_invert_x
1179 else animation
.frames
.first
.texture_coords
1180 data
[o
+35] = tc
[v
*2]
1181 data
[o
+36] = tc
[v
*2+1]
1184 var dx
= animation
.frames
[1].texture_coords
[0] - animation
.frames
[0].texture_coords
[0]
1185 var dy
= animation
.frames
[1].texture_coords
[1] - animation
.frames
[0].texture_coords
[1]
1190 data
[o
+39] = sprite
.animation_start
1193 data
[o
+40] = sprite
.animation_loops
1196 o
+= float_per_vertex
1199 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
1200 glBufferSubData
(gl_ARRAY_BUFFER
, sprite_index
*bytes_per_sprite
, bytes_per_sprite
, data
.native_array
)
1202 var gl_error
= glGetError
1203 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1212 var indices
= local_indices_buffer
1213 var io
= sprite_index
*4
1221 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
1222 glBufferSubData
(gl_ELEMENT_ARRAY_BUFFER
, sprite_index
*6*2, 6*2, indices
.native_array
)
1224 gl_error
= glGetError
1225 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1228 # Draw all `sprites`
1230 # Call `resize` and `update_sprite` as needed before actual draw operation.
1232 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
1235 if buffer_array
== -1 then prepare
1237 assert buffer_array
> 0 and buffer_element
> 0 else
1238 print_error
"Internal error: {self} was destroyed"
1242 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
1243 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
1245 # Resize GPU buffers?
1246 var update_everything
= false
1247 if sprites
.capacity
> buffer_capacity
then
1248 # Try to defragment first
1249 var moved
= sprites
.defragment
1251 if sprites
.capacity
> buffer_capacity
then
1252 # Defragmentation wasn't enough, grow
1255 # We must update everything
1256 update_everything
= true
1257 for s
in sprites
.items
do if s
!= null then sprites_to_update
.add s
1259 # Just update the moved sprites
1260 for s
in moved
do sprites_to_update
.add s
1262 else if sprites
.available
.not_empty
then
1263 # Defragment a bit anyway
1264 # TODO defrag only when there's time left on a frame
1265 var moved
= sprites
.defragment
(1)
1266 for s
in moved
do sprites_to_update
.add s
1269 # Update GPU sprites data
1270 if sprites_to_update
.not_empty
or update_everything
then
1271 app
.perf_clock_sprites
.lapse
1273 if update_everything
then
1274 for sprite
in sprites
.items
do if sprite
!= null then
1275 update_sprite
(sprite
)
1278 for sprite
in sprites_to_update
do update_sprite
(sprite
)
1281 sprites_to_update
.clear
1282 last_sprite_to_update
= null
1284 sys
.perfs
["gamnit flat gpu update"].add app
.perf_clock_sprites
.lapse
1287 # Update uniforms specific to this context
1288 var texture
= texture
1289 app
.simple_2d_program
.use_texture
.uniform texture
!= null
1290 if texture
!= null then
1291 glActiveTexture gl_TEXTURE0
1292 glBindTexture
(gl_TEXTURE_2D
, texture
.gl_texture
)
1293 app
.simple_2d_program
.texture
.uniform
0
1295 var gl_error
= glGetError
1296 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1298 var animation
= animation_texture
1299 if animation
!= null then
1300 glActiveTexture gl_TEXTURE1
1301 glBindTexture
(gl_TEXTURE_2D
, animation
.gl_texture
)
1302 app
.simple_2d_program
.animation_texture
.uniform
1
1304 gl_error
= glGetError
1305 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1307 # Configure attributes, in order:
1308 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*,
1309 # a_fps, a_n_frames, a_coord, a_tex_coord, a_tex_diff, a_start, a_loops
1312 var p
= app
.simple_2d_program
1313 var sizeof_gl_float
= 4 # sizeof(GL_FLOAT)
1315 var size
= 4 # Number of floats
1316 glEnableVertexAttribArray p
.translation
.location
1317 glVertexAttribPointeri
(p
.translation
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1318 offset
+= size
* sizeof_gl_float
1319 gl_error
= glGetError
1320 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1323 glEnableVertexAttribArray p
.color
.location
1324 glVertexAttribPointeri
(p
.color
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1325 offset
+= size
* sizeof_gl_float
1326 gl_error
= glGetError
1327 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1330 glEnableVertexAttribArray p
.scale
.location
1331 glVertexAttribPointeri
(p
.scale
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1332 offset
+= size
* sizeof_gl_float
1333 gl_error
= glGetError
1334 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1337 glEnableVertexAttribArray p
.coord
.location
1338 glVertexAttribPointeri
(p
.coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1339 offset
+= size
* sizeof_gl_float
1340 gl_error
= glGetError
1341 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1344 glEnableVertexAttribArray p
.tex_coord
.location
1345 glVertexAttribPointeri
(p
.tex_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1346 offset
+= size
* sizeof_gl_float
1347 gl_error
= glGetError
1348 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1351 for r
in [p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
] do
1353 glEnableVertexAttribArray r
.location
1354 glVertexAttribPointeri
(r
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1356 offset
+= size
* sizeof_gl_float
1357 gl_error
= glGetError
1358 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1362 glEnableVertexAttribArray p
.animation_fps
.location
1363 glVertexAttribPointeri
(p
.animation_fps
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1364 offset
+= size
* sizeof_gl_float
1365 gl_error
= glGetError
1366 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1369 glEnableVertexAttribArray p
.animation_n_frames
.location
1370 glVertexAttribPointeri
(p
.animation_n_frames
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1371 offset
+= size
* sizeof_gl_float
1372 gl_error
= glGetError
1373 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1376 glEnableVertexAttribArray p
.animation_coord
.location
1377 glVertexAttribPointeri
(p
.animation_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1378 offset
+= size
* sizeof_gl_float
1379 gl_error
= glGetError
1380 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1383 glEnableVertexAttribArray p
.animation_tex_coord
.location
1384 glVertexAttribPointeri
(p
.animation_tex_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1385 offset
+= size
* sizeof_gl_float
1386 gl_error
= glGetError
1387 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1390 glEnableVertexAttribArray p
.animation_tex_diff
.location
1391 glVertexAttribPointeri
(p
.animation_tex_diff
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1392 offset
+= size
* sizeof_gl_float
1393 gl_error
= glGetError
1394 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1397 glEnableVertexAttribArray p
.animation_start
.location
1398 glVertexAttribPointeri
(p
.animation_start
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1399 offset
+= size
* sizeof_gl_float
1400 gl_error
= glGetError
1401 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1404 glEnableVertexAttribArray p
.animation_loops
.location
1405 glVertexAttribPointeri
(p
.animation_loops
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1406 offset
+= size
* sizeof_gl_float
1407 gl_error
= glGetError
1408 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1411 for s
in sprites
.starts
, e
in sprites
.ends
do
1413 glDrawElementsi
(gl_TRIANGLES
, l
*indices_per_sprite
, gl_UNSIGNED_SHORT
, 2*s
*indices_per_sprite
)
1414 gl_error
= glGetError
1415 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1419 for attr
in [p
.translation
, p
.color
, p
.scale
, p
.coord
, p
.tex_coord
,
1420 p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
: Attribute] do
1421 if not attr
.is_active
then continue
1422 glDisableVertexAttribArray
(attr
.location
)
1423 gl_error
= glGetError
1424 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1427 glBindBuffer
(gl_ARRAY_BUFFER
, 0)
1428 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, 0)
1429 gl_error
= glGetError
1430 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1434 # Representation of sprite data on the GPU
1436 # The main purpose of this class is to optimize the use of contiguous
1437 # space in GPU memory. Each contiguous memory block can be drawn in a
1438 # single call. The starts index of each block is kept by `starts,
1439 # and the end + 1 by `ends`.
1441 # The data can be compressed by a call to `defragment`.
1444 # intrude import gamnit::flat
1446 # var array = new GroupedArray[String]
1447 # assert array.to_s == ""
1455 # assert array.to_s == "[a,b,c,d,e,f]"
1456 # assert array.capacity == 6
1459 # assert array.to_s == "[b,c,d,e,f]"
1462 # assert array.to_s == "[c,d,e,f]"
1465 # assert array.to_s == "[c,d,e]"
1468 # assert array.to_s == "[c][e]"
1471 # assert array.to_s == "[A][c][e]"
1474 # assert array.to_s == "[A,B,c][e]"
1477 # assert array.to_s == "[A,B,c]"
1480 # assert array.to_s == "[A,B,c,D]"
1483 # assert array.to_s == "[A,B,c,D,E]"
1484 # assert array.capacity == 6
1485 # assert array.length == 5
1492 # assert array.to_s == ""
1495 # assert array.to_s == "[a]"
1497 private class GroupedArray[E
]
1499 # Memory with actual objects, and null in empty slots
1500 var items
= new Array[nullable E
]
1502 # Number of items in the array
1505 # Number of item slots in the array
1506 fun capacity
: Int do return items
.length
1508 # List of available slots
1509 var available
= new MinHeap[Int].default
1511 # Start index of filled chunks
1512 var starts
= new List[Int]
1514 # Index of the spots after filled chunks
1515 var ends
= new List[Int]
1517 # Add `item` to the first available slot and return its index
1518 fun add
(item
: E
): Int
1522 if available
.not_empty
then
1523 # starts & ends can't be empty
1525 var i
= available
.take
1528 if i
== starts
.first
- 1 then
1529 # slot 0 free, 1 taken
1532 # slot 0 and more free
1535 else if starts
.length
>= 2 and ends
.first
+ 1 == starts
[1] then
1540 # at end of first chunk
1547 if ends
.is_empty
then
1551 return ends
.last
- 1
1554 # Remove the first instance of `item`
1557 var index
= items
.index_of
(item
)
1558 remove_at
(item
, index
)
1561 # Remove `item` at `index`
1562 fun remove_at
(item
: E
, index
: Int)
1569 for s
in starts
, e
in ends
do
1570 if s
<= i
and i
< e
then
1576 if starts
.is_empty
then
1581 else if e-1
== i
then
1582 # last item of chunk
1586 # first item of chunk
1590 ends
.insert
(ends
[ii
], ii
+1)
1592 starts
.insert
(i
+1, ii
+1)
1604 # Defragment and compress everything into a single chunks beginning at 0
1606 # Returns the elements that moved as a list.
1609 # intrude import gamnit::flat
1611 # var array = new GroupedArray[String]
1618 # assert array.to_s == "[b][d]"
1620 # var moved = array.defragment
1621 # assert moved.to_s == "[d]"
1622 # assert array.to_s == "[d,b]"
1623 # assert array.length == 2
1624 # assert array.capacity == 2
1628 # assert array.to_s == "[d,b,e,f]"
1630 fun defragment
(max
: nullable Int): Array[E
]
1632 app
.perf_clock_sprites
.lapse
1633 max
= max
or else length
1635 var moved
= new Array[E
]
1636 while max
> 0 and (starts
.length
> 1 or starts
.first
!= 0) do
1637 var i
= ends
.last
- 1
1646 if starts
.length
== 1 and starts
.first
== 0 then
1647 for i
in [length
..capacity
[ do items
.pop
1651 sys
.perfs
["gamnit flat gpu defrag"].add app
.perf_clock_sprites
.lapse
1657 var ss
= new Array[String]
1658 for s
in starts
, e
in ends
do
1661 var item
: nullable Object = items
[i
]
1662 if item
== null then item
= "null"
1664 if i
!= e-1
then ss
.add
","
1672 # Optimized `GroupedArray` to use `Sprite::context_index` and avoid using `index_of`
1673 private class GroupedSprites
1674 super GroupedArray[Sprite]
1679 item
.context_index
= index
1683 redef fun remove
(item
) do remove_at
(item
, item
.context_index
)
1686 redef class GLfloatArray
1687 private fun fill_from_matrix
(matrix
: Matrix, dst_offset
: nullable Int)
1689 dst_offset
= dst_offset
or else 0
1690 var mat_len
= matrix
.width
*matrix
.height
1691 assert length
>= mat_len
+ dst_offset
1692 native_array
.fill_from_matrix_native
(matrix
.items
, dst_offset
, mat_len
)
1696 redef class NativeGLfloatArray
1697 private fun fill_from_matrix_native
(matrix
: matrix
::NativeDoubleArray, dst_offset
, len
: Int) `{
1699 for (i = 0; i < len; i ++)
1700 self[i+dst_offset] = (GLfloat)matrix[i];