b489f1c442db8025d3edfb326140f11d9e63c7fd
[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 # Mirror `texture` horizontally, inverting each pixel on the X axis
59 var invert_x = false is writable
60
61 # Scale applied to this sprite
62 var scale = 1.0 is writable
63
64 # Transparency applied to the texture on draw
65 fun alpha: Float do return tint[3]
66
67 # Transparency applied to the texture on draw
68 fun alpha=(value: Float) do tint[3] = value
69
70 # Tint applied to the texture on draw
71 #
72 # Require: `tint.length == 4`
73 var tint: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable
74
75 private fun draw
76 do
77 var simple_2d_program = app.simple_2d_program
78
79 glActiveTexture gl_TEXTURE0
80 glBindTexture(gl_TEXTURE_2D, texture.root.gl_texture)
81
82 simple_2d_program.translation.array_enabled = false
83 simple_2d_program.color.array_enabled = false
84 simple_2d_program.scale.array_enabled = false
85
86 simple_2d_program.translation.uniform(center.x, center.y, center.z, 0.0)
87 simple_2d_program.color.uniform(tint[0], tint[1], tint[2], tint[3])
88 simple_2d_program.scale.uniform scale
89
90 simple_2d_program.use_texture.uniform true
91 simple_2d_program.texture.uniform 0
92 simple_2d_program.tex_coord.array(
93 if invert_x then
94 texture.texture_coords_invert_x
95 else texture.texture_coords, 2)
96 simple_2d_program.coord.array(texture.vertices, 3)
97
98 simple_2d_program.rotation.uniform new Matrix.rotation(rotation, 0.0, 0.0, 1.0)
99
100 glDrawArrays(gl_TRIANGLE_STRIP, 0, 4)
101 end
102 end
103
104 redef class App
105 # Default graphic program to draw `sprites`
106 var simple_2d_program = new Simple2dProgram is lazy # TODO private
107
108 # Camera for world objects with perspective
109 #
110 # By default, the camera is configured to respect the resolution
111 # of the screen in world coordinates at `z == 0.0`.
112 var world_camera: EulerCamera is lazy do
113 var camera = new EulerCamera(app.display.as(not null))
114
115 # Aim for pixel resolution at level 0
116 camera.reset_height
117 camera.near = 100.0
118
119 return camera
120 end
121
122 # Camera for UI elements using an orthogonal view
123 var ui_camera: UICamera = new UICamera(app.display.as(not null)) is lazy
124
125 # Live sprites to draw in reference to `world_camera`
126 var sprites: Sequence[Sprite] = new List[Sprite]
127
128 # UI sprites to draw in reference to `ui_camera`, over world `sprites`
129 var ui_sprites: Sequence[Sprite] = new List[Sprite]
130
131 private var clock = new Clock is lazy
132
133 redef fun on_create
134 do
135 super
136
137 var display = display
138 assert display != null
139
140 var gl_error = glGetError
141 assert gl_error == gl_NO_ERROR else print gl_error
142
143 # Prepare program
144 var program = simple_2d_program
145 program.compile_and_link
146
147 var gamnit_error = program.error
148 assert gamnit_error == null else print_error gamnit_error
149
150 # Enable blending
151 gl.capabilities.blend.enable
152 glBlendFunc(gl_SRC_ALPHA, gl_ONE_MINUS_SRC_ALPHA)
153
154 # Enable depth test
155 gl.capabilities.depth_test.enable
156 glDepthFunc gl_LEQUAL
157 glDepthMask true
158
159 # Prepare viewport and background color
160 glViewport(0, 0, display.width, display.height)
161 glClearColor(0.0, 0.0, 0.0, 1.0)
162
163 gl_error = glGetError
164 assert gl_error == gl_NO_ERROR else print gl_error
165
166 # Prepare to draw
167 for tex in all_root_textures do
168 tex.load
169
170 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
171 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
172
173 gamnit_error = tex.error
174 assert gamnit_error == null else print_error gamnit_error
175 end
176 end
177
178 redef fun frame_core(display)
179 do
180 # Prepare to draw, clear buffers
181 glClear(gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT)
182
183 # Check errors
184 var gl_error = glGetError
185 assert gl_error == gl_NO_ERROR else print gl_error
186
187 # Update game logic and set sprites
188 var dt = clock.lapse.to_f
189 update dt
190
191 # Draw and flip screen
192 frame_core_draw display
193 display.flip
194
195 # Check errors
196 gl_error = glGetError
197 assert gl_error == gl_NO_ERROR else print gl_error
198 end
199
200 # Draw the whole screen, all `glDraw...` calls should be executed here
201 protected fun frame_core_draw(display: GamnitDisplay)
202 do
203 frame_core_world_sprites display
204 frame_core_ui_sprites display
205 end
206
207 # Draw world sprites from `sprites`
208 protected fun frame_core_world_sprites(display: GamnitDisplay)
209 do
210 simple_2d_program.use
211
212 # Set constant configs
213 simple_2d_program.coord.array_enabled = true
214 simple_2d_program.tex_coord.array_enabled = true
215 simple_2d_program.color.array_enabled = false
216
217 # TODO optimize this draw to store constant values on the GPU
218 # World sprites
219 simple_2d_program.mvp.uniform world_camera.mvp_matrix
220 for sprite in sprites do sprite.draw
221 end
222
223 # Draw UI sprites from `ui_sprites`
224 protected fun frame_core_ui_sprites(display: GamnitDisplay)
225 do
226 simple_2d_program.use
227
228 # Set constant configs
229 simple_2d_program.coord.array_enabled = true
230 simple_2d_program.tex_coord.array_enabled = true
231 simple_2d_program.color.array_enabled = false
232
233 # Reset only the depth buffer
234 glClear gl_DEPTH_BUFFER_BIT
235
236 # UI sprites
237 simple_2d_program.mvp.uniform ui_camera.mvp_matrix
238 for sprite in ui_sprites do sprite.draw
239 end
240
241 # Main method to refine in clients to update game logic and `sprites`
242 fun update(dt: Float) do end
243
244 # Display `texture` as a splash screen
245 #
246 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
247 fun show_splash_screen(texture: Texture)
248 do
249 texture.load
250
251 ui_camera.reset_height 1080.0
252
253 var splash = new Sprite(texture, ui_camera.center)
254 ui_sprites.add splash
255
256 var display = display
257 assert display != null
258 glClear gl_COLOR_BUFFER_BIT
259 frame_core_ui_sprites display
260 display.flip
261
262 ui_sprites.remove splash
263 end
264
265 redef fun on_stop
266 do
267 # Clean up
268 simple_2d_program.delete
269
270 # Close gamnit
271 var display = display
272 if display != null then display.close
273 end
274 end
275
276 redef class Texture
277
278 # Vertices coordinates of the base geometry
279 private var vertices: Array[Float] is lazy do
280 var mod = 1.0
281 var w = width * mod
282 var h = height * mod
283 var a = [-0.5*w, -0.5*h, 0.0]
284 var b = [ 0.5*w, -0.5*h, 0.0]
285 var c = [-0.5*w, 0.5*h, 0.0]
286 var d = [ 0.5*w, 0.5*h, 0.0]
287
288 var vertices = new Array[Float]
289 for v in [c, d, a, b] do vertices.add_all v
290 return vertices
291 end
292
293 # Coordinates of this texture on the `root` texture, with `[0..1.0]`
294 private var texture_coords: Array[Float] is lazy do
295 var a = [offset_left, offset_bottom]
296 var b = [offset_right, offset_bottom]
297 var c = [offset_left, offset_top]
298 var d = [offset_right, offset_top]
299
300 var texture_coords = new Array[Float]
301 for v in [c, d, a, b] do texture_coords.add_all v
302 return texture_coords
303 end
304
305 # Coordinates of this texture on the `root` texture, with the X axis inverted
306 private var texture_coords_invert_x: Array[Float] is lazy do
307 var a = [offset_left, offset_bottom]
308 var b = [offset_right, offset_bottom]
309 var c = [offset_left, offset_top]
310 var d = [offset_right, offset_top]
311
312 var texture_coords = new Array[Float]
313 for v in [d, c, b, a] do texture_coords.add_all v
314 return texture_coords
315 end
316 end
317
318 # Graphic program to display simple models with a texture, translation, rotation and scale
319 class Simple2dProgram
320 super GamnitProgramFromSource
321
322 redef var vertex_shader_source = """
323 // Vertex coordinates
324 attribute vec4 coord;
325
326 // Vertex color tint
327 attribute vec4 color;
328
329 // Vertex translation
330 attribute vec4 translation;
331
332 // Vertex scaling
333 attribute float scale;
334
335 // Vertex coordinates on textures
336 attribute vec2 tex_coord;
337
338 // Model view projection matrix
339 uniform mat4 mvp;
340
341 // Rotation matrix
342 uniform mat4 rotation;
343
344 // Output for the fragment shader
345 varying vec4 v_color;
346 varying vec2 v_coord;
347
348 void main()
349 {
350 v_color = color;
351 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation + translation) * mvp;
352 v_coord = tex_coord;
353 }
354 """ @ glsl_vertex_shader
355
356 redef var fragment_shader_source = """
357 precision mediump float;
358
359 // Does this object use a texture?
360 uniform bool use_texture;
361
362 // Texture to apply on this object
363 uniform sampler2D texture;
364
365 // Input from the vertex shader
366 varying vec4 v_color;
367 varying vec2 v_coord;
368
369 void main()
370 {
371 if(use_texture) {
372 gl_FragColor = v_color * texture2D(texture, v_coord);
373 if (gl_FragColor.a == 0.0) discard;
374 } else {
375 gl_FragColor = v_color;
376 }
377 }
378 """ @ glsl_fragment_shader
379
380 # Vertices coordinates
381 var coord = attributes["coord"].as(AttributeVec4) is lazy
382
383 # Should this program use the texture `texture`?
384 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
385
386 # Visible texture unit
387 var texture = uniforms["texture"].as(UniformSampler2D) is lazy
388
389 # Coordinates on the textures, per vertex
390 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
391
392 # Color tint per vertex
393 var color = attributes["color"].as(AttributeVec4) is lazy
394
395 # Translation applied to each vertex
396 var translation = attributes["translation"].as(AttributeVec4) is lazy
397
398 # Rotation matrix
399 var rotation = uniforms["rotation"].as(UniformMat4) is lazy
400
401 # Scaling per vertex
402 var scale = attributes["scale"].as(AttributeFloat) is lazy
403
404 # Model view projection matrix
405 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
406 end
407
408 redef class Point3d[N]
409 # Get a new `Point3d[Float]` with an offset of each axis of `x, y, z`
410 fun offset(x, y, z: Numeric): Point3d[Float]
411 do
412 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)
413 end
414 end