lib/gamnit: divide frame_core_flat in 2 parts to draw particles in between
[nit.git] / lib / gamnit / flat.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Simple API for 2D games, based around `Sprite` and `App::update`
16 #
17 # Client programs should implement `App::update` to execute game logic and
18 # add instances of `Sprite` to `App::sprites` and `App::ui_sprites`.
19 # At each frame, all sprites are drawn to the screen.
20 #
21 # This system relies on two cameras `App::world_camera` and `App::ui_camera`.
22 #
23 # * `App::world_camera` applies a perspective effect to draw the game world.
24 # This camera is designed to be moved around to see the world as well as to zoom in and out.
25 # It is used to position the sprites in `App::sprites`.
26 #
27 # * `App::ui_camera` is a simple orthogonal camera to display UI objects.
28 # This camera should mostly be still, it can still move for chock effects 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`.
31 #
32 # See the sample game at `contrib/asteronits/`.
33 module flat
34
35 import glesv2
36
37 import geometry::points_and_lines
38 import matrix::projection
39 import more_collections
40 import realtime
41
42 import gamnit
43 import gamnit::cameras
44 import gamnit::limit_fps
45
46 # Image to draw on screen
47 class Sprite
48
49 # Texture drawn to screen
50 var texture: Texture is writable
51
52 # Position of this sprite in world coordinates
53 var center: Point3d[Float] is writable
54
55 # Rotation on the Z axis
56 var rotation = 0.0 is writable
57
58 # Scale applied to this sprite
59 var scale = 1.0 is writable
60
61 # Transparency applied to the texture on draw
62 var alpha = 1.0 is writable
63
64 private fun draw
65 do
66 var simple_2d_program = app.simple_2d_program
67
68 glActiveTexture gl_TEXTURE0
69 glBindTexture(gl_TEXTURE_2D, texture.root.gl_texture)
70
71 simple_2d_program.translation.array_enabled = false
72 simple_2d_program.color.array_enabled = false
73 simple_2d_program.scale.array_enabled = false
74
75 simple_2d_program.translation.uniform(center.x, -center.y, center.z, 0.0)
76 simple_2d_program.color.uniform(1.0, 1.0, 1.0, alpha)
77 simple_2d_program.scale.uniform scale
78
79 simple_2d_program.use_texture.uniform true
80 simple_2d_program.texture.uniform 0
81 simple_2d_program.tex_coord.array(texture.texture_coords, 2)
82 simple_2d_program.coord.array(texture.vertices, 3)
83
84 simple_2d_program.rotation.uniform new Matrix.rotation(rotation, 0.0, 0.0, 1.0)
85
86 glDrawArrays(gl_TRIANGLE_STRIP, 0, 4)
87 end
88 end
89
90 redef class App
91 # Default graphic program to draw `sprites`
92 var simple_2d_program = new Simple2dProgram is lazy # TODO private
93
94 # Camera for world objects with perspective
95 #
96 # By default, the camera is configured to respect the resolution
97 # of the screen in world coordinates at `z == 0.0`.
98 var world_camera: EulerCamera is lazy do
99 var camera = new EulerCamera(app.display.as(not null))
100
101 # Aim for pixel resolution at level 0
102 camera.reset_height
103 camera.near = 100.0
104
105 return camera
106 end
107
108 # Camera for UI elements using an orthogonal view
109 var ui_camera: UICamera = new UICamera(app.display.as(not null)) is lazy
110
111 # Live sprites to draw in reference to `world_camera`
112 var sprites: Sequence[Sprite] = new List[Sprite]
113
114 # UI sprites to draw in reference to `ui_camera`, over world `sprites`
115 var ui_sprites: Sequence[Sprite] = new List[Sprite]
116
117 private var clock = new Clock
118
119 redef fun on_create
120 do
121 super
122
123 var display = display
124 assert display != null
125
126 var gl_error = glGetError
127 assert gl_error == gl_NO_ERROR else print gl_error
128
129 # Prepare program
130 var program = simple_2d_program
131 program.compile_and_link
132
133 var gamnit_error = program.error
134 assert gamnit_error == null else print_error gamnit_error
135
136 # Enable blending
137 gl.capabilities.blend.enable
138 glBlendFunc(gl_SRC_ALPHA, gl_ONE_MINUS_SRC_ALPHA)
139
140 # Enable depth test
141 gl.capabilities.depth_test.enable
142 glDepthFunc gl_LEQUAL
143 glDepthMask true
144
145 # Prepare viewport and background color
146 glViewport(0, 0, display.width, display.height)
147 glClearColor(0.0, 0.0, 0.0, 1.0)
148
149 gl_error = glGetError
150 assert gl_error == gl_NO_ERROR else print gl_error
151
152 # Prepare to draw
153 for tex in all_root_textures do
154 tex.load
155
156 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
157 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
158
159 gamnit_error = tex.error
160 assert gamnit_error == null else print_error gamnit_error
161 end
162 end
163
164 redef fun frame_core(display)
165 do
166 # Prepare to draw, clear buffers
167 glClear(gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT)
168
169 # Check errors
170 var gl_error = glGetError
171 assert gl_error == gl_NO_ERROR else print gl_error
172
173 # Update game logic and set sprites
174 var dt = clock.lapse.to_f
175 update dt
176
177 # Draw and flip screen
178 frame_core_draw display
179 display.flip
180
181 # Check errors
182 gl_error = glGetError
183 assert gl_error == gl_NO_ERROR else print gl_error
184 end
185
186 # Draw the whole screen, all `glDraw...` calls should be executed here
187 protected fun frame_core_draw(display: GamnitDisplay)
188 do
189 frame_core_world_sprites display
190 frame_core_ui_sprites display
191 end
192
193 # Draw world sprites from `sprites`
194 protected fun frame_core_world_sprites(display: GamnitDisplay)
195 do
196 simple_2d_program.use
197
198 # Set constant configs
199 simple_2d_program.coord.array_enabled = true
200 simple_2d_program.tex_coord.array_enabled = true
201 simple_2d_program.color.array_enabled = false
202
203 # TODO optimize this draw to store constant values on the GPU
204 # World sprites
205 simple_2d_program.mvp.uniform world_camera.mvp_matrix
206 for sprite in sprites do sprite.draw
207 end
208
209 # Draw UI sprites from `ui_sprites`
210 protected fun frame_core_ui_sprites(display: GamnitDisplay)
211 do
212 simple_2d_program.use
213
214 # Set constant configs
215 simple_2d_program.coord.array_enabled = true
216 simple_2d_program.tex_coord.array_enabled = true
217 simple_2d_program.color.array_enabled = false
218
219 # Reset only the depth buffer
220 glClear gl_DEPTH_BUFFER_BIT
221
222 # UI sprites
223 simple_2d_program.mvp.uniform ui_camera.mvp_matrix
224 for sprite in ui_sprites do sprite.draw
225 end
226
227 # Main method to refine in clients to update game logic and `sprites`
228 fun update(dt: Float) do end
229
230 # Display `texture` as a splash screen
231 #
232 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
233 fun show_splash_screen(texture: Texture)
234 do
235 texture.load
236
237 ui_camera.reset_height 1080.0
238
239 var splash = new Sprite(texture, ui_camera.center)
240 ui_sprites.add splash
241
242 var display = display
243 assert display != null
244 glClear gl_COLOR_BUFFER_BIT
245 frame_core_ui_sprites display
246 display.flip
247
248 ui_sprites.remove splash
249 end
250
251 redef fun on_stop
252 do
253 # Clean up
254 simple_2d_program.delete
255
256 # Close gamnit
257 var display = display
258 if display != null then display.close
259 end
260 end
261
262 redef class Texture
263
264 # Vertices coordinates of the base geometry
265 private var vertices: Array[Float] is lazy do
266 var mod = 1.0
267 var w = width * mod
268 var h = height * mod
269 var a = [-0.5*w, -0.5*h, 0.0]
270 var b = [ 0.5*w, -0.5*h, 0.0]
271 var c = [-0.5*w, 0.5*h, 0.0]
272 var d = [ 0.5*w, 0.5*h, 0.0]
273
274 var vertices = new Array[Float]
275 for v in [c, d, a, b] do vertices.add_all v
276 return vertices
277 end
278
279 # Coordinates of this texture on the `root` texture, with `[0..1.0]`
280 private var texture_coords: Array[Float] is lazy do
281 var a = [offset_left, offset_bottom]
282 var b = [offset_right, offset_bottom]
283 var c = [offset_left, offset_top]
284 var d = [offset_right, offset_top]
285
286 var texture_coords = new Array[Float]
287 for v in [c, d, a, b] do texture_coords.add_all v
288 return texture_coords
289 end
290 end
291
292 # Graphic program to display simple models with a texture, translation, rotation and scale
293 class Simple2dProgram
294 super GamnitProgramFromSource
295
296 redef var vertex_shader_source = """
297 // Vertex coordinates
298 attribute vec4 coord;
299
300 // Vertex color tint
301 attribute vec4 color;
302
303 // Vertex translation
304 attribute vec4 translation;
305
306 // Vertex scaling
307 attribute float scale;
308
309 // Vertex coordinates on textures
310 attribute vec2 tex_coord;
311
312 // Model view projection matrix
313 uniform mat4 mvp;
314
315 // Rotation matrix
316 uniform mat4 rotation;
317
318 // Output for the fragment shader
319 varying vec4 v_color;
320 varying vec2 v_coord;
321
322 void main()
323 {
324 v_color = color;
325 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation + translation) * mvp;
326 v_coord = tex_coord;
327 }
328 """ @ glsl_vertex_shader
329
330 redef var fragment_shader_source = """
331 precision mediump float;
332
333 // Does this object use a texture?
334 uniform bool use_texture;
335
336 // Texture to apply on this object
337 uniform sampler2D texture;
338
339 // Input from the vertex shader
340 varying vec4 v_color;
341 varying vec2 v_coord;
342
343 void main()
344 {
345 if(use_texture) {
346 gl_FragColor = v_color * texture2D(texture, v_coord);
347 if (gl_FragColor.a == 0.0) discard;
348 } else {
349 gl_FragColor = v_color;
350 }
351 }
352 """ @ glsl_fragment_shader
353
354 # Vertices coordinates
355 var coord = attributes["coord"].as(AttributeVec4) is lazy
356
357 # Should this program use the texture `texture`?
358 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
359
360 # Visible texture unit
361 var texture = uniforms["texture"].as(UniformSampler2D) is lazy
362
363 # Coordinates on the textures, per vertex
364 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
365
366 # Color tint per vertex
367 var color = attributes["color"].as(AttributeVec4) is lazy
368
369 # Translation applied to each vertex
370 var translation = attributes["translation"].as(AttributeVec4) is lazy
371
372 # Rotation matrix
373 var rotation = uniforms["rotation"].as(UniformMat4) is lazy
374
375 # Scaling per vertex
376 var scale = attributes["scale"].as(AttributeFloat) is lazy
377
378 # Model view projection matrix
379 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
380 end
381
382 redef class Point3d[N]
383 # Get a new `Point3d[Float]` with an offset of each axis of `x, y, z`
384 fun offset(x, y, z: Numeric): Point3d[Float]
385 do
386 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)
387 end
388 end