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, based 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 zoom in and out.
25 # 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 and the like.
29 # It can be used to standardize the size of the UI across devices.
30 # It is used to position the sprites in `App::ui_sprites`.
32 # See the sample game at `contrib/asteronits/`.
37 import geometry
::points_and_lines
38 import matrix
::projection
39 import more_collections
43 import gamnit
::cameras
44 import gamnit
::limit_fps
46 # Image to draw on screen
49 # Texture drawn to screen
50 var texture
: Texture is writable
52 # Position of this sprite in world coordinates
53 var center
: Point3d[Float] is writable
55 # Rotation on the Z axis
56 var rotation
= 0.0 is writable
58 # Scale applied to this sprite
59 var scale
= 1.0 is writable
61 # Transparency applied to the texture on draw
62 var alpha
= 1.0 is writable
66 var simple_2d_program
= app
.simple_2d_program
68 glActiveTexture gl_TEXTURE0
69 glBindTexture
(gl_TEXTURE_2D
, texture
.root
.gl_texture
)
71 simple_2d_program
.translation
.uniform
(center
.x
, -center
.y
, center
.z
, 0.0)
72 simple_2d_program
.color
.uniform
(1.0, 1.0, 1.0, alpha
)
73 simple_2d_program
.scale
.uniform scale
75 simple_2d_program
.use_texture
.uniform
true
76 simple_2d_program
.texture
.uniform
0
77 simple_2d_program
.tex_coord
.array
(texture
.texture_coords
, 2)
78 simple_2d_program
.coord
.array
(texture
.vertices
, 3)
80 simple_2d_program
.rotation
.uniform
new Matrix.rotation
(rotation
, 0.0, 0.0, 1.0)
82 glDrawArrays
(gl_TRIANGLE_STRIP
, 0, 4)
87 # Default graphic program to draw `sprites`
88 var simple_2d_program
= new Simple2dProgram is lazy
# TODO private
90 # Camera for world objects with perspective
92 # By default, the camera is configured to respect the resolution
93 # of the screen in world coordinates at `z == 0.0`.
94 var world_camera
: EulerCamera is lazy
do
95 var camera
= new EulerCamera(app
.display
.as(not null))
97 # Aim for pixel resolution at level 0
104 # Camera for UI elements using an orthogonal view
105 var ui_camera
: UICamera = new UICamera(app
.display
.as(not null)) is lazy
107 # Live sprites to draw in reference to `world_camera`
108 var sprites
: Sequence[Sprite] = new List[Sprite]
110 # UI sprites to draw in reference to `ui_camera`, over world `sprites`
111 var ui_sprites
: Sequence[Sprite] = new List[Sprite]
113 private var clock
= new Clock
119 var display
= display
120 assert display
!= null
122 var gl_error
= glGetError
123 assert gl_error
== gl_NO_ERROR
else print gl_error
126 var program
= simple_2d_program
127 program
.compile_and_link
129 var gamnit_error
= program
.error
130 assert gamnit_error
== null else print_error gamnit_error
133 gl
.capabilities
.blend
.enable
134 glBlendFunc
(gl_SRC_ALPHA
, gl_ONE_MINUS_SRC_ALPHA
)
137 gl
.capabilities
.depth_test
.enable
138 glDepthFunc gl_LEQUAL
141 # Prepare viewport and background color
142 glViewport
(0, 0, display
.width
, display
.height
)
143 glClearColor
(0.0, 0.0, 0.0, 1.0)
145 gl_error
= glGetError
146 assert gl_error
== gl_NO_ERROR
else print gl_error
149 for tex
in all_root_textures
do
152 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MIN_FILTER
, gl_LINEAR
)
153 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MAG_FILTER
, gl_LINEAR
)
155 gamnit_error
= tex
.error
156 assert gamnit_error
== null else print_error gamnit_error
160 redef fun frame_core
(display
)
162 # Prepare to draw, clear buffers
163 glClear
(gl_COLOR_BUFFER_BIT
| gl_DEPTH_BUFFER_BIT
)
166 var gl_error
= glGetError
167 assert gl_error
== gl_NO_ERROR
else print gl_error
169 # Update game logic and set sprites
170 var dt
= clock
.lapse
.to_f
173 # Draw and flip screen
174 frame_core_draw display
178 gl_error
= glGetError
179 assert gl_error
== gl_NO_ERROR
else print gl_error
182 # Draw sprites in `sprites` and `ui_sprites`
183 protected fun frame_core_draw
(display
: GamnitDisplay)
185 simple_2d_program
.use
187 # Set constant configs
188 simple_2d_program
.coord
.array_enabled
= true
189 simple_2d_program
.tex_coord
.array_enabled
= true
190 simple_2d_program
.color
.array_enabled
= false
192 # TODO optimize this draw to store constant values on the GPU
194 simple_2d_program
.mvp
.uniform world_camera
.mvp_matrix
195 for sprite
in sprites
do sprite
.draw
197 # Reset only the depth buffer
198 glClear gl_DEPTH_BUFFER_BIT
201 simple_2d_program
.mvp
.uniform ui_camera
.mvp_matrix
202 for sprite
in ui_sprites
do sprite
.draw
205 # Main method to refine in clients to update game logic and `sprites`
206 fun update
(dt
: Float) do end
211 simple_2d_program
.delete
214 var display
= display
215 if display
!= null then display
.close
221 # Vertices coordinates of the base geometry
222 private var vertices
: Array[Float] is lazy
do
226 var a
= [-0.5*w
, -0.5*h
, 0.0]
227 var b
= [ 0.5*w
, -0.5*h
, 0.0]
228 var c
= [-0.5*w
, 0.5*h
, 0.0]
229 var d
= [ 0.5*w
, 0.5*h
, 0.0]
231 var vertices
= new Array[Float]
232 for v
in [c
, d
, a
, b
] do vertices
.add_all v
236 # Coordinates of this texture on the `root` texture, with `[0..1.0]`
237 private var texture_coords
: Array[Float] is lazy
do
238 var a
= [offset_left
, offset_bottom
]
239 var b
= [offset_right
, offset_bottom
]
240 var c
= [offset_left
, offset_top
]
241 var d
= [offset_right
, offset_top
]
243 var texture_coords
= new Array[Float]
244 for v
in [c
, d
, a
, b
] do texture_coords
.add_all v
245 return texture_coords
249 # Graphic program to display simple models with a texture, translation, rotation and scale
250 class Simple2dProgram
251 super GamnitProgramFromSource
253 redef var vertex_shader_source
= """
254 // Vertex coordinates
255 attribute vec4 coord;
258 attribute vec4 color;
260 // Vertex translation
261 attribute vec4 translation;
264 attribute float scale;
266 // Vertex coordinates on textures
267 attribute vec2 tex_coord;
269 // Model view projection matrix
273 uniform mat4 rotation;
275 // Output for the fragment shader
276 varying vec4 v_color;
277 varying vec2 v_coord;
282 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation + translation) * mvp;
285 """ @ glsl_vertex_shader
287 redef var fragment_shader_source
= """
288 precision mediump float;
290 // Does this object use a texture?
291 uniform bool use_texture;
293 // Texture to apply on this object
294 uniform sampler2D texture;
296 // Input from the vertex shader
297 varying vec4 v_color;
298 varying vec2 v_coord;
303 gl_FragColor = v_color * texture2D(texture, v_coord);
304 if (gl_FragColor.a == 0.0) discard;
306 gl_FragColor = v_color;
309 """ @ glsl_fragment_shader
311 # Vertices coordinates
312 var coord
= attributes
["coord"].as(AttributeVec4) is lazy
314 # Should this program use the texture `texture`?
315 var use_texture
= uniforms
["use_texture"].as(UniformBool) is lazy
317 # Visible texture unit
318 var texture
= uniforms
["texture"].as(UniformSampler2D) is lazy
320 # Coordinates on the textures, per vertex
321 var tex_coord
= attributes
["tex_coord"].as(AttributeVec2) is lazy
323 # Color tint per vertex
324 var color
= attributes
["color"].as(AttributeVec4) is lazy
326 # Translation applied to each vertex
327 var translation
= attributes
["translation"].as(AttributeVec4) is lazy
330 var rotation
= uniforms
["rotation"].as(UniformMat4) is lazy
333 var scale
= attributes
["scale"].as(AttributeFloat) is lazy
335 # Model view projection matrix
336 var mvp
= uniforms
["mvp"].as(UniformMat4) is lazy
339 redef class Point3d[N
]
340 # Get a new `Point3d[Float]` with an offset of each axis of `x, y, z`
341 fun offset
(x
, y
, z
: Numeric): Point3d[Float]
343 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
)