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 # Core services for the `flat` API for 2D games
19 intrude import geometry
::points_and_lines
# For _x, _y and _z
21 import matrix
::projection
22 import more_collections
23 import performance_analysis
26 intrude import gamnit
::cameras
27 intrude import gamnit
::cameras_cache
28 import gamnit
::dynamic_resolution
30 # Visible 2D entity in the game world or UI
32 # Similar to `gamnit::Actor` which is in 3D.
34 # Each sprite associates a `texture` to the position `center`.
35 # The appearance is modified by `rotation`, `invert_x`,
36 # `scale`, `red`, `green`, `blue` and `alpha`.
37 # These values can be changed at any time and will trigger an update
38 # of the data on the GPU side, having a small performance cost.
40 # For a sprite to be visible, it must be added to either the world `sprites`
41 # or the `ui_sprites`.
42 # However, an instance of `Sprite` can only belong to a single `SpriteSet`
43 # at a time. The final on-screen position depends on the camera associated
47 # # Load texture and create sprite
48 # var texture = new Texture("path/in/assets.png")
49 # var sprite = new Sprite(texture, new Point3d[Float](0.0, 0.0, 0.0))
51 # # Add sprite to the visible game world
52 # app.sprites.add sprite
54 # # Extra configuration of the sprite
55 # sprite.rotation = pi/2.0
58 # # Show only the blue colors
63 # To add a sprite to the UI it can be anchored to screen borders
64 # with `ui_camera.top_left` and the likes.
67 # # Place it a bit off the top left of the screen
68 # var pos = app.ui_camera.top_left.offset(128.0, -128.0, 0)
70 # # Load texture and create sprite
71 # var texture = new Texture("path/in/assets.png")
72 # var sprite = new Sprite(texture, pos)
74 # # Add it to the UI (above world sprites)
75 # app.ui_sprites.add sprite
79 # Texture drawn to screen
80 var texture
: Texture is writable(texture_direct
=)
82 # Texture drawn to screen
83 fun texture
=(texture
: Texture)
85 if isset _texture
and texture
!= self.texture
then
87 if texture
.root
!= self.texture
.root
then needs_remap
89 texture_direct
= texture
92 # Center position of this sprite in world coordinates
93 var center
: Point3d[Float] is writable(center_direct
=), noautoinit
95 # Center position of this sprite in world coordinates
96 fun center
=(center
: Point3d[Float]) is autoinit
do
97 if isset _center
and center
!= self.center
then
99 self.center
.sprites_remove
self
102 center
.sprites_add
self
103 center_direct
= center
106 # Last animation set with `animate`
107 var animation
: nullable Animation = null
109 # Animation on the shader, if this changes it `needs_remap`
110 private var shader_animation
: nullable Animation = null
112 # Animation start time, relative to `sprite_set.time`
114 # At -1.0 if animation started before being assigned a `sprite_set`.
115 private var animation_start
= 0.0
117 # Number of loops to show `animation`
118 private var animation_loops
= 0.0
120 # Start the `animation` for `n_loops`, replacing the static `texture`
122 # By default, if `n_loops` is not set, the animation plays once.
123 # If `n_loops == -1.0` then the animation loops infinitely.
124 # Otherwise, the animation repeats, e.g. it repeats twice and a half
125 # if `n_loops == 2.5`.
127 # The animation can be stopped using `animate_stop`.
128 fun animate
(animation
: Animation, n_loops
: nullable Float)
130 if not animation
.valid
then print_error
"{class_name}::animate: invalid animation {animation}"
132 var shader_animation
= shader_animation
133 if shader_animation
== null or animation
.frames
.first
.root
!= shader_animation
.frames
.first
.root
then
134 # Resort with the new animation texture
140 var sprite_set
= sprite_set
141 animation_start
= if sprite_set
!= null then sprite_set
.time
else -1.0
142 animation_loops
= n_loops
or else 1.0
143 self.shader_animation
= animation
144 self.animation
= animation
147 # Stop any active `animation` to display the static `texture`
150 if animation
== null then return
155 # Rotation on the Z axis, positive values turn counterclockwise
156 var rotation
= 0.0 is writable(rotation_direct
=)
158 # Rotation on the Z axis, positive values turn counterclockwise
159 fun rotation
=(value
: Float)
161 if isset _rotation
and value
!= rotation
then needs_update
162 rotation_direct
= value
165 # Mirror `texture` horizontally, inverting each pixel on the X axis
166 var invert_x
= false is writable(invert_x_direct
=)
168 # Mirror `texture` horizontally, inverting each pixel on the X axis
169 fun invert_x
=(value
: Bool)
171 if isset _invert_x
and value
!= invert_x
then needs_update
172 invert_x_direct
= value
175 # Scale applied to this sprite
177 # The basic size of `self` depends on the size in pixels of `texture`.
178 var scale
= 1.0 is writable(scale_direct
=)
180 # Scale applied to this sprite
182 # The basic size of `self` depends on the size in pixels of `texture`.
183 fun scale
=(value
: Float)
185 if isset _scale
and value
!= scale
then needs_update
189 # Red tint applied to `texture` on draw
190 fun red
: Float do return tint
[0]
192 # Red tint applied to `texture` on draw
193 fun red
=(value
: Float)
195 if isset _tint
and value
!= red
then needs_update
199 # Green tint applied to `texture` on draw
200 fun green
: Float do return tint
[1]
202 # Green tint applied to `texture` on draw
203 fun green
=(value
: Float)
205 if isset _tint
and value
!= green
then needs_update
209 # Blue tint applied to `texture` on draw
210 fun blue
: Float do return tint
[2]
212 # Blue tint applied to `texture` on draw
213 fun blue
=(value
: Float)
215 if isset _tint
and value
!= blue
then needs_update
219 # Transparency applied to `texture` on draw
220 fun alpha
: Float do return tint
[3]
222 # Transparency applied to `texture` on draw
223 fun alpha
=(value
: Float)
225 if isset _tint
and value
!= alpha
then needs_update
229 # Tint applied to `texture` on draw
231 # Alternative to the accessors `red, green, blue & alpha`.
232 # Changes inside the array do not automatically set `needs_update`.
234 # Require: `tint.length == 4`
235 var tint
: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct
=)
237 # Tint applied to `texture` on draw, see `tint`
238 fun tint
=(value
: Array[Float])
240 if isset _tint
and value
!= tint
then needs_update
244 # Draw order, higher values cause this sprite to be drawn latter
246 # Change this value to avoid artifacts when drawing non-opaque sprites.
247 # In general, sprites with a non-opaque `texture` and sprites closer to
248 # the camera should have a higher value to be drawn last.
250 # Sprites sharing a `draw_order` are drawn in the same pass.
251 # The sprite to sprite draw order is undefined and may change when adding
252 # and removing sprites, or changing their attributes.
256 # Changing this value may have a negative performance impact if there are
257 # many different `draw_order` values across many sprites.
258 # Sprites sharing some attributes are drawn as group to reduce
259 # the communication overhead between the CPU and GPU,
260 # and changing `draw_order` may break up large groups into smaller groups.
261 var draw_order
= 0 is writable(draw_order_direct
=)
263 # Set draw order, see `draw_order`
264 fun draw_order
=(value
: Int)
266 if isset _draw_order
and value
!= draw_order
then needs_remap
267 draw_order_direct
= value
270 # Is this sprite static and added in bulk?
272 # Set to `true` to give a hint to the framework that this sprite won't
273 # change often and that it is added in bulk with other static sprites.
274 # This value can be ignored in the prototyping phase of a game and
275 # added only when better performance are needed.
276 var static
= false is writable(static_direct
=)
278 # Is this sprite static and added in bulk? see `static`
279 fun static
=(value
: Bool)
281 if isset _static
and value
!= static
then needs_remap
282 static_direct
= value
285 # Request an update on the CPU
287 # This is called automatically on modification of any value of `Sprite`.
288 # However, it can still be set manually if a modification can't be
289 # detected or by subclasses.
293 if c
== null then return
294 if c
.last_sprite_to_update
== self then return
295 c
.sprites_to_update
.add
self
296 c
.last_sprite_to_update
= self
299 # Request a resorting of this sprite in its sprite list
301 # Resorting is required when `static` or the root of `texture` changes.
302 # This is called automatically when such changes are detected.
303 # However, it can still be set manually if a modification can't be
304 # detected or by subclasses.
308 if l
!= null then l
.sprites_to_remap
.add
self
311 # Current context to which `self` was sorted
312 private var context
: nullable SpriteContext = null
315 private var context_index
: Int = -1
317 # Current context to which `self` belongs
318 private var sprite_set
: nullable SpriteSet = null
321 # Animation for sprites, set with `Sprite.animate`
323 # Two main services create animations:
324 # * The constructors accepts an array of textures and the number of frames per
325 # seconds: `new Animation(array_of_subtextures, 10.0)`
326 # * The method `Texture::to_animation` uses the whole texture
327 # dividing it in frames either on X or Y:
328 # `new Texture("path/in/assets.png").to_animation(30.0, 0, 12)`
331 # Frames composing this animation
333 # All frames must share the same `Texture::root`, be on a vertical or
334 # horizontal line, be spaced equally and share the same dimensions.
335 var frames
: SequenceRead[Texture]
337 # Frames per seconds, a higher value makes this animation faster
339 # The animation speed is also affected by `SpriteSet::time_mod`.
342 # Are the `frames` valid for an animation? (see the requirements in `frames`)
343 var valid
: Bool is lazy
do
344 var r
: nullable RootTexture = null
349 if r
!= f
.root
then return false
353 # TODO check for line, constant distance, and same aspect ratio.
360 # Default graphic program to draw `sprites`
361 private var simple_2d_program
= new Simple2dProgram is lazy
363 # Camera for world `sprites` and `depth::actors` with perspective
365 # By default, the camera is configured to a height of 1080 units
366 # of world coordinates at `z == 0.0`.
367 var world_camera
: EulerCamera is lazy
do
368 var camera
= new EulerCamera(app
.display
.as(not null))
370 # Aim for full HD pixel resolution at level 0
371 camera
.reset_height
1080.0
377 # Camera for `ui_sprites` using an orthogonal view
378 var ui_camera
= new UICamera(app
.display
.as(not null)) is lazy
380 # World sprites drawn as seen by `world_camera`
381 var sprites
= new SpriteSet
383 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
384 var ui_sprites
= new SpriteSet
386 # Main method to refine in clients to update game logic and `sprites`
387 fun update
(dt
: Float) do end
389 # Display `texture` as a splash screen
391 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
392 fun show_splash_screen
(texture
: Texture)
396 var splash
= new Sprite(texture
, ui_camera
.center
.offset
(0.0, 0.0, 0.0))
397 ui_sprites
.add splash
399 var display
= display
400 assert display
!= null
401 glClear gl_COLOR_BUFFER_BIT
402 frame_core_ui_sprites display
405 ui_sprites
.remove splash
409 # Support and implementation
411 # Main clock used to count each frame `dt`, lapsed for `update` only
412 private var clock
= new Clock is lazy
414 # Performance clock to for `frame_core_draw` operations
415 private var perf_clock_main
= new Clock
417 # Second performance clock for smaller operations
418 private var perf_clock_sprites
= new Clock is lazy
420 redef fun create_gamnit
426 # Prepare the flat framework services
429 var display
= display
430 assert display
!= null
432 var gl_error
= glGetError
433 assert gl_error
== gl_NO_ERROR
else print_error gl_error
436 var program
= simple_2d_program
437 program
.compile_and_link
439 var gamnit_error
= program
.error
440 assert gamnit_error
== null else print_error gamnit_error
443 gl
.capabilities
.blend
.enable
444 glBlendFunc
(gl_ONE
, gl_ONE_MINUS_SRC_ALPHA
)
447 gl
.capabilities
.depth_test
.enable
448 glDepthFunc gl_LEQUAL
451 # Prepare viewport and background color
452 glViewport
(0, 0, display
.width
, display
.height
)
453 glClearColor
(0.0, 0.0, 0.0, 1.0)
455 gl_error
= glGetError
456 assert gl_error
== gl_NO_ERROR
else print_error gl_error
459 for tex
in all_root_textures
do
461 gamnit_error
= tex
.error
462 if gamnit_error
!= null then print_error gamnit_error
464 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MIN_FILTER
, gl_LINEAR
)
465 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MAG_FILTER
, gl_LINEAR
)
477 simple_2d_program
.delete
480 var display
= display
481 if display
!= null then display
.close
484 redef fun on_resize
(display
)
488 world_camera
.mvp_matrix_cache
= null
489 ui_camera
.mvp_matrix_cache
= null
491 # Update all sprites in the UI
492 for sprite
in ui_sprites
do sprite
.needs_update
495 redef fun frame_core
(display
)
498 var gl_error
= glGetError
499 assert gl_error
== gl_NO_ERROR
else print_error gl_error
501 # Update game logic and set sprites
502 perf_clock_main
.lapse
503 var dt
= clock
.lapse
.to_f
506 sys
.perfs
["gamnit flat update client"].add perf_clock_main
.lapse
508 # Draw and flip screen
509 frame_core_draw display
513 gl_error
= glGetError
514 assert gl_error
== gl_NO_ERROR
else print_error gl_error
517 private var frame_dt
= 0.0
519 # Draw the whole screen, all `glDraw...` calls should be executed here
520 protected fun frame_core_draw
(display
: GamnitDisplay)
522 frame_core_dynamic_resolution_before display
524 perf_clock_main
.lapse
525 frame_core_world_sprites display
526 perfs
["gamnit flat world_sprites"].add perf_clock_main
.lapse
528 frame_core_ui_sprites display
529 perfs
["gamnit flat ui_sprites"].add perf_clock_main
.lapse
531 frame_core_dynamic_resolution_after display
534 private fun frame_core_sprites
(display
: GamnitDisplay, sprite_set
: SpriteSet, camera
: Camera)
536 var simple_2d_program
= app
.simple_2d_program
537 simple_2d_program
.use
538 simple_2d_program
.mvp
.uniform camera
.mvp_matrix
540 sprite_set
.time
+= frame_dt
*sprite_set
.time_mod
541 simple_2d_program
.time
.uniform sprite_set
.time
546 assert glGetError
== gl_NO_ERROR
549 # Draw world sprites from `sprites`
550 protected fun frame_core_world_sprites
(display
: GamnitDisplay)
552 frame_core_sprites
(display
, sprites
, world_camera
)
555 # Draw UI sprites from `ui_sprites`
556 protected fun frame_core_ui_sprites
(display
: GamnitDisplay)
558 # Reset only the depth buffer
559 glClear gl_DEPTH_BUFFER_BIT
561 frame_core_sprites
(display
, ui_sprites
, ui_camera
)
567 # Vertices coordinates of the base geometry
569 # Defines the default width and height of related sprites.
570 private var vertices
: Array[Float] is lazy
do
573 return [-0.5*w
, 0.5*h
, 0.0,
579 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
580 private var texture_coords
: Array[Float] is lazy
do
583 var b
= offset_bottom
591 # Coordinates of this texture on the `root` texture, inverting the X axis
592 private var texture_coords_invert_x
: Array[Float] is lazy
do
595 var b
= offset_bottom
603 # Convert to a sprite animation at `fps` speed with `x` or `y` frames
605 # The arguments `x` and `y` set the number of frames in the texture.
606 # Use `x` for an horizontal arrangement or `y` for vertical.
607 # One and only one of the arguments must be different than 0,
608 # as an animation can only be on a line and cannot wrap.
609 fun to_animation
(fps
: Float, x
, y
: Int): Animation
611 assert (x
== 0) != (y
== 0)
613 var n_frames
= x
.max
(y
)
614 var frames
= new Array[Texture]
616 var dx
= (x
/n_frames
).to_f
/n_frames
.to_f
617 var dy
= (y
/n_frames
).to_f
/n_frames
.to_f
618 var w
= if x
== 0 then 1.0 else dx
619 var h
= if y
== 0 then 1.0 else dy
622 for i
in n_frames
.times
do
623 frames
.add
new RelativeSubtexture(root
, left
, top
, left
+w
, top
+h
)
628 return new Animation(frames
, fps
)
632 # Graphic program to display simple models with a texture, translation, rotation and scale
633 private class Simple2dProgram
634 super GamnitProgramFromSource
636 redef var vertex_shader_source
= """
637 // Vertex coordinates
638 attribute vec4 coord;
641 attribute vec4 color;
643 // Vertex translation
644 attribute vec4 translation;
647 attribute float scale;
649 // Vertex coordinates on textures
650 attribute vec2 tex_coord;
652 // Model view projection matrix
655 // Current world time, in seconds
659 attribute vec4 rotation_row0;
660 attribute vec4 rotation_row1;
661 attribute vec4 rotation_row2;
662 attribute vec4 rotation_row3;
664 // Animation speed, frames per seconds
665 attribute float a_fps;
667 // Number of frames in the animation
668 attribute float a_n_frames;
670 // World coordinate of the animation (for aspect ratio)
671 attribute vec2 a_coord;
673 // Animation texture coordinates of the first frame
674 attribute vec2 a_tex_coord;
676 // Animation texture coordinates difference between frames
677 attribute vec2 a_tex_diff;
679 // Animation start time, in reference to `time`
680 attribute float a_start;
682 // Number of loops to play of the animation
683 attribute float a_loops;
687 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
690 // Output to the fragment shader
691 varying vec4 v_color;
692 varying vec2 v_coord;
694 // Is there an active animation?
695 varying float v_animated;
701 float end = a_start + a_loops/a_fps*a_n_frames;
702 if (a_fps != 0.0 && (a_loops == -1.0 || time < end)) {
704 float frame = mod(floor((time-a_start)*a_fps), a_n_frames);
705 v_coord = a_tex_coord + a_tex_diff*frame;
706 c = vec3(a_coord, coord.z);
715 gl_Position = (vec4(c * scale, 1.0) * rotation() + translation)* mvp;
716 v_color = vec4(color.rgb*color.a, color.a);
718 """ @ glsl_vertex_shader
720 redef var fragment_shader_source
= """
721 precision mediump float;
723 // Does this object use a texture?
724 uniform bool use_texture;
726 // Texture to apply on this object
727 uniform sampler2D texture0;
729 // Texture to apply on this object
730 uniform sampler2D animation;
732 // Input from the vertex shader
733 varying vec4 v_color;
734 varying vec2 v_coord;
735 varying float v_animated;
739 if (v_animated > 0.5) {
740 gl_FragColor = v_color * texture2D(animation, v_coord);
741 if (gl_FragColor.a <= 0.01) discard;
742 } else if (use_texture) {
743 gl_FragColor = v_color * texture2D(texture0, v_coord);
744 if (gl_FragColor.a <= 0.01) discard;
746 gl_FragColor = v_color;
749 """ @ glsl_fragment_shader
751 # Vertices coordinates
752 var coord
= attributes
["coord"].as(AttributeVec4) is lazy
754 # Should this program use the texture `texture`?
755 var use_texture
= uniforms
["use_texture"].as(UniformBool) is lazy
757 # Visible texture unit
758 var texture
= uniforms
["texture0"].as(UniformSampler2D) is lazy
760 # Coordinates on the textures, per vertex
761 var tex_coord
= attributes
["tex_coord"].as(AttributeVec2) is lazy
763 # Color tint per vertex
764 var color
= attributes
["color"].as(AttributeVec4) is lazy
766 # Translation applied to each vertex
767 var translation
= attributes
["translation"].as(AttributeVec4) is lazy
769 # Rotation matrix, row 0
770 var rotation_row0
= attributes
["rotation_row0"].as(AttributeVec4) is lazy
772 # Rotation matrix, row 1
773 var rotation_row1
= attributes
["rotation_row1"].as(AttributeVec4) is lazy
775 # Rotation matrix, row 2
776 var rotation_row2
= attributes
["rotation_row2"].as(AttributeVec4) is lazy
778 # Rotation matrix, row 3
779 var rotation_row3
= attributes
["rotation_row3"].as(AttributeVec4) is lazy
782 var scale
= attributes
["scale"].as(AttributeFloat) is lazy
784 # Model view projection matrix
785 var mvp
= uniforms
["mvp"].as(UniformMat4) is lazy
787 # World time, in seconds
788 var time
= uniforms
["time"].as(UniformFloat) is lazy
793 # Texture of all the frames of the animation
794 var animation_texture
= uniforms
["animation"].as(UniformSampler2D) is lazy
796 # Frame per second of the animation
797 var animation_fps
= attributes
["a_fps"].as(AttributeFloat) is lazy
799 # Number of frames in the animation
800 var animation_n_frames
= attributes
["a_n_frames"].as(AttributeFloat) is lazy
802 # Coordinates of each frame (mush be shared by all frames)
803 var animation_coord
= attributes
["a_coord"].as(AttributeVec2) is lazy
805 # Texture coordinates of the first frame
806 var animation_tex_coord
= attributes
["a_tex_coord"].as(AttributeVec2) is lazy
808 # Coordinate difference between each frame
809 var animation_tex_diff
= attributes
["a_tex_diff"].as(AttributeVec2) is lazy
811 # Animation start time, in seconds and in reference to `dt`
812 var animation_start
= attributes
["a_start"].as(AttributeFloat) is lazy
814 # Number of loops of the animation, -1 for infinite
815 var animation_loops
= attributes
["a_loops"].as(AttributeFloat) is lazy
818 redef class Point3d[N
]
820 # Associate each point to its sprites
822 private var sprites
: nullable Array[Sprite] = null
824 private fun sprites_add
(sprite
: Sprite)
826 var sprites
= sprites
827 if sprites
== null then
828 sprites
= new Array[Sprite]
829 self.sprites
= sprites
834 private fun sprites_remove
(sprite
: Sprite)
836 var sprites
= sprites
837 assert sprites
!= null
838 sprites
.remove sprite
842 # Notify `sprites` on attribute modification
844 private fun needs_update
846 var sprites
= sprites
847 if sprites
!= null then for s
in sprites
do s
.needs_update
852 if isset _x
and v
!= x
then needs_update
858 if isset _y
and v
!= y
then needs_update
864 if isset _z
and v
!= z
then needs_update
869 redef class OffsetPoint3d
872 if isset _x
and v
!= x
then needs_update
878 if isset _y
and v
!= y
then needs_update
884 if isset _z
and v
!= z
then needs_update
889 # Set of sprites sorting them into different `SpriteContext`
891 super HashSet[Sprite]
893 # Animation speed multiplier (0.0 to pause, 1.0 for normal speed, etc.)
894 var time_mod
= 1.0 is writable
896 # Seconds elapsed since the launch of the program, in world time responding to `time_mod`
899 # Map texture then static vs dynamic to a `SpriteContext`
900 private var contexts_map
= new HashMap4[RootTexture, nullable RootTexture, Bool, Int, Array[SpriteContext]]
902 # Contexts in `contexts_map`, sorted by draw order
903 private var contexts_items
= new Array[SpriteContext]
905 # Sprites needing resorting in `contexts_map`
906 private var sprites_to_remap
= new Array[Sprite]
908 # Add a sprite to the appropriate context
909 private fun map_sprite
(sprite
: Sprite)
911 assert sprite
.context
== null else print_error
"Sprite {sprite} belongs to another SpriteSet"
913 # Sort by texture and animation texture
914 var texture
= sprite
.texture
.root
915 var animation
= sprite
.animation
916 var animation_texture
= if animation
!= null then
917 animation
.frames
.first
.root
else null
918 var draw_order
= sprite
.draw_order
919 var contexts
= contexts_map
[texture
, animation_texture
, sprite
.static
, draw_order
]
922 if contexts
!= null then
923 for c
in contexts
.reverse_iterator
do
924 var size
= c
.sprites
.length
+ 1
925 if size
* 4 <= 0xffff then
932 if context
== null then
933 var usage
= if sprite
.static
then gl_STATIC_DRAW
else gl_DYNAMIC_DRAW
934 context
= new SpriteContext(texture
, animation_texture
, usage
, draw_order
)
936 if contexts
== null then
937 contexts
= new Array[SpriteContext]
938 contexts_map
[texture
, animation_texture
, sprite
.static
, draw_order
] = contexts
943 contexts_items
.add context
944 sprite_draw_order_sorter
.sort
(contexts_items
)
947 context
.sprites
.add sprite
948 context
.sprites_to_update
.add sprite
949 context
.last_sprite_to_update
= sprite
951 sprite
.context
= context
952 sprite
.sprite_set
= self
954 if animation
!= null and sprite
.animation_start
== -1.0 then
956 sprite
.animation_start
= time
960 # Remove a sprite from its context
961 private fun unmap_sprite
(sprite
: Sprite)
963 var context
= sprite
.context
964 assert context
!= null
965 context
.sprites
.remove sprite
967 sprite
.context
= null
968 sprite
.sprite_set
= null
971 # Draw all sprites by all contexts
974 # Remap sprites that may need to change context
975 for sprite
in sprites_to_remap
do
977 # Skip if it was removed from this set after being modified
978 if sprite
.sprite_set
!= self then continue
983 sprites_to_remap
.clear
986 for context
in contexts_items
do context
.draw
991 if contexts_items
.has
(e
.context
) then return
999 if e
isa Sprite then unmap_sprite e
1002 redef fun remove_all
(e
)
1004 if not has
(e
) then return
1010 for sprite
in self do
1011 sprite
.context
= null
1012 sprite
.sprite_set
= null
1015 for c
in contexts_items
do c
.destroy
1017 contexts_items
.clear
1018 sprites_to_remap
.clear
1023 for sprite
in self do
1024 sprite
.context
= null
1027 for c
in contexts_items
do c
.destroy
1029 contexts_items
.clear
1030 sprites_to_remap
.clear
1032 for sprite
in self do
1038 # Context for calls to `glDrawElements`
1040 # Each context has only one `texture` and `usage`, but many sprites.
1041 private class SpriteContext
1044 # Context config and state
1046 # Only root texture drawn by this context
1047 var texture
: nullable RootTexture
1049 # Only animation texture drawn by this context
1050 var animation_texture
: nullable RootTexture
1052 # OpenGL ES usage of `buffer_array` and `buffer_element`
1053 var usage
: GLBufferUsage
1055 # Draw order shared by all `sprites`
1058 # Sprites drawn by this context
1059 var sprites
= new GroupedSprites
1061 # Sprites to update since last `draw`
1062 var sprites_to_update
= new Set[Sprite]
1064 # Cache of the last `Sprite` added to `sprites_to_update` since the last call to `draw`
1065 var last_sprite_to_update
: nullable Sprite = null
1067 # Sprites that have been update and for which `needs_update` can be set to false
1068 var updated_sprites
= new Array[Sprite]
1070 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
1072 # Require: `resize_ratio >= 1.0`
1073 var resize_ratio
= 1.2
1078 # OpenGL ES buffer name for vertex data
1079 var buffer_array
: Int = -1
1081 # OpenGL ES buffer name for indices
1082 var buffer_element
: Int = -1
1084 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
1085 var buffer_capacity
= 0
1087 # C buffers used to pass the data of a single sprite
1088 var local_data_buffer
= new GLfloatArray(float_per_vertex
*4) is lazy
1089 var local_indices_buffer
= new CUInt16Array(indices_per_sprite
) is lazy
1094 # Number of GL_FLOAT per vertex of `Simple2dProgram`
1095 var float_per_vertex
: Int is lazy
do
1096 return 4 + 4 + 4 + # vec4 translation, vec4 color, vec4 coord,
1097 1 + 2 + 4*4 + # float scale, vec2 tex_coord, vec4 rotation_row*,
1098 1 + 1 + # float a_fps, float a_n_frames,
1099 2 + 2 + 2 + # vec2 a_coord, vec2 a_tex_coord, vec2 a_tex_diff,
1100 1 + 1 # float a_start, float a_loops
1103 # Number of bytes per vertex of `Simple2dProgram`
1104 var bytes_per_vertex
: Int is lazy
do
1105 var fs
= 4 # sizeof(GL_FLOAT)
1106 return fs
* float_per_vertex
1109 # Number of bytes per sprite
1110 var bytes_per_sprite
: Int is lazy
do return bytes_per_vertex
* 4
1112 # Number of vertex indices per sprite draw call (2 triangles)
1113 var indices_per_sprite
= 6
1118 # Allocate `buffer_array` and `buffer_element`
1121 var bufs
= glGenBuffers
(2)
1122 buffer_array
= bufs
[0]
1123 buffer_element
= bufs
[1]
1125 var gl_error
= glGetError
1126 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1129 # Destroy `buffer_array` and `buffer_element`
1132 glDeleteBuffers
([buffer_array
, buffer_element
])
1133 var gl_error
= glGetError
1134 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1140 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
1143 app
.perf_clock_sprites
.lapse
1145 # Allocate a bit more space
1146 var capacity
= (sprites
.capacity
.to_f
* resize_ratio
).to_i
1148 var array_bytes
= capacity
* bytes_per_sprite
1149 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
1150 assert glIsBuffer
(buffer_array
)
1151 glBufferData
(gl_ARRAY_BUFFER
, array_bytes
, new Pointer.nul
, usage
)
1152 var gl_error
= glGetError
1153 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1155 # GL_TRIANGLES 6 vertices * sprite
1156 var n_indices
= capacity
* indices_per_sprite
1157 var ius
= 2 # sizeof(GL_UNSIGNED_SHORT)
1158 var element_bytes
= n_indices
* ius
1159 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
1160 assert glIsBuffer
(buffer_element
)
1161 glBufferData
(gl_ELEMENT_ARRAY_BUFFER
, element_bytes
, new Pointer.nul
, usage
)
1162 gl_error
= glGetError
1163 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1165 buffer_capacity
= capacity
1167 sys
.perfs
["gamnit flat gpu resize"].add app
.perf_clock_sprites
.lapse
1170 # Update GPU data of `sprite`
1171 fun update_sprite
(sprite
: Sprite)
1173 var context
= sprite
.context
1174 if context
!= self then return
1176 var sprite_index
= sprite
.context_index
1177 assert sprite_index
!= -1
1181 var data
= local_data_buffer
1185 data
[o
+ 0] = sprite
.center
.x
1186 data
[o
+ 1] = sprite
.center
.y
1187 data
[o
+ 2] = sprite
.center
.z
1191 data
[o
+ 4] = sprite
.tint
[0]
1192 data
[o
+ 5] = sprite
.tint
[1]
1193 data
[o
+ 6] = sprite
.tint
[2]
1194 data
[o
+ 7] = sprite
.tint
[3]
1197 data
[o
+ 8] = sprite
.scale
1200 data
[o
+ 9] = sprite
.texture
.vertices
[v
*3+0]
1201 data
[o
+10] = sprite
.texture
.vertices
[v
*3+1]
1202 data
[o
+11] = sprite
.texture
.vertices
[v
*3+2]
1206 var texture
= texture
1207 if texture
!= null then
1208 var tc
= if sprite
.invert_x
then
1209 sprite
.texture
.texture_coords_invert_x
1210 else sprite
.texture
.texture_coords
1211 data
[o
+13] = tc
[v
*2+0]
1212 data
[o
+14] = tc
[v
*2+1]
1217 if sprite
.rotation
== 0.0 then
1218 # Cache the matrix at no rotation
1219 rot
= once
new Matrix.identity
(4)
1221 rot
= new Matrix.rotation
(sprite
.rotation
, 0.0, 0.0, 1.0)
1223 data
.fill_from_matrix
(rot
, o
+15)
1225 var animation
= sprite
.animation
1226 if animation
== null then
1227 for i
in [31..40] do data
[o
+i
] = 0.0
1230 data
[o
+31] = animation
.fps
1233 data
[o
+32] = animation
.frames
.length
.to_f
1236 data
[o
+33] = animation
.frames
.first
.vertices
[v
*3+0]
1237 data
[o
+34] = animation
.frames
.first
.vertices
[v
*3+1]
1240 var tc
= if sprite
.invert_x
then
1241 animation
.frames
.first
.texture_coords_invert_x
1242 else animation
.frames
.first
.texture_coords
1243 data
[o
+35] = tc
[v
*2]
1244 data
[o
+36] = tc
[v
*2+1]
1249 if animation
.frames
.length
> 1 then
1250 dx
= animation
.frames
[1].texture_coords
[0] - animation
.frames
[0].texture_coords
[0]
1251 dy
= animation
.frames
[1].texture_coords
[1] - animation
.frames
[0].texture_coords
[1]
1257 data
[o
+39] = sprite
.animation_start
1260 data
[o
+40] = sprite
.animation_loops
1263 o
+= float_per_vertex
1266 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
1267 glBufferSubData
(gl_ARRAY_BUFFER
, sprite_index
*bytes_per_sprite
, bytes_per_sprite
, data
.native_array
)
1269 var gl_error
= glGetError
1270 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1279 var indices
= local_indices_buffer
1280 var io
= sprite_index
*4
1288 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
1289 glBufferSubData
(gl_ELEMENT_ARRAY_BUFFER
, sprite_index
*6*2, 6*2, indices
.native_array
)
1291 gl_error
= glGetError
1292 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1295 # Draw all `sprites`
1297 # Call `resize` and `update_sprite` as needed before actual draw operation.
1299 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
1302 if buffer_array
== -1 then prepare
1304 assert buffer_array
> 0 and buffer_element
> 0 else
1305 print_error
"Internal error: {self} was destroyed"
1309 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
1310 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
1312 # Resize GPU buffers?
1313 var update_everything
= false
1314 if sprites
.capacity
> buffer_capacity
then
1315 # Try to defragment first
1316 var moved
= sprites
.defragment
1318 if sprites
.capacity
> buffer_capacity
then
1319 # Defragmentation wasn't enough, grow
1322 # We must update everything
1323 update_everything
= true
1324 for s
in sprites
.items
do if s
!= null then sprites_to_update
.add s
1326 # Just update the moved sprites
1327 for s
in moved
do sprites_to_update
.add s
1329 else if sprites
.available
.not_empty
then
1330 # Defragment a bit anyway
1331 # TODO defrag only when there's time left on a frame
1332 var moved
= sprites
.defragment
(1)
1333 for s
in moved
do sprites_to_update
.add s
1336 # Update GPU sprites data
1337 if sprites_to_update
.not_empty
or update_everything
then
1338 app
.perf_clock_sprites
.lapse
1340 if update_everything
then
1341 for sprite
in sprites
.items
do if sprite
!= null then
1342 update_sprite
(sprite
)
1345 for sprite
in sprites_to_update
do update_sprite
(sprite
)
1348 sprites_to_update
.clear
1349 last_sprite_to_update
= null
1351 sys
.perfs
["gamnit flat gpu update"].add app
.perf_clock_sprites
.lapse
1354 # Update uniforms specific to this context
1355 var texture
= texture
1356 app
.simple_2d_program
.use_texture
.uniform texture
!= null
1357 if texture
!= null then
1358 glActiveTexture gl_TEXTURE0
1359 glBindTexture
(gl_TEXTURE_2D
, texture
.gl_texture
)
1360 app
.simple_2d_program
.texture
.uniform
0
1362 var gl_error
= glGetError
1363 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1365 var animation
= animation_texture
1366 if animation
!= null then
1367 glActiveTexture gl_TEXTURE1
1368 glBindTexture
(gl_TEXTURE_2D
, animation
.gl_texture
)
1369 app
.simple_2d_program
.animation_texture
.uniform
1
1371 gl_error
= glGetError
1372 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1374 # Configure attributes, in order:
1375 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*,
1376 # a_fps, a_n_frames, a_coord, a_tex_coord, a_tex_diff, a_start, a_loops
1379 var p
= app
.simple_2d_program
1380 var sizeof_gl_float
= 4 # sizeof(GL_FLOAT)
1382 var size
= 4 # Number of floats
1383 glEnableVertexAttribArray p
.translation
.location
1384 glVertexAttribPointeri
(p
.translation
.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
.color
.location
1391 glVertexAttribPointeri
(p
.color
.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
.scale
.location
1398 glVertexAttribPointeri
(p
.scale
.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
.coord
.location
1405 glVertexAttribPointeri
(p
.coord
.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 glEnableVertexAttribArray p
.tex_coord
.location
1412 glVertexAttribPointeri
(p
.tex_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1413 offset
+= size
* sizeof_gl_float
1414 gl_error
= glGetError
1415 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1418 for r
in [p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
] do
1420 glEnableVertexAttribArray r
.location
1421 glVertexAttribPointeri
(r
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1423 offset
+= size
* sizeof_gl_float
1424 gl_error
= glGetError
1425 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1429 glEnableVertexAttribArray p
.animation_fps
.location
1430 glVertexAttribPointeri
(p
.animation_fps
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1431 offset
+= size
* sizeof_gl_float
1432 gl_error
= glGetError
1433 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1436 glEnableVertexAttribArray p
.animation_n_frames
.location
1437 glVertexAttribPointeri
(p
.animation_n_frames
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1438 offset
+= size
* sizeof_gl_float
1439 gl_error
= glGetError
1440 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1443 glEnableVertexAttribArray p
.animation_coord
.location
1444 glVertexAttribPointeri
(p
.animation_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1445 offset
+= size
* sizeof_gl_float
1446 gl_error
= glGetError
1447 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1450 glEnableVertexAttribArray p
.animation_tex_coord
.location
1451 glVertexAttribPointeri
(p
.animation_tex_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1452 offset
+= size
* sizeof_gl_float
1453 gl_error
= glGetError
1454 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1457 glEnableVertexAttribArray p
.animation_tex_diff
.location
1458 glVertexAttribPointeri
(p
.animation_tex_diff
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1459 offset
+= size
* sizeof_gl_float
1460 gl_error
= glGetError
1461 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1464 glEnableVertexAttribArray p
.animation_start
.location
1465 glVertexAttribPointeri
(p
.animation_start
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1466 offset
+= size
* sizeof_gl_float
1467 gl_error
= glGetError
1468 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1471 glEnableVertexAttribArray p
.animation_loops
.location
1472 glVertexAttribPointeri
(p
.animation_loops
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1473 offset
+= size
* sizeof_gl_float
1474 gl_error
= glGetError
1475 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1478 for s
in sprites
.starts
, e
in sprites
.ends
do
1480 glDrawElementsi
(gl_TRIANGLES
, l
*indices_per_sprite
, gl_UNSIGNED_SHORT
, 2*s
*indices_per_sprite
)
1481 gl_error
= glGetError
1482 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1486 for attr
in [p
.translation
, p
.color
, p
.scale
, p
.coord
, p
.tex_coord
,
1487 p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
: Attribute] do
1488 if not attr
.is_active
then continue
1489 glDisableVertexAttribArray
(attr
.location
)
1490 gl_error
= glGetError
1491 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1494 glBindBuffer
(gl_ARRAY_BUFFER
, 0)
1495 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, 0)
1496 gl_error
= glGetError
1497 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1501 # Representation of sprite data on the GPU
1503 # The main purpose of this class is to optimize the use of contiguous
1504 # space in GPU memory. Each contiguous memory block can be drawn in a
1505 # single call. The starts index of each block is kept by `starts,
1506 # and the end + 1 by `ends`.
1508 # The data can be compressed by a call to `defragment`.
1511 # intrude import gamnit::flat
1513 # var array = new GroupedArray[String]
1514 # assert array.to_s == ""
1522 # assert array.to_s == "[a,b,c,d,e,f]"
1523 # assert array.capacity == 6
1526 # assert array.to_s == "[b,c,d,e,f]"
1529 # assert array.to_s == "[c,d,e,f]"
1532 # assert array.to_s == "[c,d,e]"
1535 # assert array.to_s == "[c][e]"
1538 # assert array.to_s == "[A][c][e]"
1541 # assert array.to_s == "[A,B,c][e]"
1544 # assert array.to_s == "[A,B,c]"
1547 # assert array.to_s == "[A,B,c,D]"
1550 # assert array.to_s == "[A,B,c,D,E]"
1551 # assert array.capacity == 6
1552 # assert array.length == 5
1559 # assert array.to_s == ""
1562 # assert array.to_s == "[a]"
1564 private class GroupedArray[E
]
1566 # Memory with actual objects, and null in empty slots
1567 var items
= new Array[nullable E
]
1569 # Number of items in the array
1572 # Number of item slots in the array
1573 fun capacity
: Int do return items
.length
1575 # List of available slots
1576 var available
= new MinHeap[Int].default
1578 # Start index of filled chunks
1579 var starts
= new List[Int]
1581 # Index of the spots after filled chunks
1582 var ends
= new List[Int]
1584 # Add `item` to the first available slot and return its index
1585 fun add
(item
: E
): Int
1589 if available
.not_empty
then
1590 # starts & ends can't be empty
1592 var i
= available
.take
1595 if i
== starts
.first
- 1 then
1596 # slot 0 free, 1 taken
1599 # slot 0 and more free
1602 else if starts
.length
>= 2 and ends
.first
+ 1 == starts
[1] then
1607 # at end of first chunk
1614 if ends
.is_empty
then
1618 return ends
.last
- 1
1621 # Remove the first instance of `item`
1624 var index
= items
.index_of
(item
)
1625 remove_at
(item
, index
)
1628 # Remove `item` at `index`
1629 fun remove_at
(item
: E
, index
: Int)
1636 for s
in starts
, e
in ends
do
1637 if s
<= i
and i
< e
then
1643 if starts
.is_empty
then
1648 else if e-1
== i
then
1649 # last item of chunk
1653 # first item of chunk
1657 ends
.insert
(ends
[ii
], ii
+1)
1659 starts
.insert
(i
+1, ii
+1)
1671 # Defragment and compress everything into a single chunks beginning at 0
1673 # Returns the elements that moved as a list.
1676 # intrude import gamnit::flat
1678 # var array = new GroupedArray[String]
1685 # assert array.to_s == "[b][d]"
1687 # var moved = array.defragment
1688 # assert moved.to_s == "[d]"
1689 # assert array.to_s == "[d,b]"
1690 # assert array.length == 2
1691 # assert array.capacity == 2
1695 # assert array.to_s == "[d,b,e,f]"
1697 fun defragment
(max
: nullable Int): Array[E
]
1699 app
.perf_clock_sprites
.lapse
1700 max
= max
or else length
1702 var moved
= new Array[E
]
1703 while max
> 0 and (starts
.length
> 1 or starts
.first
!= 0) do
1704 var i
= ends
.last
- 1
1713 if starts
.length
== 1 and starts
.first
== 0 then
1714 for i
in [length
..capacity
[ do items
.pop
1718 sys
.perfs
["gamnit flat gpu defrag"].add app
.perf_clock_sprites
.lapse
1724 var ss
= new Array[String]
1725 for s
in starts
, e
in ends
do
1728 var item
: nullable Object = items
[i
]
1729 if item
== null then item
= "null"
1731 if i
!= e-1
then ss
.add
","
1739 # Optimized `GroupedArray` to use `Sprite::context_index` and avoid using `index_of`
1740 private class GroupedSprites
1741 super GroupedArray[Sprite]
1746 item
.context_index
= index
1750 redef fun remove
(item
) do remove_at
(item
, item
.context_index
)
1753 redef class GLfloatArray
1754 private fun fill_from_matrix
(matrix
: Matrix, dst_offset
: nullable Int)
1756 dst_offset
= dst_offset
or else add_index
1757 var mat_len
= matrix
.width
*matrix
.height
1758 assert length
>= mat_len
+ dst_offset
1759 native_array
.fill_from_matrix_native
(matrix
.items
, dst_offset
, mat_len
)
1760 add_index
+= mat_len
1764 redef class NativeGLfloatArray
1765 private fun fill_from_matrix_native
(matrix
: matrix
::NativeDoubleArray, dst_offset
, len
: Int) `{
1767 for (i = 0; i < len; i ++)
1768 self[i+dst_offset] = (GLfloat)matrix[i];
1773 private var sprite_draw_order_sorter
= new DrawOrderComparator is lazy
1776 # Sort `SpriteContext` by their `draw_order`
1777 private class DrawOrderComparator
1780 # This class can't set COMPARED because
1781 # `the public property cannot contain the private type...`
1782 #redef type COMPARED: SpriteContext
1784 # Require: `a isa SpriteContext and b isa SpriteContext`
1785 redef fun compare
(a
, b
)
1786 do return a
.as(SpriteContext).draw_order
<=> b
.as(SpriteContext).draw_order