271e688c3f5181e02def47e182180594b0a5ec70
[nit.git] / lib / gamnit / textures.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 # Load textures, create subtextures and manage their life-cycle
16 module textures
17
18 import display
19
20 # Texture composed of pixels, loaded from the assets folder by default
21 #
22 # Most textures should be created with `App` (as attributes)
23 # for the method `on_create` to load them.
24 #
25 # ~~~
26 # import gamnit::flat
27 #
28 # redef class App
29 # # Create the texture object, it will be loaded automatically
30 # var texture = new Texture("path/in/assets.png")
31 #
32 # redef fun on_create()
33 # do
34 # # Let `on_create` load the texture
35 # super
36 #
37 # # Use the texture
38 # var sprite = new Sprite(texture, new Point3d[Float](0.0, 0.0, 0.0))
39 # app.sprites.add sprite
40 # end
41 # end
42 # ~~~
43 #
44 # Otherwise, they can be loaded and error checked explicitly after `on_create`.
45 #
46 # ~~~nitish
47 # var texture = new Texture("path/in/assets.png")
48 # texture.load
49 # var error = texture.error
50 # if error != null then print_error error
51 # ~~~
52 #
53 # A texture may also be created programmatically, like `CheckerTexture`,
54 # or derived from another texture, using `subtexture`.
55 # Textures with actual pixel data (not `Subtexture`) are `RootTexture`.
56 # Texture loaded from the assets folder may in the PNG or JPG formats.
57 abstract class Texture
58
59 # Prepare a texture located at `path` within the `assets` folder
60 new (path: Text) do return new TextureAsset(path.to_s)
61
62 # Root texture from which `self` is derived
63 fun root: RootTexture is abstract
64
65 # Width in pixels of this texture
66 var width = 0.0
67
68 # Height in pixels of this texture
69 var height = 0.0
70
71 # Load this texture, force reloading it if `force`
72 fun load(force: nullable Bool) do end
73
74 # Last error on this texture
75 var error: nullable Error = null
76
77 # OpenGL handle to this texture
78 fun gl_texture: Int do return root.gl_texture
79
80 # Prepare a subtexture from this texture, from the given pixel offsets
81 fun subtexture(left, top, width, height: Numeric): Subtexture
82 do
83 # Setup the subtexture
84 var subtex = new Subtexture(root, self, left.to_f, top.to_f, width.to_f, height.to_f)
85 return subtex
86 end
87
88 # Offset of the left border on `root` from 0.0 to 1.0
89 fun offset_left: Float do return 0.0
90
91 # Offset of the top border on `root` from 0.0 to 1.0
92 fun offset_top: Float do return 0.0
93
94 # Offset of the right border on `root` from 0.0 to 1.0
95 fun offset_right: Float do return 1.0
96
97 # Offset of the bottom border on `root` from 0.0 to 1.0
98 fun offset_bottom: Float do return 1.0
99 end
100
101 # Colorful small texture of 32x32 pixels by default
102 class CheckerTexture
103 super RootTexture
104
105 # Width and height in pixels, defaults to 32
106 var size = 32 is optional
107
108 redef fun load(force)
109 do
110 if gl_texture != -1 then return
111 load_checker size
112 loaded = true
113 end
114 end
115
116 # Custom texture with pixel values filled programmatically
117 #
118 # At creation, the texture is composed of `width` by `height` (rounded down)
119 # transparent pixels. The pixels value can be set using `[]=`.
120 #
121 # ~~~
122 # # Build a texture with 4 colors
123 # var tex = new CustomTexture(2.0, 2.0)
124 # tex[0, 0] = [1.0, 0.0, 0.0] # Red
125 # tex[0, 1] = [0.0, 1.0, 0.0] # Green
126 # tex[1, 0] = [0.0, 0.0, 1.0] # Blue
127 # tex[1, 1] = [1.0, 1.0, 1.0, 0.5] # Transparent white
128 # tex.load
129 # ~~~
130 class CustomTexture
131 super RootTexture
132
133 redef var width
134 redef var height
135
136 private var cpixels = new CByteArray(4*width.to_i*height.to_i) is lazy
137
138 # Set the `color` of the pixel at `x`, `y` (from the top-left corner)
139 #
140 # The argument `color` should be an array of up to 4 floats (RGBA).
141 # If `color` has less than 4 items, the missing items are replaced by 1.0.
142 #
143 # Require: `not loaded and x < width.to_i and y < height.to_i`
144 fun []=(x, y: Int, color: Array[Float])
145 do
146 assert not loaded else print_error "{class_name}::[]= already loaded"
147 assert x < width.to_i and y < height.to_i else print_error "{class_name}::[] out of bounds"
148
149 # Simple conversion from [0.0..1.0] to [0..255]
150 var bytes = [for c in color do (c*255.0).round.to_i.clamp(0, 255).to_bytes.last]
151 while bytes.length < 4 do bytes.add 255u8
152
153 var offset = 4*(x + y*width.to_i)
154 for i in [0..4[ do cpixels[offset+i] = bytes[i]
155 end
156
157 redef fun load(force)
158 do
159 if loaded then return
160
161 # Round down the desired dimension
162 var width = width.to_i
163 var height = height.to_i
164 self.width = width.to_f
165 self.height = height.to_f
166
167 load_from_pixels(cpixels.native_array, width, height, gl_RGBA)
168
169 cpixels.destroy
170 loaded = true
171 end
172 end
173
174 # Texture with its own pixels
175 class RootTexture
176 super Texture
177
178 redef fun root do return self
179
180 # Has this texture been loaded yet?
181 var loaded = false
182
183 redef var gl_texture = -1
184
185 init do all_root_textures.add self
186
187 private fun load_from_pixels(pixels: Pointer, width, height: Int, format: GLPixelFormat)
188 do
189 var max_texture_size = glGetIntegerv(gl_MAX_TEXTURE_SIZE, 0)
190 if width > max_texture_size or height > max_texture_size then
191 error = new Error("Texture {self} width or height is over the GL_MAX_TEXTURE_SIZE of {max_texture_size}")
192 return
193 end
194
195 glPixelStorei(gl_UNPACK_ALIGNEMENT, 1)
196 var tex = glGenTextures(1)[0]
197 gl_texture = tex
198
199 glBindTexture(gl_TEXTURE_2D, tex)
200 glTexImage2D(gl_TEXTURE_2D, 0, format, width, height, 0, format, gl_UNSIGNED_BYTE, pixels)
201
202 glHint(gl_GENERATE_MIPMAP_HINT, gl_NICEST)
203 glGenerateMipmap(gl_TEXTURE_2D)
204 end
205
206 private fun load_checker(size: Int)
207 do
208 var cpixels = new CByteArray(3*size*size)
209
210 var i = 0
211 for x in [0..size[ do
212 var quadrant_x = if x < size/2 then 0 else 1
213 for y in [0..size[ do
214 var quadrant_y = if y < size/2 then 0 else 1
215 var color = if quadrant_x == quadrant_y then
216 [0u8, 0u8, 0u8, 255u8]
217 else [255u8, 255u8, 255u8, 255u8]
218
219 for j in [0..3[ do cpixels[i+j] = color[j]
220 i += 3
221 end
222 end
223
224 width = size.to_f
225 height = size.to_f
226 load_from_pixels(cpixels.native_array, size, size, gl_RGB)
227
228 cpixels.destroy
229 end
230
231 # Set whether this texture should be pixelated when drawn, otherwise it is interpolated
232 fun pixelated=(pixelated: Bool)
233 do
234 # TODO this service could be made available in `Texture` when using
235 # the kind of texture wrapper of gles v2 or maybe 3
236
237 glBindTexture(gl_TEXTURE_2D, gl_texture)
238
239 var param = if pixelated then gl_NEAREST else gl_LINEAR
240 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, param)
241 end
242
243 # Has this resource been deleted?
244 var deleted = false
245
246 # Delete this texture and free all its resources
247 #
248 # Use caution with this service as the subtextures may rely on the deleted data.
249 fun delete
250 do
251 if deleted or not loaded then return
252
253 deleted = true
254 end
255 end
256
257 # Texture loaded from the assets folder
258 class TextureAsset
259 super RootTexture
260
261 # Path to this texture within the `assets` folder
262 var path: String
263
264 redef fun load(force)
265 do
266 if loaded and force != true then return
267
268 load_from_platform
269
270 # If no pixel data was loaded, load the pixel default texture
271 if gl_texture == -1 then load_checker 32
272
273 loaded = true
274 end
275
276 # Partially load this texture from platform-specific features
277 #
278 # This method should fill `width`, `height` and `pixels`.
279 private fun load_from_platform is abstract
280
281 redef fun to_s do return "<{class_name} path:{path}>"
282 end
283
284 # Texture derived from another texture, does not own its pixels
285 class Subtexture
286 super Texture
287
288 redef var root
289
290 # Parent texture, from which this texture was created
291 var parent: Texture
292
293 # Left border of this texture compared to `parent`
294 var left: Float
295
296 # Top border of this texture compared to `parent`
297 var top: Float
298
299 private fun set_wh(width, height: Float)
300 is autoinit do
301 self.width = width
302 self.height = height
303 end
304
305 redef fun load(force) do root.load(force)
306
307 redef var offset_left = parent.offset_left + left / root.width is lazy
308 redef var offset_top = parent.offset_top + top / root.height is lazy
309 redef var offset_right = offset_left + width / root.width is lazy
310 redef var offset_bottom = offset_top + height / root.height is lazy
311 end
312
313 redef class Sys
314 # All declared root textures
315 var all_root_textures = new TextureSet
316 end
317
318 # Group of `Texture`
319 class TextureSet
320 super HashSet[Texture]
321
322 # Load all texture of this set
323 fun load_all do for t in self do t.load
324 end