1 /*************************************************************************/
2 /*  rasterizer_storage_gles3.cpp                                         */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
9 /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
10 /*                                                                       */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the       */
13 /* "Software"), to deal in the Software without restriction, including   */
14 /* without limitation the rights to use, copy, modify, merge, publish,   */
15 /* distribute, sublicense, and/or sell copies of the Software, and to    */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions:                                             */
18 /*                                                                       */
19 /* The above copyright notice and this permission notice shall be        */
20 /* included in all copies or substantial portions of the Software.       */
21 /*                                                                       */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
29 /*************************************************************************/
30 
31 #include "rasterizer_storage_gles3.h"
32 #include "core/engine.h"
33 #include "core/project_settings.h"
34 #include "rasterizer_canvas_gles3.h"
35 #include "rasterizer_scene_gles3.h"
36 
37 /* TEXTURE API */
38 
39 #define _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
40 #define _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
41 #define _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
42 #define _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
43 
44 #define _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54
45 #define _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55
46 #define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56
47 #define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57
48 
49 #define _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
50 #define _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
51 #define _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
52 
53 #define _EXT_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70
54 #define _EXT_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71
55 #define _EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72
56 #define _EXT_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73
57 
58 #define _EXT_COMPRESSED_RED_RGTC1_EXT 0x8DBB
59 #define _EXT_COMPRESSED_RED_RGTC1 0x8DBB
60 #define _EXT_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC
61 #define _EXT_COMPRESSED_RG_RGTC2 0x8DBD
62 #define _EXT_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE
63 #define _EXT_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC
64 #define _EXT_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD
65 #define _EXT_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE
66 #define _EXT_ETC1_RGB8_OES 0x8D64
67 
68 #define _EXT_SLUMINANCE_NV 0x8C46
69 #define _EXT_SLUMINANCE_ALPHA_NV 0x8C44
70 #define _EXT_SRGB8_NV 0x8C41
71 #define _EXT_SLUMINANCE8_NV 0x8C47
72 #define _EXT_SLUMINANCE8_ALPHA8_NV 0x8C45
73 
74 #define _EXT_COMPRESSED_SRGB_S3TC_DXT1_NV 0x8C4C
75 #define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV 0x8C4D
76 #define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV 0x8C4E
77 #define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV 0x8C4F
78 
79 #define _EXT_ATC_RGB_AMD 0x8C92
80 #define _EXT_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
81 #define _EXT_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
82 
83 #define _EXT_TEXTURE_CUBE_MAP_SEAMLESS 0x884F
84 
85 #define _GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
86 #define _GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
87 
88 #define _EXT_COMPRESSED_R11_EAC 0x9270
89 #define _EXT_COMPRESSED_SIGNED_R11_EAC 0x9271
90 #define _EXT_COMPRESSED_RG11_EAC 0x9272
91 #define _EXT_COMPRESSED_SIGNED_RG11_EAC 0x9273
92 #define _EXT_COMPRESSED_RGB8_ETC2 0x9274
93 #define _EXT_COMPRESSED_SRGB8_ETC2 0x9275
94 #define _EXT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276
95 #define _EXT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277
96 #define _EXT_COMPRESSED_RGBA8_ETC2_EAC 0x9278
97 #define _EXT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279
98 
99 #define _EXT_COMPRESSED_RGBA_BPTC_UNORM 0x8E8C
100 #define _EXT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D
101 #define _EXT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E
102 #define _EXT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F
103 
104 #define _GL_TEXTURE_EXTERNAL_OES 0x8D65
105 
106 #ifndef GLES_OVER_GL
107 #define glClearDepth glClearDepthf
108 #endif
109 
110 #ifdef __EMSCRIPTEN__
111 #include <emscripten/emscripten.h>
112 
glGetBufferSubData(GLenum target,GLintptr offset,GLsizeiptr size,GLvoid * data)113 void glGetBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data) {
114 
115 	/* clang-format off */
116 	EM_ASM({
117 	    GLctx.getBufferSubData($0, $1, HEAPU8, $2, $3);
118 	}, target, offset, data, size);
119 	/* clang-format on */
120 }
121 #endif
122 
glTexStorage2DCustom(GLenum target,GLsizei levels,GLenum internalformat,GLsizei width,GLsizei height,GLenum format,GLenum type)123 void glTexStorage2DCustom(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type) {
124 
125 #ifdef GLES_OVER_GL
126 
127 	for (int i = 0; i < levels; i++) {
128 		glTexImage2D(target, i, internalformat, width, height, 0, format, type, NULL);
129 		width = MAX(1, (width / 2));
130 		height = MAX(1, (height / 2));
131 	}
132 
133 #else
134 	glTexStorage2D(target, levels, internalformat, width, height);
135 #endif
136 }
137 
138 GLuint RasterizerStorageGLES3::system_fbo = 0;
139 
_get_gl_image_and_format(const Ref<Image> & p_image,Image::Format p_format,uint32_t p_flags,Image::Format & r_real_format,GLenum & r_gl_format,GLenum & r_gl_internal_format,GLenum & r_gl_type,bool & r_compressed,bool & r_srgb,bool p_force_decompress) const140 Ref<Image> RasterizerStorageGLES3::_get_gl_image_and_format(const Ref<Image> &p_image, Image::Format p_format, uint32_t p_flags, Image::Format &r_real_format, GLenum &r_gl_format, GLenum &r_gl_internal_format, GLenum &r_gl_type, bool &r_compressed, bool &r_srgb, bool p_force_decompress) const {
141 
142 	r_compressed = false;
143 	r_gl_format = 0;
144 	r_real_format = p_format;
145 	Ref<Image> image = p_image;
146 	r_srgb = false;
147 
148 	bool need_decompress = false;
149 
150 	switch (p_format) {
151 
152 		case Image::FORMAT_L8: {
153 #ifdef GLES_OVER_GL
154 			r_gl_internal_format = GL_R8;
155 			r_gl_format = GL_RED;
156 			r_gl_type = GL_UNSIGNED_BYTE;
157 #else
158 			r_gl_internal_format = GL_LUMINANCE;
159 			r_gl_format = GL_LUMINANCE;
160 			r_gl_type = GL_UNSIGNED_BYTE;
161 #endif
162 		} break;
163 		case Image::FORMAT_LA8: {
164 #ifdef GLES_OVER_GL
165 			r_gl_internal_format = GL_RG8;
166 			r_gl_format = GL_RG;
167 			r_gl_type = GL_UNSIGNED_BYTE;
168 #else
169 			r_gl_internal_format = GL_LUMINANCE_ALPHA;
170 			r_gl_format = GL_LUMINANCE_ALPHA;
171 			r_gl_type = GL_UNSIGNED_BYTE;
172 #endif
173 		} break;
174 		case Image::FORMAT_R8: {
175 
176 			r_gl_internal_format = GL_R8;
177 			r_gl_format = GL_RED;
178 			r_gl_type = GL_UNSIGNED_BYTE;
179 
180 		} break;
181 		case Image::FORMAT_RG8: {
182 
183 			r_gl_internal_format = GL_RG8;
184 			r_gl_format = GL_RG;
185 			r_gl_type = GL_UNSIGNED_BYTE;
186 
187 		} break;
188 		case Image::FORMAT_RGB8: {
189 
190 			r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? GL_SRGB8 : GL_RGB8;
191 			r_gl_format = GL_RGB;
192 			r_gl_type = GL_UNSIGNED_BYTE;
193 			r_srgb = true;
194 
195 		} break;
196 		case Image::FORMAT_RGBA8: {
197 
198 			r_gl_format = GL_RGBA;
199 			r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? GL_SRGB8_ALPHA8 : GL_RGBA8;
200 			r_gl_type = GL_UNSIGNED_BYTE;
201 			r_srgb = true;
202 
203 		} break;
204 		case Image::FORMAT_RGBA4444: {
205 
206 			r_gl_internal_format = GL_RGBA4;
207 			r_gl_format = GL_RGBA;
208 			r_gl_type = GL_UNSIGNED_SHORT_4_4_4_4;
209 
210 		} break;
211 		case Image::FORMAT_RGBA5551: {
212 
213 			r_gl_internal_format = GL_RGB5_A1;
214 			r_gl_format = GL_RGBA;
215 			r_gl_type = GL_UNSIGNED_SHORT_5_5_5_1;
216 
217 		} break;
218 		case Image::FORMAT_RF: {
219 
220 			r_gl_internal_format = GL_R32F;
221 			r_gl_format = GL_RED;
222 			r_gl_type = GL_FLOAT;
223 
224 		} break;
225 		case Image::FORMAT_RGF: {
226 
227 			r_gl_internal_format = GL_RG32F;
228 			r_gl_format = GL_RG;
229 			r_gl_type = GL_FLOAT;
230 
231 		} break;
232 		case Image::FORMAT_RGBF: {
233 
234 			r_gl_internal_format = GL_RGB32F;
235 			r_gl_format = GL_RGB;
236 			r_gl_type = GL_FLOAT;
237 
238 		} break;
239 		case Image::FORMAT_RGBAF: {
240 
241 			r_gl_internal_format = GL_RGBA32F;
242 			r_gl_format = GL_RGBA;
243 			r_gl_type = GL_FLOAT;
244 
245 		} break;
246 		case Image::FORMAT_RH: {
247 			r_gl_internal_format = GL_R16F;
248 			r_gl_format = GL_RED;
249 			r_gl_type = GL_HALF_FLOAT;
250 		} break;
251 		case Image::FORMAT_RGH: {
252 			r_gl_internal_format = GL_RG16F;
253 			r_gl_format = GL_RG;
254 			r_gl_type = GL_HALF_FLOAT;
255 
256 		} break;
257 		case Image::FORMAT_RGBH: {
258 			r_gl_internal_format = GL_RGB16F;
259 			r_gl_format = GL_RGB;
260 			r_gl_type = GL_HALF_FLOAT;
261 
262 		} break;
263 		case Image::FORMAT_RGBAH: {
264 			r_gl_internal_format = GL_RGBA16F;
265 			r_gl_format = GL_RGBA;
266 			r_gl_type = GL_HALF_FLOAT;
267 
268 		} break;
269 		case Image::FORMAT_RGBE9995: {
270 			r_gl_internal_format = GL_RGB9_E5;
271 			r_gl_format = GL_RGB;
272 			r_gl_type = GL_UNSIGNED_INT_5_9_9_9_REV;
273 
274 		} break;
275 		case Image::FORMAT_DXT1: {
276 
277 			if (config.s3tc_supported) {
278 
279 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV : _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT;
280 				r_gl_format = GL_RGBA;
281 				r_gl_type = GL_UNSIGNED_BYTE;
282 				r_compressed = true;
283 				r_srgb = true;
284 
285 			} else {
286 
287 				need_decompress = true;
288 			}
289 
290 		} break;
291 		case Image::FORMAT_DXT3: {
292 
293 			if (config.s3tc_supported) {
294 
295 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV : _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT;
296 				r_gl_format = GL_RGBA;
297 				r_gl_type = GL_UNSIGNED_BYTE;
298 				r_compressed = true;
299 				r_srgb = true;
300 
301 			} else {
302 
303 				need_decompress = true;
304 			}
305 
306 		} break;
307 		case Image::FORMAT_DXT5: {
308 
309 			if (config.s3tc_supported) {
310 
311 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV : _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT;
312 				r_gl_format = GL_RGBA;
313 				r_gl_type = GL_UNSIGNED_BYTE;
314 				r_compressed = true;
315 				r_srgb = true;
316 
317 			} else {
318 
319 				need_decompress = true;
320 			}
321 
322 		} break;
323 		case Image::FORMAT_RGTC_R: {
324 
325 			if (config.rgtc_supported) {
326 
327 				r_gl_internal_format = _EXT_COMPRESSED_RED_RGTC1_EXT;
328 				r_gl_format = GL_RGBA;
329 				r_gl_type = GL_UNSIGNED_BYTE;
330 				r_compressed = true;
331 
332 			} else {
333 
334 				need_decompress = true;
335 			}
336 
337 		} break;
338 		case Image::FORMAT_RGTC_RG: {
339 
340 			if (config.rgtc_supported) {
341 
342 				r_gl_internal_format = _EXT_COMPRESSED_RED_GREEN_RGTC2_EXT;
343 				r_gl_format = GL_RGBA;
344 				r_gl_type = GL_UNSIGNED_BYTE;
345 				r_compressed = true;
346 			} else {
347 
348 				need_decompress = true;
349 			}
350 
351 		} break;
352 		case Image::FORMAT_BPTC_RGBA: {
353 
354 			if (config.bptc_supported) {
355 
356 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM : _EXT_COMPRESSED_RGBA_BPTC_UNORM;
357 				r_gl_format = GL_RGBA;
358 				r_gl_type = GL_UNSIGNED_BYTE;
359 				r_compressed = true;
360 				r_srgb = true;
361 
362 			} else {
363 
364 				need_decompress = true;
365 			}
366 		} break;
367 		case Image::FORMAT_BPTC_RGBF: {
368 
369 			if (config.bptc_supported) {
370 
371 				r_gl_internal_format = _EXT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT;
372 				r_gl_format = GL_RGB;
373 				r_gl_type = GL_FLOAT;
374 				r_compressed = true;
375 			} else {
376 
377 				need_decompress = true;
378 			}
379 		} break;
380 		case Image::FORMAT_BPTC_RGBFU: {
381 			if (config.bptc_supported) {
382 
383 				r_gl_internal_format = _EXT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT;
384 				r_gl_format = GL_RGB;
385 				r_gl_type = GL_FLOAT;
386 				r_compressed = true;
387 			} else {
388 
389 				need_decompress = true;
390 			}
391 		} break;
392 		case Image::FORMAT_PVRTC2: {
393 
394 			if (config.pvrtc_supported) {
395 
396 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT : _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
397 				r_gl_format = GL_RGBA;
398 				r_gl_type = GL_UNSIGNED_BYTE;
399 				r_compressed = true;
400 				r_srgb = true;
401 
402 			} else {
403 
404 				need_decompress = true;
405 			}
406 		} break;
407 		case Image::FORMAT_PVRTC2A: {
408 
409 			if (config.pvrtc_supported) {
410 
411 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT : _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
412 				r_gl_format = GL_RGBA;
413 				r_gl_type = GL_UNSIGNED_BYTE;
414 				r_compressed = true;
415 				r_srgb = true;
416 
417 			} else {
418 
419 				need_decompress = true;
420 			}
421 
422 		} break;
423 		case Image::FORMAT_PVRTC4: {
424 
425 			if (config.pvrtc_supported) {
426 
427 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT : _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
428 				r_gl_format = GL_RGBA;
429 				r_gl_type = GL_UNSIGNED_BYTE;
430 				r_compressed = true;
431 				r_srgb = true;
432 
433 			} else {
434 
435 				need_decompress = true;
436 			}
437 
438 		} break;
439 		case Image::FORMAT_PVRTC4A: {
440 
441 			if (config.pvrtc_supported) {
442 
443 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT : _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
444 				r_gl_format = GL_RGBA;
445 				r_gl_type = GL_UNSIGNED_BYTE;
446 				r_compressed = true;
447 				r_srgb = true;
448 
449 			} else {
450 
451 				need_decompress = true;
452 			}
453 
454 		} break;
455 		case Image::FORMAT_ETC: {
456 
457 			if (config.etc_supported) {
458 
459 				r_gl_internal_format = _EXT_ETC1_RGB8_OES;
460 				r_gl_format = GL_RGBA;
461 				r_gl_type = GL_UNSIGNED_BYTE;
462 				r_compressed = true;
463 
464 			} else {
465 
466 				need_decompress = true;
467 			}
468 
469 		} break;
470 		case Image::FORMAT_ETC2_R11: {
471 
472 			if (config.etc2_supported) {
473 
474 				r_gl_internal_format = _EXT_COMPRESSED_R11_EAC;
475 				r_gl_format = GL_RED;
476 				r_gl_type = GL_UNSIGNED_BYTE;
477 				r_compressed = true;
478 
479 			} else {
480 
481 				need_decompress = true;
482 			}
483 		} break;
484 		case Image::FORMAT_ETC2_R11S: {
485 
486 			if (config.etc2_supported) {
487 
488 				r_gl_internal_format = _EXT_COMPRESSED_SIGNED_R11_EAC;
489 				r_gl_format = GL_RED;
490 				r_gl_type = GL_UNSIGNED_BYTE;
491 				r_compressed = true;
492 
493 			} else {
494 
495 				need_decompress = true;
496 			}
497 		} break;
498 		case Image::FORMAT_ETC2_RG11: {
499 
500 			if (config.etc2_supported) {
501 
502 				r_gl_internal_format = _EXT_COMPRESSED_RG11_EAC;
503 				r_gl_format = GL_RG;
504 				r_gl_type = GL_UNSIGNED_BYTE;
505 				r_compressed = true;
506 
507 			} else {
508 
509 				need_decompress = true;
510 			}
511 		} break;
512 		case Image::FORMAT_ETC2_RG11S: {
513 			if (config.etc2_supported) {
514 
515 				r_gl_internal_format = _EXT_COMPRESSED_SIGNED_RG11_EAC;
516 				r_gl_format = GL_RG;
517 				r_gl_type = GL_UNSIGNED_BYTE;
518 				r_compressed = true;
519 
520 			} else {
521 				need_decompress = true;
522 			}
523 		} break;
524 		case Image::FORMAT_ETC2_RGB8: {
525 
526 			if (config.etc2_supported) {
527 
528 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB8_ETC2 : _EXT_COMPRESSED_RGB8_ETC2;
529 				r_gl_format = GL_RGB;
530 				r_gl_type = GL_UNSIGNED_BYTE;
531 				r_compressed = true;
532 				r_srgb = true;
533 
534 			} else {
535 
536 				need_decompress = true;
537 			}
538 		} break;
539 		case Image::FORMAT_ETC2_RGBA8: {
540 
541 			if (config.etc2_supported) {
542 
543 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : _EXT_COMPRESSED_RGBA8_ETC2_EAC;
544 				r_gl_format = GL_RGBA;
545 				r_gl_type = GL_UNSIGNED_BYTE;
546 				r_compressed = true;
547 				r_srgb = true;
548 
549 			} else {
550 
551 				need_decompress = true;
552 			}
553 		} break;
554 		case Image::FORMAT_ETC2_RGB8A1: {
555 
556 			if (config.etc2_supported) {
557 
558 				r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? _EXT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : _EXT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
559 				r_gl_format = GL_RGBA;
560 				r_gl_type = GL_UNSIGNED_BYTE;
561 				r_compressed = true;
562 				r_srgb = true;
563 
564 			} else {
565 
566 				need_decompress = true;
567 			}
568 		} break;
569 		default: {
570 
571 			ERR_FAIL_V(Ref<Image>());
572 		}
573 	}
574 
575 	if (need_decompress || p_force_decompress) {
576 
577 		if (!image.is_null()) {
578 			image = image->duplicate();
579 			image->decompress();
580 			ERR_FAIL_COND_V(image->is_compressed(), image);
581 			image->convert(Image::FORMAT_RGBA8);
582 		}
583 
584 		r_gl_format = GL_RGBA;
585 		r_gl_internal_format = (config.srgb_decode_supported || (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) ? GL_SRGB8_ALPHA8 : GL_RGBA8;
586 		r_gl_type = GL_UNSIGNED_BYTE;
587 		r_compressed = false;
588 		r_real_format = Image::FORMAT_RGBA8;
589 		r_srgb = true;
590 
591 		return image;
592 	}
593 
594 	return image;
595 }
596 
597 static const GLenum _cube_side_enum[6] = {
598 
599 	GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
600 	GL_TEXTURE_CUBE_MAP_POSITIVE_X,
601 	GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
602 	GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
603 	GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
604 	GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
605 
606 };
607 
texture_create()608 RID RasterizerStorageGLES3::texture_create() {
609 
610 	Texture *texture = memnew(Texture);
611 	ERR_FAIL_COND_V(!texture, RID());
612 	glGenTextures(1, &texture->tex_id);
613 	texture->active = false;
614 	texture->total_data_size = 0;
615 
616 	return texture_owner.make_rid(texture);
617 }
618 
texture_allocate(RID p_texture,int p_width,int p_height,int p_depth_3d,Image::Format p_format,VisualServer::TextureType p_type,uint32_t p_flags)619 void RasterizerStorageGLES3::texture_allocate(RID p_texture, int p_width, int p_height, int p_depth_3d, Image::Format p_format, VisualServer::TextureType p_type, uint32_t p_flags) {
620 
621 	GLenum format;
622 	GLenum internal_format;
623 	GLenum type;
624 
625 	bool compressed;
626 	bool srgb;
627 
628 	if (p_flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING) {
629 		p_flags &= ~VS::TEXTURE_FLAG_MIPMAPS; // no mipies for video
630 	}
631 
632 #ifndef GLES_OVER_GL
633 	switch (p_format) {
634 		case Image::FORMAT_RF:
635 		case Image::FORMAT_RGF:
636 		case Image::FORMAT_RGBF:
637 		case Image::FORMAT_RGBAF:
638 		case Image::FORMAT_RH:
639 		case Image::FORMAT_RGH:
640 		case Image::FORMAT_RGBH:
641 		case Image::FORMAT_RGBAH: {
642 			if (!config.texture_float_linear_supported) {
643 				// disable linear texture filtering when not supported for float format on some devices (issue #24295)
644 				p_flags &= ~VS::TEXTURE_FLAG_FILTER;
645 			}
646 		} break;
647 		default: {
648 		}
649 	}
650 #endif
651 
652 	Texture *texture = texture_owner.get(p_texture);
653 	ERR_FAIL_COND(!texture);
654 	texture->width = p_width;
655 	texture->height = p_height;
656 	texture->depth = p_depth_3d;
657 	texture->format = p_format;
658 	texture->flags = p_flags;
659 	texture->stored_cube_sides = 0;
660 
661 	texture->type = p_type;
662 
663 	switch (p_type) {
664 		case VS::TEXTURE_TYPE_2D: {
665 			texture->target = GL_TEXTURE_2D;
666 			texture->images.resize(1);
667 		} break;
668 		case VS::TEXTURE_TYPE_EXTERNAL: {
669 #ifdef ANDROID_ENABLED
670 			texture->target = _GL_TEXTURE_EXTERNAL_OES;
671 #else
672 			texture->target = GL_TEXTURE_2D;
673 #endif
674 			texture->images.resize(0);
675 		} break;
676 		case VS::TEXTURE_TYPE_CUBEMAP: {
677 			texture->target = GL_TEXTURE_CUBE_MAP;
678 			texture->images.resize(6);
679 		} break;
680 		case VS::TEXTURE_TYPE_2D_ARRAY: {
681 			texture->target = GL_TEXTURE_2D_ARRAY;
682 			texture->images.resize(p_depth_3d);
683 		} break;
684 		case VS::TEXTURE_TYPE_3D: {
685 			texture->target = GL_TEXTURE_3D;
686 			texture->images.resize(p_depth_3d);
687 		} break;
688 	}
689 
690 	if (p_type != VS::TEXTURE_TYPE_EXTERNAL) {
691 		texture->is_npot_repeat_mipmap = false;
692 #ifdef JAVASCRIPT_ENABLED
693 		// WebGL 2.0 on browsers does not seem to properly support compressed non power-of-two (NPOT)
694 		// textures with repeat/mipmaps, even though NPOT textures should be supported as per the spec.
695 		// Force decompressing them to work it around on WebGL 2.0 at a performance cost (GH-33058).
696 		int po2_width = next_power_of_2(p_width);
697 		int po2_height = next_power_of_2(p_height);
698 		bool is_po2 = p_width == po2_width && p_height == po2_height;
699 
700 		if (!is_po2 && (p_flags & VS::TEXTURE_FLAG_REPEAT || p_flags & VS::TEXTURE_FLAG_MIPMAPS)) {
701 			texture->is_npot_repeat_mipmap = true;
702 		}
703 #endif // JAVASCRIPT_ENABLED
704 
705 		Image::Format real_format;
706 		_get_gl_image_and_format(Ref<Image>(),
707 				texture->format,
708 				texture->flags,
709 				real_format,
710 				format,
711 				internal_format,
712 				type,
713 				compressed,
714 				srgb,
715 				texture->is_npot_repeat_mipmap);
716 
717 		texture->alloc_width = texture->width;
718 		texture->alloc_height = texture->height;
719 		texture->alloc_depth = texture->depth;
720 
721 		texture->gl_format_cache = format;
722 		texture->gl_type_cache = type;
723 		texture->gl_internal_format_cache = internal_format;
724 		texture->compressed = compressed;
725 		texture->srgb = srgb;
726 		texture->data_size = 0;
727 		texture->mipmaps = 1;
728 	}
729 
730 	glActiveTexture(GL_TEXTURE0);
731 	glBindTexture(texture->target, texture->tex_id);
732 
733 	if (p_type == VS::TEXTURE_TYPE_EXTERNAL) {
734 		glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
735 		glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
736 		glTexParameteri(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
737 		glTexParameteri(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
738 	} else if (p_type == VS::TEXTURE_TYPE_3D || p_type == VS::TEXTURE_TYPE_2D_ARRAY) {
739 
740 		int width = p_width;
741 		int height = p_height;
742 		int depth = p_depth_3d;
743 
744 		int mipmaps = 0;
745 
746 		while (width > 0 || height > 0 || (p_type == VS::TEXTURE_TYPE_3D && depth > 0)) {
747 			width = MAX(1, width);
748 			height = MAX(1, height);
749 			depth = MAX(1, depth);
750 
751 			glTexImage3D(texture->target, mipmaps, internal_format, width, height, depth, 0, format, type, NULL);
752 
753 			width /= 2;
754 			height /= 2;
755 
756 			if (p_type == VS::TEXTURE_TYPE_3D) {
757 				depth /= 2;
758 			}
759 
760 			mipmaps++;
761 
762 			if (!(p_flags & VS::TEXTURE_FLAG_MIPMAPS))
763 				break;
764 		}
765 
766 		glTexParameteri(texture->target, GL_TEXTURE_BASE_LEVEL, 0);
767 		glTexParameteri(texture->target, GL_TEXTURE_MAX_LEVEL, mipmaps - 1);
768 
769 	} else if (p_flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING) {
770 		//prealloc if video
771 		glTexImage2D(texture->target, 0, internal_format, p_width, p_height, 0, format, type, NULL);
772 	}
773 
774 	texture->active = true;
775 }
776 
texture_set_data(RID p_texture,const Ref<Image> & p_image,int p_layer)777 void RasterizerStorageGLES3::texture_set_data(RID p_texture, const Ref<Image> &p_image, int p_layer) {
778 
779 	Texture *texture = texture_owner.get(p_texture);
780 
781 	ERR_FAIL_COND(!texture);
782 	ERR_FAIL_COND(!texture->active);
783 	ERR_FAIL_COND(texture->render_target);
784 	ERR_FAIL_COND(texture->format != p_image->get_format());
785 	ERR_FAIL_COND(p_image.is_null());
786 	ERR_FAIL_COND(texture->type == VS::TEXTURE_TYPE_EXTERNAL);
787 
788 	GLenum type;
789 	GLenum format;
790 	GLenum internal_format;
791 	bool compressed;
792 	bool srgb;
793 
794 	if (config.keep_original_textures && !(texture->flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING)) {
795 		texture->images.write[p_layer] = p_image;
796 	}
797 
798 	Image::Format real_format;
799 	Ref<Image> img = _get_gl_image_and_format(p_image, p_image->get_format(), texture->flags, real_format, format, internal_format, type, compressed, srgb, texture->is_npot_repeat_mipmap);
800 
801 	if (config.shrink_textures_x2 && (p_image->has_mipmaps() || !p_image->is_compressed()) && !(texture->flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING)) {
802 
803 		texture->alloc_height = MAX(1, texture->alloc_height / 2);
804 		texture->alloc_width = MAX(1, texture->alloc_width / 2);
805 
806 		if (texture->alloc_width == img->get_width() / 2 && texture->alloc_height == img->get_height() / 2) {
807 
808 			img->shrink_x2();
809 		} else if (img->get_format() <= Image::FORMAT_RGBA8) {
810 
811 			img->resize(texture->alloc_width, texture->alloc_height, Image::INTERPOLATE_BILINEAR);
812 		}
813 	};
814 
815 	GLenum blit_target = GL_TEXTURE_2D;
816 
817 	switch (texture->type) {
818 		case VS::TEXTURE_TYPE_2D:
819 		case VS::TEXTURE_TYPE_EXTERNAL: {
820 			blit_target = GL_TEXTURE_2D;
821 		} break;
822 		case VS::TEXTURE_TYPE_CUBEMAP: {
823 			ERR_FAIL_INDEX(p_layer, 6);
824 			blit_target = _cube_side_enum[p_layer];
825 		} break;
826 		case VS::TEXTURE_TYPE_2D_ARRAY: {
827 			blit_target = GL_TEXTURE_2D_ARRAY;
828 		} break;
829 		case VS::TEXTURE_TYPE_3D: {
830 			blit_target = GL_TEXTURE_3D;
831 		} break;
832 	}
833 
834 	texture->data_size = img->get_data().size();
835 	PoolVector<uint8_t>::Read read = img->get_data().read();
836 	ERR_FAIL_COND(!read.ptr());
837 
838 	glActiveTexture(GL_TEXTURE0);
839 	glBindTexture(texture->target, texture->tex_id);
840 
841 	texture->ignore_mipmaps = compressed && !img->has_mipmaps();
842 
843 	if ((texture->flags & VS::TEXTURE_FLAG_MIPMAPS) && !texture->ignore_mipmaps)
844 		if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
845 			glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, config.use_fast_texture_filter ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR);
846 		} else {
847 			glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, config.use_fast_texture_filter ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_LINEAR);
848 		}
849 	else {
850 		if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
851 			glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
852 		} else {
853 			glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
854 		}
855 	}
856 
857 	if (config.srgb_decode_supported && srgb) {
858 
859 		if (texture->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
860 
861 			glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
862 			texture->using_srgb = true;
863 		} else {
864 			glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _SKIP_DECODE_EXT);
865 			texture->using_srgb = false;
866 		}
867 	}
868 
869 	if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
870 
871 		glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering
872 
873 	} else {
874 
875 		glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // raw Filtering
876 	}
877 
878 	if (((texture->flags & VS::TEXTURE_FLAG_REPEAT) || (texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT)) && texture->target != GL_TEXTURE_CUBE_MAP) {
879 
880 		if (texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) {
881 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
882 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
883 		} else {
884 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
885 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
886 		}
887 	} else {
888 
889 		//glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
890 		glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
891 		glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
892 	}
893 
894 //set swizle for older format compatibility
895 #ifdef GLES_OVER_GL
896 	switch (texture->format) {
897 
898 		case Image::FORMAT_L8: {
899 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED);
900 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_RED);
901 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_RED);
902 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_ONE);
903 
904 		} break;
905 		case Image::FORMAT_LA8: {
906 
907 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED);
908 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_RED);
909 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_RED);
910 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_GREEN);
911 		} break;
912 		default: {
913 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED);
914 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
915 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_BLUE);
916 			glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_ALPHA);
917 
918 		} break;
919 	}
920 #endif
921 	if (config.use_anisotropic_filter) {
922 
923 		if (texture->flags & VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
924 
925 			glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, config.anisotropic_level);
926 		} else {
927 			glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, 1);
928 		}
929 	}
930 
931 	int mipmaps = ((texture->flags & VS::TEXTURE_FLAG_MIPMAPS) && img->has_mipmaps()) ? img->get_mipmap_count() + 1 : 1;
932 
933 	int w = img->get_width();
934 	int h = img->get_height();
935 
936 	int tsize = 0;
937 
938 	for (int i = 0; i < mipmaps; i++) {
939 
940 		int size, ofs;
941 		img->get_mipmap_offset_and_size(i, ofs, size);
942 
943 		if (texture->type == VS::TEXTURE_TYPE_2D || texture->type == VS::TEXTURE_TYPE_CUBEMAP) {
944 
945 			if (texture->compressed) {
946 				glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
947 
948 				int bw = w;
949 				int bh = h;
950 
951 				glCompressedTexImage2D(blit_target, i, internal_format, bw, bh, 0, size, &read[ofs]);
952 
953 			} else {
954 				glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
955 				if (texture->flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING) {
956 					glTexSubImage2D(blit_target, i, 0, 0, w, h, format, type, &read[ofs]);
957 				} else {
958 					glTexImage2D(blit_target, i, internal_format, w, h, 0, format, type, &read[ofs]);
959 				}
960 			}
961 		} else {
962 			if (texture->compressed) {
963 				glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
964 
965 				int bw = w;
966 				int bh = h;
967 
968 				glCompressedTexSubImage3D(blit_target, i, 0, 0, p_layer, bw, bh, 1, internal_format, size, &read[ofs]);
969 			} else {
970 				glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
971 
972 				glTexSubImage3D(blit_target, i, 0, 0, p_layer, w, h, 1, format, type, &read[ofs]);
973 			}
974 		}
975 		tsize += size;
976 
977 		w = MAX(1, w >> 1);
978 		h = MAX(1, h >> 1);
979 	}
980 
981 	// Handle array and 3D textures, as those set their data per layer.
982 	tsize *= MAX(texture->alloc_depth, 1);
983 
984 	info.texture_mem -= texture->total_data_size;
985 	texture->total_data_size = tsize;
986 	info.texture_mem += texture->total_data_size;
987 
988 	//printf("texture: %i x %i - size: %i - total: %i\n",texture->width,texture->height,tsize,_rinfo.texture_mem);
989 
990 	texture->stored_cube_sides |= (1 << p_layer);
991 
992 	if ((texture->type == VS::TEXTURE_TYPE_2D || texture->type == VS::TEXTURE_TYPE_CUBEMAP) && (texture->flags & VS::TEXTURE_FLAG_MIPMAPS) && mipmaps == 1 && !texture->ignore_mipmaps && (texture->type != VS::TEXTURE_TYPE_CUBEMAP || texture->stored_cube_sides == (1 << 6) - 1)) {
993 		//generate mipmaps if they were requested and the image does not contain them
994 		glGenerateMipmap(texture->target);
995 	} else if (mipmaps > 1) {
996 		glTexParameteri(texture->target, GL_TEXTURE_BASE_LEVEL, 0);
997 		glTexParameteri(texture->target, GL_TEXTURE_MAX_LEVEL, mipmaps - 1);
998 	} else {
999 		glTexParameteri(texture->target, GL_TEXTURE_BASE_LEVEL, 0);
1000 		glTexParameteri(texture->target, GL_TEXTURE_MAX_LEVEL, 0);
1001 	}
1002 
1003 	texture->mipmaps = mipmaps;
1004 
1005 	//texture_set_flags(p_texture,texture->flags);
1006 }
1007 
1008 // Uploads pixel data to a sub-region of a texture, for the specified mipmap.
1009 // The texture pixels must have been allocated before, because most features seen in texture_set_data() make no sense in a partial update.
1010 // TODO If we want this to be usable without pre-filling pixels with a full image, we have to call glTexImage2D() with null data.
texture_set_data_partial(RID p_texture,const Ref<Image> & p_image,int src_x,int src_y,int src_w,int src_h,int dst_x,int dst_y,int p_dst_mip,int p_layer)1011 void RasterizerStorageGLES3::texture_set_data_partial(RID p_texture, const Ref<Image> &p_image, int src_x, int src_y, int src_w, int src_h, int dst_x, int dst_y, int p_dst_mip, int p_layer) {
1012 
1013 	Texture *texture = texture_owner.get(p_texture);
1014 
1015 	ERR_FAIL_COND(!texture);
1016 	ERR_FAIL_COND(!texture->active);
1017 	ERR_FAIL_COND(texture->render_target);
1018 	ERR_FAIL_COND(texture->format != p_image->get_format());
1019 	ERR_FAIL_COND(p_image.is_null());
1020 	ERR_FAIL_COND(src_w <= 0 || src_h <= 0);
1021 	ERR_FAIL_COND(src_x < 0 || src_y < 0 || src_x + src_w > p_image->get_width() || src_y + src_h > p_image->get_height());
1022 	ERR_FAIL_COND(dst_x < 0 || dst_y < 0 || dst_x + src_w > texture->alloc_width || dst_y + src_h > texture->alloc_height);
1023 	ERR_FAIL_COND(p_dst_mip < 0 || p_dst_mip >= texture->mipmaps);
1024 	ERR_FAIL_COND(texture->type == VS::TEXTURE_TYPE_EXTERNAL);
1025 
1026 	GLenum type;
1027 	GLenum format;
1028 	GLenum internal_format;
1029 	bool compressed;
1030 	bool srgb;
1031 
1032 	// Because OpenGL wants data as a dense array, we have to extract the sub-image if the source rect isn't the full image
1033 	Ref<Image> p_sub_img = p_image;
1034 	if (src_x > 0 || src_y > 0 || src_w != p_image->get_width() || src_h != p_image->get_height()) {
1035 		p_sub_img = p_image->get_rect(Rect2(src_x, src_y, src_w, src_h));
1036 	}
1037 
1038 	Image::Format real_format;
1039 	Ref<Image> img = _get_gl_image_and_format(p_sub_img, p_sub_img->get_format(), texture->flags, real_format, format, internal_format, type, compressed, srgb, texture->is_npot_repeat_mipmap);
1040 
1041 	GLenum blit_target = GL_TEXTURE_2D;
1042 
1043 	switch (texture->type) {
1044 		case VS::TEXTURE_TYPE_2D:
1045 		case VS::TEXTURE_TYPE_EXTERNAL: {
1046 			blit_target = GL_TEXTURE_2D;
1047 		} break;
1048 		case VS::TEXTURE_TYPE_CUBEMAP: {
1049 			ERR_FAIL_INDEX(p_layer, 6);
1050 			blit_target = _cube_side_enum[p_layer];
1051 		} break;
1052 		case VS::TEXTURE_TYPE_2D_ARRAY: {
1053 			blit_target = GL_TEXTURE_2D_ARRAY;
1054 		} break;
1055 		case VS::TEXTURE_TYPE_3D: {
1056 			blit_target = GL_TEXTURE_3D;
1057 		} break;
1058 	}
1059 
1060 	PoolVector<uint8_t>::Read read = img->get_data().read();
1061 
1062 	glActiveTexture(GL_TEXTURE0);
1063 	glBindTexture(texture->target, texture->tex_id);
1064 
1065 	int src_data_size = img->get_data().size();
1066 	int src_ofs = 0;
1067 
1068 	if (texture->type == VS::TEXTURE_TYPE_2D || texture->type == VS::TEXTURE_TYPE_CUBEMAP) {
1069 		if (texture->compressed) {
1070 			glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
1071 			glCompressedTexSubImage2D(blit_target, p_dst_mip, dst_x, dst_y, src_w, src_h, internal_format, src_data_size, &read[src_ofs]);
1072 
1073 		} else {
1074 			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1075 			// `format` has to match the internal_format used when the texture was created
1076 			glTexSubImage2D(blit_target, p_dst_mip, dst_x, dst_y, src_w, src_h, format, type, &read[src_ofs]);
1077 		}
1078 	} else {
1079 		if (texture->compressed) {
1080 			glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
1081 			glCompressedTexSubImage3D(blit_target, p_dst_mip, dst_x, dst_y, p_layer, src_w, src_h, 1, format, src_data_size, &read[src_ofs]);
1082 		} else {
1083 			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1084 			// `format` has to match the internal_format used when the texture was created
1085 			glTexSubImage3D(blit_target, p_dst_mip, dst_x, dst_y, p_layer, src_w, src_h, 1, format, type, &read[src_ofs]);
1086 		}
1087 	}
1088 
1089 	if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
1090 
1091 		glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering
1092 
1093 	} else {
1094 
1095 		glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // raw Filtering
1096 	}
1097 }
1098 
texture_get_data(RID p_texture,int p_layer) const1099 Ref<Image> RasterizerStorageGLES3::texture_get_data(RID p_texture, int p_layer) const {
1100 
1101 	Texture *texture = texture_owner.get(p_texture);
1102 
1103 	ERR_FAIL_COND_V(!texture, Ref<Image>());
1104 	ERR_FAIL_COND_V(!texture->active, Ref<Image>());
1105 	ERR_FAIL_COND_V(texture->data_size == 0 && !texture->render_target, Ref<Image>());
1106 
1107 	if (texture->type == VS::TEXTURE_TYPE_CUBEMAP && p_layer < 6 && !texture->images[p_layer].is_null()) {
1108 		return texture->images[p_layer];
1109 	}
1110 
1111 	// 3D textures and 2D texture arrays need special treatment, as the glGetTexImage reads **the whole**
1112 	// texture to host-memory. 3D textures and 2D texture arrays are potentially very big, so reading
1113 	// everything just to throw everything but one layer away is A Bad Idea.
1114 	//
1115 	// Unfortunately, to solve this, the copy shader has to read the data out via a shader and store it
1116 	// in a temporary framebuffer. The data from the framebuffer can then be read using glReadPixels.
1117 	if (texture->type == VS::TEXTURE_TYPE_2D_ARRAY || texture->type == VS::TEXTURE_TYPE_3D) {
1118 		// can't read a layer that doesn't exist
1119 		ERR_FAIL_INDEX_V(p_layer, texture->alloc_depth, Ref<Image>());
1120 
1121 		// get some information about the texture
1122 		Image::Format real_format;
1123 		GLenum gl_format;
1124 		GLenum gl_internal_format;
1125 		GLenum gl_type;
1126 
1127 		bool compressed;
1128 		bool srgb;
1129 
1130 		_get_gl_image_and_format(
1131 				Ref<Image>(),
1132 				texture->format,
1133 				texture->flags,
1134 				real_format,
1135 				gl_format,
1136 				gl_internal_format,
1137 				gl_type,
1138 				compressed,
1139 				srgb,
1140 				texture->is_npot_repeat_mipmap);
1141 
1142 		PoolVector<uint8_t> data;
1143 
1144 		// TODO need to decide between RgbaUnorm and RgbaFloat32 for output
1145 		int data_size = Image::get_image_data_size(texture->alloc_width, texture->alloc_height, Image::FORMAT_RGBA8, false);
1146 
1147 		data.resize(data_size * 2); // add some more memory at the end, just in case for buggy drivers
1148 		PoolVector<uint8_t>::Write wb = data.write();
1149 
1150 		// generate temporary resources
1151 		GLuint tmp_fbo;
1152 		glGenFramebuffers(1, &tmp_fbo);
1153 
1154 		GLuint tmp_color_attachment;
1155 		glGenTextures(1, &tmp_color_attachment);
1156 
1157 		// now bring the OpenGL context into the correct state
1158 		{
1159 			glBindFramebuffer(GL_FRAMEBUFFER, tmp_fbo);
1160 
1161 			// back color attachment with memory, then set properties
1162 			glActiveTexture(GL_TEXTURE0);
1163 			glBindTexture(GL_TEXTURE_2D, tmp_color_attachment);
1164 			// TODO support HDR properly
1165 			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->alloc_width, texture->alloc_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1166 
1167 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1168 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1169 
1170 			// use the color texture as color attachment for this render pass
1171 			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tmp_color_attachment, 0);
1172 
1173 			// more GL state, wheeeey
1174 			glDepthMask(GL_FALSE);
1175 			glDisable(GL_DEPTH_TEST);
1176 			glDisable(GL_CULL_FACE);
1177 			glDisable(GL_BLEND);
1178 			glDepthFunc(GL_LEQUAL);
1179 			glColorMask(1, 1, 1, 1);
1180 
1181 			// use volume tex for reading
1182 			glActiveTexture(GL_TEXTURE0);
1183 			glBindTexture(texture->target, texture->tex_id);
1184 
1185 			glViewport(0, 0, texture->alloc_width, texture->alloc_height);
1186 
1187 			// set up copy shader for proper use
1188 			shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, !srgb);
1189 			shaders.copy.set_conditional(CopyShaderGLES3::USE_TEXTURE3D, texture->type == VS::TEXTURE_TYPE_3D);
1190 			shaders.copy.set_conditional(CopyShaderGLES3::USE_TEXTURE2DARRAY, texture->type == VS::TEXTURE_TYPE_2D_ARRAY);
1191 			shaders.copy.bind();
1192 
1193 			float layer;
1194 			if (texture->type == VS::TEXTURE_TYPE_2D_ARRAY)
1195 				layer = (float)p_layer;
1196 			else
1197 				// calculate the normalized z coordinate for the layer
1198 				layer = (float)p_layer / (float)texture->alloc_depth;
1199 
1200 			shaders.copy.set_uniform(CopyShaderGLES3::LAYER, layer);
1201 
1202 			glBindVertexArray(resources.quadie_array);
1203 		}
1204 
1205 		// clear color attachment, then perform copy
1206 		glClearColor(0.0, 0.0, 0.0, 0.0);
1207 		glClear(GL_COLOR_BUFFER_BIT);
1208 
1209 		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1210 
1211 		// read the image into the host buffer
1212 		glReadPixels(0, 0, texture->alloc_width, texture->alloc_height, GL_RGBA, GL_UNSIGNED_BYTE, &wb[0]);
1213 
1214 		// remove temp resources and unset some GL state
1215 		{
1216 			shaders.copy.set_conditional(CopyShaderGLES3::USE_TEXTURE3D, false);
1217 			shaders.copy.set_conditional(CopyShaderGLES3::USE_TEXTURE2DARRAY, false);
1218 			shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false);
1219 
1220 			glBindFramebuffer(GL_FRAMEBUFFER, 0);
1221 
1222 			glDeleteTextures(1, &tmp_color_attachment);
1223 			glDeleteFramebuffers(1, &tmp_fbo);
1224 		}
1225 
1226 		wb.release();
1227 
1228 		data.resize(data_size);
1229 
1230 		Image *img = memnew(Image(texture->alloc_width, texture->alloc_height, false, Image::FORMAT_RGBA8, data));
1231 		if (!texture->compressed) {
1232 			img->convert(real_format);
1233 		}
1234 
1235 		return Ref<Image>(img);
1236 	}
1237 
1238 #ifdef GLES_OVER_GL
1239 
1240 	Image::Format real_format;
1241 	GLenum gl_format;
1242 	GLenum gl_internal_format;
1243 	GLenum gl_type;
1244 	bool compressed;
1245 	bool srgb;
1246 	_get_gl_image_and_format(Ref<Image>(), texture->format, texture->flags, real_format, gl_format, gl_internal_format, gl_type, compressed, srgb, false);
1247 
1248 	PoolVector<uint8_t> data;
1249 
1250 	int data_size = Image::get_image_data_size(texture->alloc_width, texture->alloc_height, real_format, texture->mipmaps > 1);
1251 
1252 	data.resize(data_size * 2); //add some memory at the end, just in case for buggy drivers
1253 	PoolVector<uint8_t>::Write wb = data.write();
1254 
1255 	glActiveTexture(GL_TEXTURE0);
1256 
1257 	glBindTexture(texture->target, texture->tex_id);
1258 
1259 	glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1260 
1261 	for (int i = 0; i < texture->mipmaps; i++) {
1262 
1263 		int ofs = Image::get_image_mipmap_offset(texture->alloc_width, texture->alloc_height, real_format, i);
1264 
1265 		if (texture->compressed) {
1266 
1267 			glPixelStorei(GL_PACK_ALIGNMENT, 4);
1268 			glGetCompressedTexImage(texture->target, i, &wb[ofs]);
1269 
1270 		} else {
1271 
1272 			glPixelStorei(GL_PACK_ALIGNMENT, 1);
1273 
1274 			glGetTexImage(texture->target, i, texture->gl_format_cache, texture->gl_type_cache, &wb[ofs]);
1275 		}
1276 	}
1277 
1278 	Image::Format img_format;
1279 
1280 	//convert special case RGB10_A2 to RGBA8 because it's not a supported image format
1281 	if (texture->gl_internal_format_cache == GL_RGB10_A2) {
1282 
1283 		img_format = Image::FORMAT_RGBA8;
1284 
1285 		uint32_t *ptr = (uint32_t *)wb.ptr();
1286 		uint32_t num_pixels = data_size / 4;
1287 
1288 		for (uint32_t ofs = 0; ofs < num_pixels; ofs++) {
1289 			uint32_t px = ptr[ofs];
1290 			uint32_t a = px >> 30 & 0xFF;
1291 
1292 			ptr[ofs] = (px >> 2 & 0xFF) |
1293 					   (px >> 12 & 0xFF) << 8 |
1294 					   (px >> 22 & 0xFF) << 16 |
1295 					   (a | a << 2 | a << 4 | a << 6) << 24;
1296 		}
1297 	} else {
1298 		img_format = real_format;
1299 	}
1300 
1301 	wb.release();
1302 
1303 	data.resize(data_size);
1304 
1305 	Image *img = memnew(Image(texture->alloc_width, texture->alloc_height, texture->mipmaps > 1, img_format, data));
1306 
1307 	return Ref<Image>(img);
1308 #else
1309 
1310 	Image::Format real_format;
1311 	GLenum gl_format;
1312 	GLenum gl_internal_format;
1313 	GLenum gl_type;
1314 	bool compressed;
1315 	bool srgb;
1316 	_get_gl_image_and_format(Ref<Image>(), texture->format, texture->flags, real_format, gl_format, gl_internal_format, gl_type, compressed, srgb, texture->is_npot_repeat_mipmap);
1317 
1318 	PoolVector<uint8_t> data;
1319 
1320 	int data_size = Image::get_image_data_size(texture->alloc_width, texture->alloc_height, Image::FORMAT_RGBA8, false);
1321 
1322 	data.resize(data_size * 2); //add some memory at the end, just in case for buggy drivers
1323 	PoolVector<uint8_t>::Write wb = data.write();
1324 
1325 	GLuint temp_framebuffer;
1326 	glGenFramebuffers(1, &temp_framebuffer);
1327 
1328 	GLuint temp_color_texture;
1329 	glGenTextures(1, &temp_color_texture);
1330 
1331 	glBindFramebuffer(GL_FRAMEBUFFER, temp_framebuffer);
1332 
1333 	glBindTexture(GL_TEXTURE_2D, temp_color_texture);
1334 	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->alloc_width, texture->alloc_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1335 
1336 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1337 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1338 	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, temp_color_texture, 0);
1339 
1340 	glDepthMask(GL_FALSE);
1341 	glDisable(GL_DEPTH_TEST);
1342 	glDisable(GL_CULL_FACE);
1343 	glDisable(GL_BLEND);
1344 	glDepthFunc(GL_LEQUAL);
1345 	glColorMask(1, 1, 1, 1);
1346 	glActiveTexture(GL_TEXTURE0);
1347 	glBindTexture(GL_TEXTURE_2D, texture->tex_id);
1348 
1349 	glViewport(0, 0, texture->alloc_width, texture->alloc_height);
1350 
1351 	shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, !srgb);
1352 	shaders.copy.bind();
1353 
1354 	glClearColor(0.0, 0.0, 0.0, 0.0);
1355 	glClear(GL_COLOR_BUFFER_BIT);
1356 	glBindVertexArray(resources.quadie_array);
1357 	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1358 	glBindVertexArray(0);
1359 
1360 	glReadPixels(0, 0, texture->alloc_width, texture->alloc_height, GL_RGBA, GL_UNSIGNED_BYTE, &wb[0]);
1361 
1362 	shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false);
1363 
1364 	glDeleteTextures(1, &temp_color_texture);
1365 
1366 	glBindFramebuffer(GL_FRAMEBUFFER, 0);
1367 	glDeleteFramebuffers(1, &temp_framebuffer);
1368 
1369 	wb.release();
1370 
1371 	data.resize(data_size);
1372 
1373 	Image *img = memnew(Image(texture->alloc_width, texture->alloc_height, false, Image::FORMAT_RGBA8, data));
1374 	if (!texture->compressed) {
1375 		img->convert(real_format);
1376 	}
1377 
1378 	return Ref<Image>(img);
1379 #endif
1380 }
1381 
texture_set_flags(RID p_texture,uint32_t p_flags)1382 void RasterizerStorageGLES3::texture_set_flags(RID p_texture, uint32_t p_flags) {
1383 
1384 	Texture *texture = texture_owner.get(p_texture);
1385 	ERR_FAIL_COND(!texture);
1386 	if (texture->render_target) {
1387 
1388 		p_flags &= VS::TEXTURE_FLAG_FILTER; //can change only filter
1389 	}
1390 
1391 	bool had_mipmaps = texture->flags & VS::TEXTURE_FLAG_MIPMAPS;
1392 
1393 	texture->flags = p_flags;
1394 
1395 	glActiveTexture(GL_TEXTURE0);
1396 	glBindTexture(texture->target, texture->tex_id);
1397 
1398 	if (((texture->flags & VS::TEXTURE_FLAG_REPEAT) || (texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT)) && texture->target != GL_TEXTURE_CUBE_MAP) {
1399 
1400 		if (texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) {
1401 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
1402 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
1403 		} else {
1404 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1405 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
1406 		}
1407 	} else {
1408 		//glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
1409 		glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1410 		glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1411 	}
1412 
1413 	if (config.use_anisotropic_filter) {
1414 
1415 		if (texture->flags & VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
1416 
1417 			glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, config.anisotropic_level);
1418 		} else {
1419 			glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, 1);
1420 		}
1421 	}
1422 
1423 	if ((texture->flags & VS::TEXTURE_FLAG_MIPMAPS) && !texture->ignore_mipmaps) {
1424 		if (!had_mipmaps && texture->mipmaps == 1) {
1425 			glGenerateMipmap(texture->target);
1426 		}
1427 		if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
1428 			glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, config.use_fast_texture_filter ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR);
1429 		} else {
1430 			glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, config.use_fast_texture_filter ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_LINEAR);
1431 		}
1432 
1433 	} else {
1434 		if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
1435 			glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1436 		} else {
1437 			glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1438 		}
1439 	}
1440 
1441 	if (config.srgb_decode_supported && texture->srgb) {
1442 
1443 		if (texture->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
1444 
1445 			glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
1446 			texture->using_srgb = true;
1447 		} else {
1448 			glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _SKIP_DECODE_EXT);
1449 			texture->using_srgb = false;
1450 		}
1451 	}
1452 
1453 	if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
1454 
1455 		glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering
1456 
1457 	} else {
1458 
1459 		glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // raw Filtering
1460 	}
1461 }
texture_get_flags(RID p_texture) const1462 uint32_t RasterizerStorageGLES3::texture_get_flags(RID p_texture) const {
1463 
1464 	Texture *texture = texture_owner.get(p_texture);
1465 
1466 	ERR_FAIL_COND_V(!texture, 0);
1467 
1468 	return texture->flags;
1469 }
texture_get_format(RID p_texture) const1470 Image::Format RasterizerStorageGLES3::texture_get_format(RID p_texture) const {
1471 
1472 	Texture *texture = texture_owner.get(p_texture);
1473 
1474 	ERR_FAIL_COND_V(!texture, Image::FORMAT_L8);
1475 
1476 	return texture->format;
1477 }
1478 
texture_get_type(RID p_texture) const1479 VisualServer::TextureType RasterizerStorageGLES3::texture_get_type(RID p_texture) const {
1480 	Texture *texture = texture_owner.get(p_texture);
1481 
1482 	ERR_FAIL_COND_V(!texture, VS::TEXTURE_TYPE_2D);
1483 
1484 	return texture->type;
1485 }
texture_get_texid(RID p_texture) const1486 uint32_t RasterizerStorageGLES3::texture_get_texid(RID p_texture) const {
1487 
1488 	Texture *texture = texture_owner.get(p_texture);
1489 
1490 	ERR_FAIL_COND_V(!texture, 0);
1491 
1492 	return texture->tex_id;
1493 }
texture_bind(RID p_texture,uint32_t p_texture_no)1494 void RasterizerStorageGLES3::texture_bind(RID p_texture, uint32_t p_texture_no) {
1495 
1496 	Texture *texture = texture_owner.getornull(p_texture);
1497 
1498 	ERR_FAIL_COND(!texture);
1499 
1500 	glActiveTexture(GL_TEXTURE0 + p_texture_no);
1501 	glBindTexture(texture->target, texture->tex_id);
1502 }
texture_get_width(RID p_texture) const1503 uint32_t RasterizerStorageGLES3::texture_get_width(RID p_texture) const {
1504 
1505 	Texture *texture = texture_owner.get(p_texture);
1506 
1507 	ERR_FAIL_COND_V(!texture, 0);
1508 
1509 	return texture->width;
1510 }
texture_get_height(RID p_texture) const1511 uint32_t RasterizerStorageGLES3::texture_get_height(RID p_texture) const {
1512 
1513 	Texture *texture = texture_owner.get(p_texture);
1514 
1515 	ERR_FAIL_COND_V(!texture, 0);
1516 
1517 	return texture->height;
1518 }
1519 
texture_get_depth(RID p_texture) const1520 uint32_t RasterizerStorageGLES3::texture_get_depth(RID p_texture) const {
1521 
1522 	Texture *texture = texture_owner.get(p_texture);
1523 
1524 	ERR_FAIL_COND_V(!texture, 0);
1525 
1526 	return texture->depth;
1527 }
1528 
texture_set_size_override(RID p_texture,int p_width,int p_height,int p_depth)1529 void RasterizerStorageGLES3::texture_set_size_override(RID p_texture, int p_width, int p_height, int p_depth) {
1530 
1531 	Texture *texture = texture_owner.get(p_texture);
1532 
1533 	ERR_FAIL_COND(!texture);
1534 	ERR_FAIL_COND(texture->render_target);
1535 
1536 	ERR_FAIL_COND(p_width <= 0 || p_width > 16384);
1537 	ERR_FAIL_COND(p_height <= 0 || p_height > 16384);
1538 	//real texture size is in alloc width and height
1539 	texture->width = p_width;
1540 	texture->height = p_height;
1541 }
1542 
texture_set_path(RID p_texture,const String & p_path)1543 void RasterizerStorageGLES3::texture_set_path(RID p_texture, const String &p_path) {
1544 	Texture *texture = texture_owner.get(p_texture);
1545 	ERR_FAIL_COND(!texture);
1546 
1547 	texture->path = p_path;
1548 }
1549 
texture_get_path(RID p_texture) const1550 String RasterizerStorageGLES3::texture_get_path(RID p_texture) const {
1551 
1552 	Texture *texture = texture_owner.get(p_texture);
1553 	ERR_FAIL_COND_V(!texture, String());
1554 	return texture->path;
1555 }
texture_debug_usage(List<VS::TextureInfo> * r_info)1556 void RasterizerStorageGLES3::texture_debug_usage(List<VS::TextureInfo> *r_info) {
1557 
1558 	List<RID> textures;
1559 	texture_owner.get_owned_list(&textures);
1560 
1561 	for (List<RID>::Element *E = textures.front(); E; E = E->next()) {
1562 
1563 		Texture *t = texture_owner.get(E->get());
1564 		if (!t)
1565 			continue;
1566 		VS::TextureInfo tinfo;
1567 		tinfo.path = t->path;
1568 		tinfo.format = t->format;
1569 		tinfo.width = t->alloc_width;
1570 		tinfo.height = t->alloc_height;
1571 		tinfo.depth = t->alloc_depth;
1572 		tinfo.bytes = t->total_data_size;
1573 		r_info->push_back(tinfo);
1574 	}
1575 }
1576 
texture_set_shrink_all_x2_on_set_data(bool p_enable)1577 void RasterizerStorageGLES3::texture_set_shrink_all_x2_on_set_data(bool p_enable) {
1578 
1579 	config.shrink_textures_x2 = p_enable;
1580 }
1581 
textures_keep_original(bool p_enable)1582 void RasterizerStorageGLES3::textures_keep_original(bool p_enable) {
1583 
1584 	config.keep_original_textures = p_enable;
1585 }
1586 
texture_set_detect_3d_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void * p_userdata)1587 void RasterizerStorageGLES3::texture_set_detect_3d_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata) {
1588 
1589 	Texture *texture = texture_owner.get(p_texture);
1590 	ERR_FAIL_COND(!texture);
1591 
1592 	texture->detect_3d = p_callback;
1593 	texture->detect_3d_ud = p_userdata;
1594 }
1595 
texture_set_detect_srgb_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void * p_userdata)1596 void RasterizerStorageGLES3::texture_set_detect_srgb_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata) {
1597 	Texture *texture = texture_owner.get(p_texture);
1598 	ERR_FAIL_COND(!texture);
1599 
1600 	texture->detect_srgb = p_callback;
1601 	texture->detect_srgb_ud = p_userdata;
1602 }
1603 
texture_set_detect_normal_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void * p_userdata)1604 void RasterizerStorageGLES3::texture_set_detect_normal_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata) {
1605 	Texture *texture = texture_owner.get(p_texture);
1606 	ERR_FAIL_COND(!texture);
1607 
1608 	texture->detect_normal = p_callback;
1609 	texture->detect_normal_ud = p_userdata;
1610 }
1611 
texture_create_radiance_cubemap(RID p_source,int p_resolution) const1612 RID RasterizerStorageGLES3::texture_create_radiance_cubemap(RID p_source, int p_resolution) const {
1613 
1614 	Texture *texture = texture_owner.get(p_source);
1615 	ERR_FAIL_COND_V(!texture, RID());
1616 	ERR_FAIL_COND_V(texture->type != VS::TEXTURE_TYPE_CUBEMAP, RID());
1617 
1618 	bool use_float = config.framebuffer_half_float_supported;
1619 
1620 	if (p_resolution < 0) {
1621 		p_resolution = texture->width;
1622 	}
1623 
1624 	glBindVertexArray(0);
1625 	glDisable(GL_CULL_FACE);
1626 	glDisable(GL_DEPTH_TEST);
1627 	glDisable(GL_SCISSOR_TEST);
1628 	glDisable(GL_BLEND);
1629 
1630 	glActiveTexture(GL_TEXTURE0);
1631 	glBindTexture(texture->target, texture->tex_id);
1632 
1633 	if (config.srgb_decode_supported && texture->srgb && !texture->using_srgb) {
1634 
1635 		glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
1636 		texture->using_srgb = true;
1637 #ifdef TOOLS_ENABLED
1638 		if (!(texture->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
1639 			texture->flags |= VS::TEXTURE_FLAG_CONVERT_TO_LINEAR;
1640 			//notify that texture must be set to linear beforehand, so it works in other platforms when exported
1641 		}
1642 #endif
1643 	}
1644 
1645 	glActiveTexture(GL_TEXTURE1);
1646 	GLuint new_cubemap;
1647 	glGenTextures(1, &new_cubemap);
1648 	glBindTexture(GL_TEXTURE_CUBE_MAP, new_cubemap);
1649 
1650 	GLuint tmp_fb;
1651 
1652 	glGenFramebuffers(1, &tmp_fb);
1653 	glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb);
1654 
1655 	int size = p_resolution;
1656 
1657 	int lod = 0;
1658 
1659 	shaders.cubemap_filter.bind();
1660 
1661 	int mipmaps = 6;
1662 
1663 	int mm_level = mipmaps;
1664 
1665 	GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
1666 	GLenum format = GL_RGBA;
1667 	GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
1668 
1669 	while (mm_level) {
1670 
1671 		for (int i = 0; i < 6; i++) {
1672 			glTexImage2D(_cube_side_enum[i], lod, internal_format, size, size, 0, format, type, NULL);
1673 		}
1674 
1675 		lod++;
1676 		mm_level--;
1677 
1678 		if (size > 1)
1679 			size >>= 1;
1680 	}
1681 
1682 	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
1683 	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, lod - 1);
1684 
1685 	lod = 0;
1686 	mm_level = mipmaps;
1687 
1688 	size = p_resolution;
1689 
1690 	shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, false);
1691 
1692 	while (mm_level) {
1693 
1694 		for (int i = 0; i < 6; i++) {
1695 			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _cube_side_enum[i], new_cubemap, lod);
1696 
1697 			glViewport(0, 0, size, size);
1698 			glBindVertexArray(resources.quadie_array);
1699 
1700 			shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::FACE_ID, i);
1701 			shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS, lod / float(mipmaps - 1));
1702 
1703 			glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1704 			glBindVertexArray(0);
1705 #ifdef DEBUG_ENABLED
1706 			GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
1707 			ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
1708 #endif
1709 		}
1710 
1711 		if (size > 1)
1712 			size >>= 1;
1713 		lod++;
1714 		mm_level--;
1715 	}
1716 
1717 	//restore ranges
1718 	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
1719 	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, lod - 1);
1720 
1721 	glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
1722 	glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1723 	glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1724 	glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1725 	glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
1726 
1727 	glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
1728 	glDeleteFramebuffers(1, &tmp_fb);
1729 
1730 	Texture *ctex = memnew(Texture);
1731 
1732 	ctex->type = VS::TEXTURE_TYPE_CUBEMAP;
1733 	ctex->flags = VS::TEXTURE_FLAG_MIPMAPS | VS::TEXTURE_FLAG_FILTER;
1734 	ctex->width = p_resolution;
1735 	ctex->height = p_resolution;
1736 	ctex->alloc_width = p_resolution;
1737 	ctex->alloc_height = p_resolution;
1738 	ctex->format = use_float ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
1739 	ctex->target = GL_TEXTURE_CUBE_MAP;
1740 	ctex->gl_format_cache = format;
1741 	ctex->gl_internal_format_cache = internal_format;
1742 	ctex->gl_type_cache = type;
1743 	ctex->data_size = 0;
1744 	ctex->compressed = false;
1745 	ctex->srgb = false;
1746 	ctex->total_data_size = 0;
1747 	ctex->ignore_mipmaps = false;
1748 	ctex->mipmaps = mipmaps;
1749 	ctex->active = true;
1750 	ctex->tex_id = new_cubemap;
1751 	ctex->stored_cube_sides = (1 << 6) - 1;
1752 	ctex->render_target = NULL;
1753 
1754 	return texture_owner.make_rid(ctex);
1755 }
1756 
texture_size_with_proxy(RID p_texture) const1757 Size2 RasterizerStorageGLES3::texture_size_with_proxy(RID p_texture) const {
1758 
1759 	const Texture *texture = texture_owner.getornull(p_texture);
1760 	ERR_FAIL_COND_V(!texture, Size2());
1761 	if (texture->proxy) {
1762 		return Size2(texture->proxy->width, texture->proxy->height);
1763 	} else {
1764 		return Size2(texture->width, texture->height);
1765 	}
1766 }
1767 
texture_set_proxy(RID p_texture,RID p_proxy)1768 void RasterizerStorageGLES3::texture_set_proxy(RID p_texture, RID p_proxy) {
1769 
1770 	Texture *texture = texture_owner.get(p_texture);
1771 	ERR_FAIL_COND(!texture);
1772 
1773 	if (texture->proxy) {
1774 		texture->proxy->proxy_owners.erase(texture);
1775 		texture->proxy = NULL;
1776 	}
1777 
1778 	if (p_proxy.is_valid()) {
1779 		Texture *proxy = texture_owner.get(p_proxy);
1780 		ERR_FAIL_COND(!proxy);
1781 		ERR_FAIL_COND(proxy == texture);
1782 		proxy->proxy_owners.insert(texture);
1783 		texture->proxy = proxy;
1784 	}
1785 }
1786 
texture_set_force_redraw_if_visible(RID p_texture,bool p_enable)1787 void RasterizerStorageGLES3::texture_set_force_redraw_if_visible(RID p_texture, bool p_enable) {
1788 
1789 	Texture *texture = texture_owner.get(p_texture);
1790 	ERR_FAIL_COND(!texture);
1791 	texture->redraw_if_visible = p_enable;
1792 }
1793 
sky_create()1794 RID RasterizerStorageGLES3::sky_create() {
1795 
1796 	Sky *sky = memnew(Sky);
1797 	sky->radiance = 0;
1798 	sky->irradiance = 0;
1799 	return sky_owner.make_rid(sky);
1800 }
1801 
sky_set_texture(RID p_sky,RID p_panorama,int p_radiance_size)1802 void RasterizerStorageGLES3::sky_set_texture(RID p_sky, RID p_panorama, int p_radiance_size) {
1803 
1804 	Sky *sky = sky_owner.getornull(p_sky);
1805 	ERR_FAIL_COND(!sky);
1806 
1807 	if (sky->panorama.is_valid()) {
1808 		sky->panorama = RID();
1809 		glDeleteTextures(1, &sky->radiance);
1810 		glDeleteTextures(1, &sky->irradiance);
1811 		sky->radiance = 0;
1812 		sky->irradiance = 0;
1813 	}
1814 
1815 	sky->panorama = p_panorama;
1816 	if (!sky->panorama.is_valid())
1817 		return; //cleared
1818 
1819 	Texture *texture = texture_owner.getornull(sky->panorama);
1820 	if (!texture) {
1821 		sky->panorama = RID();
1822 		ERR_FAIL_COND(!texture);
1823 	}
1824 
1825 	texture = texture->get_ptr(); //resolve for proxies
1826 
1827 	glBindVertexArray(0);
1828 	glDisable(GL_CULL_FACE);
1829 	glDisable(GL_DEPTH_TEST);
1830 	glDisable(GL_SCISSOR_TEST);
1831 	glDisable(GL_BLEND);
1832 
1833 	glActiveTexture(GL_TEXTURE0);
1834 	glBindTexture(texture->target, texture->tex_id);
1835 	glTexParameteri(texture->target, GL_TEXTURE_BASE_LEVEL, 0);
1836 #ifdef GLES_OVER_GL
1837 	glTexParameteri(texture->target, GL_TEXTURE_MAX_LEVEL, int(Math::floor(Math::log(float(texture->width)) / Math::log(2.0f))));
1838 	glGenerateMipmap(texture->target);
1839 #else
1840 	glTexParameteri(texture->target, GL_TEXTURE_MAX_LEVEL, 0);
1841 #endif
1842 	// Need Mipmaps regardless of whether they are set in import by user
1843 	glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_REPEAT);
1844 	glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_REPEAT);
1845 #ifdef GLES_OVER_GL
1846 	glTexParameterf(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
1847 #else
1848 	glTexParameterf(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1849 #endif
1850 	glTexParameterf(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1851 
1852 	if (config.srgb_decode_supported && texture->srgb && !texture->using_srgb) {
1853 
1854 		glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
1855 		texture->using_srgb = true;
1856 #ifdef TOOLS_ENABLED
1857 		if (!(texture->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
1858 			texture->flags |= VS::TEXTURE_FLAG_CONVERT_TO_LINEAR;
1859 			//notify that texture must be set to linear beforehand, so it works in other platforms when exported
1860 		}
1861 #endif
1862 	}
1863 
1864 	{
1865 		//Irradiance map
1866 		glActiveTexture(GL_TEXTURE1);
1867 		glGenTextures(1, &sky->irradiance);
1868 		glBindTexture(GL_TEXTURE_2D, sky->irradiance);
1869 
1870 		GLuint tmp_fb;
1871 
1872 		glGenFramebuffers(1, &tmp_fb);
1873 		glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb);
1874 
1875 		int size = 32;
1876 
1877 		bool use_float = config.framebuffer_half_float_supported;
1878 
1879 		GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
1880 		GLenum format = GL_RGBA;
1881 		GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
1882 
1883 		glTexImage2D(GL_TEXTURE_2D, 0, internal_format, size, size * 2, 0, format, type, NULL);
1884 
1885 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
1886 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
1887 		glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1888 		glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1889 
1890 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1891 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1892 
1893 		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, sky->irradiance, 0);
1894 
1895 		int irradiance_size = GLOBAL_GET("rendering/quality/reflections/irradiance_max_size");
1896 		int upscale_size = MIN(int(previous_power_of_2(irradiance_size)), p_radiance_size);
1897 
1898 		GLuint tmp_fb2;
1899 		GLuint tmp_tex;
1900 		{
1901 			//generate another one for rendering, as can't read and write from a single texarray it seems
1902 			glGenFramebuffers(1, &tmp_fb2);
1903 			glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb2);
1904 			glGenTextures(1, &tmp_tex);
1905 			glBindTexture(GL_TEXTURE_2D, tmp_tex);
1906 			glTexImage2D(GL_TEXTURE_2D, 0, internal_format, upscale_size, 2.0 * upscale_size, 0, format, type, NULL);
1907 			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tmp_tex, 0);
1908 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
1909 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1910 #ifdef DEBUG_ENABLED
1911 			GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
1912 			ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
1913 #endif
1914 		}
1915 
1916 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, true);
1917 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_PANORAMA, true);
1918 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::COMPUTE_IRRADIANCE, true);
1919 		shaders.cubemap_filter.bind();
1920 
1921 		// Very large Panoramas require way too much effort to compute irradiance so use a mipmap
1922 		// level that corresponds to a panorama of 1024x512
1923 		shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::SOURCE_MIP_LEVEL, MAX(Math::floor(Math::log(float(texture->width)) / Math::log(2.0f)) - 10.0f, 0.0f));
1924 
1925 		// Compute Irradiance for a large texture, specified by radiance size and then pull out a low mipmap corresponding to 32x32
1926 		for (int i = 0; i < 2; i++) {
1927 			glViewport(0, i * upscale_size, upscale_size, upscale_size);
1928 			glBindVertexArray(resources.quadie_array);
1929 
1930 			shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP, i > 0);
1931 
1932 			glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1933 			glBindVertexArray(0);
1934 		}
1935 		glGenerateMipmap(GL_TEXTURE_2D);
1936 		glActiveTexture(GL_TEXTURE0);
1937 		glBindTexture(GL_TEXTURE_2D, tmp_tex);
1938 		glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb);
1939 
1940 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, false);
1941 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_PANORAMA, false);
1942 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::COMPUTE_IRRADIANCE, false);
1943 
1944 		shaders.copy.set_conditional(CopyShaderGLES3::USE_LOD, true);
1945 		shaders.copy.bind();
1946 		shaders.copy.set_uniform(CopyShaderGLES3::MIP_LEVEL, MAX(Math::floor(Math::log(float(upscale_size)) / Math::log(2.0f)) - 5.0f, 0.0f)); // Mip level that corresponds to a 32x32 texture
1947 
1948 		glViewport(0, 0, size, size * 2.0);
1949 		glBindVertexArray(resources.quadie_array);
1950 		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1951 		glBindVertexArray(0);
1952 
1953 		shaders.copy.set_conditional(CopyShaderGLES3::USE_LOD, false);
1954 
1955 		glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
1956 		glActiveTexture(GL_TEXTURE0);
1957 		glBindTexture(texture->target, texture->tex_id);
1958 		glDeleteFramebuffers(1, &tmp_fb);
1959 		glDeleteFramebuffers(1, &tmp_fb2);
1960 		glDeleteTextures(1, &tmp_tex);
1961 	}
1962 
1963 	// Now compute radiance
1964 
1965 	glActiveTexture(GL_TEXTURE1);
1966 	glGenTextures(1, &sky->radiance);
1967 
1968 	if (config.use_texture_array_environment) {
1969 
1970 		//texture3D
1971 		glBindTexture(GL_TEXTURE_2D_ARRAY, sky->radiance);
1972 
1973 		GLuint tmp_fb;
1974 
1975 		glGenFramebuffers(1, &tmp_fb);
1976 		glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb);
1977 
1978 		int size = p_radiance_size;
1979 
1980 		int array_level = 6;
1981 
1982 		bool use_float = config.framebuffer_half_float_supported;
1983 
1984 		GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
1985 		GLenum format = GL_RGBA;
1986 		GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
1987 
1988 		glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, internal_format, size, size * 2, array_level, 0, format, type, NULL);
1989 
1990 		glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1991 		glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1992 
1993 		GLuint tmp_fb2;
1994 		GLuint tmp_tex;
1995 		{
1996 			//generate another one for rendering, as can't read and write from a single texarray it seems
1997 			glGenFramebuffers(1, &tmp_fb2);
1998 			glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb2);
1999 			glGenTextures(1, &tmp_tex);
2000 			glBindTexture(GL_TEXTURE_2D, tmp_tex);
2001 			glTexImage2D(GL_TEXTURE_2D, 0, internal_format, size, size * 2, 0, format, type, NULL);
2002 			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tmp_tex, 0);
2003 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2004 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2005 #ifdef DEBUG_ENABLED
2006 			GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
2007 			ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
2008 #endif
2009 		}
2010 
2011 		for (int j = 0; j < array_level; j++) {
2012 
2013 			glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb2);
2014 
2015 #ifdef GLES_OVER_GL
2016 			if (j < 3) {
2017 #else
2018 			if (j == 0) {
2019 #endif
2020 
2021 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, true);
2022 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_PANORAMA, true);
2023 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_DUAL_PARABOLOID_ARRAY, false);
2024 				shaders.cubemap_filter.bind();
2025 				glActiveTexture(GL_TEXTURE0);
2026 				glBindTexture(texture->target, texture->tex_id);
2027 				shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::SOURCE_RESOLUTION, float(texture->width / 4));
2028 			} else {
2029 
2030 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, true);
2031 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_PANORAMA, false);
2032 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_DUAL_PARABOLOID_ARRAY, true);
2033 				shaders.cubemap_filter.bind();
2034 				glActiveTexture(GL_TEXTURE0);
2035 				glBindTexture(GL_TEXTURE_2D_ARRAY, sky->radiance);
2036 				shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::SOURCE_ARRAY_INDEX, j - 1); //read from previous to ensure better blur
2037 			}
2038 
2039 			for (int i = 0; i < 2; i++) {
2040 				glViewport(0, i * size, size, size);
2041 				glBindVertexArray(resources.quadie_array);
2042 
2043 				shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP, i > 0);
2044 				shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS, j / float(array_level - 1));
2045 
2046 				glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2047 				glBindVertexArray(0);
2048 			}
2049 
2050 			glBindFramebuffer(GL_DRAW_FRAMEBUFFER, tmp_fb);
2051 			glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, sky->radiance, 0, j);
2052 			glBindFramebuffer(GL_READ_FRAMEBUFFER, tmp_fb2);
2053 			glReadBuffer(GL_COLOR_ATTACHMENT0);
2054 			glBlitFramebuffer(0, 0, size, size * 2, 0, 0, size, size * 2, GL_COLOR_BUFFER_BIT, GL_NEAREST);
2055 			glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
2056 			glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
2057 		}
2058 
2059 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_PANORAMA, false);
2060 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, false);
2061 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_DUAL_PARABOLOID_ARRAY, false);
2062 
2063 		//restore ranges
2064 		glActiveTexture(GL_TEXTURE0);
2065 		glBindTexture(GL_TEXTURE_2D_ARRAY, sky->radiance);
2066 
2067 		glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
2068 
2069 		glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
2070 		glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2071 		glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2072 		glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2073 
2074 		glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
2075 		glDeleteFramebuffers(1, &tmp_fb);
2076 		glDeleteFramebuffers(1, &tmp_fb2);
2077 		glDeleteTextures(1, &tmp_tex);
2078 
2079 	} else {
2080 		//regular single texture with mipmaps
2081 		glBindTexture(GL_TEXTURE_2D, sky->radiance);
2082 
2083 		GLuint tmp_fb;
2084 
2085 		glGenFramebuffers(1, &tmp_fb);
2086 		glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb);
2087 
2088 		int size = p_radiance_size;
2089 
2090 		int lod = 0;
2091 
2092 		int mipmaps = 6;
2093 
2094 		int mm_level = mipmaps;
2095 
2096 		bool use_float = config.framebuffer_half_float_supported;
2097 
2098 		GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
2099 		GLenum format = GL_RGBA;
2100 		GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
2101 
2102 		glTexStorage2DCustom(GL_TEXTURE_2D, mipmaps, internal_format, size, size * 2.0, format, type);
2103 
2104 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
2105 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mipmaps - 1);
2106 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2107 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2108 
2109 		GLuint tmp_fb2;
2110 		GLuint tmp_tex;
2111 		{
2112 			// Need a temporary framebuffer for rendering so we can read from previous iterations
2113 			glGenFramebuffers(1, &tmp_fb2);
2114 			glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb2);
2115 			glGenTextures(1, &tmp_tex);
2116 			glBindTexture(GL_TEXTURE_2D, tmp_tex);
2117 			glTexImage2D(GL_TEXTURE_2D, 0, internal_format, size, size * 2, 0, format, type, NULL);
2118 			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tmp_tex, 0);
2119 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2120 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2121 #ifdef DEBUG_ENABLED
2122 			GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
2123 			ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
2124 #endif
2125 		}
2126 
2127 		lod = 0;
2128 		mm_level = mipmaps;
2129 
2130 		size = p_radiance_size;
2131 
2132 		while (mm_level) {
2133 			glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb);
2134 			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, sky->radiance, lod);
2135 
2136 #ifdef DEBUG_ENABLED
2137 			GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
2138 			ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
2139 #endif
2140 			glBindTexture(GL_TEXTURE_2D, tmp_tex);
2141 			glTexImage2D(GL_TEXTURE_2D, 0, internal_format, size, size * 2, 0, format, type, NULL);
2142 			glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb2);
2143 			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tmp_tex, 0);
2144 #ifdef GLES_OVER_GL
2145 			if (lod < 3) {
2146 #else
2147 			if (lod == 0) {
2148 #endif
2149 
2150 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, true);
2151 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_PANORAMA, true);
2152 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_DUAL_PARABOLOID, false);
2153 				shaders.cubemap_filter.bind();
2154 				glActiveTexture(GL_TEXTURE0);
2155 				glBindTexture(texture->target, texture->tex_id);
2156 				shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::SOURCE_RESOLUTION, float(texture->width / 4));
2157 			} else {
2158 
2159 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, true);
2160 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_PANORAMA, false);
2161 				shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_DUAL_PARABOLOID, true);
2162 				shaders.cubemap_filter.bind();
2163 				glActiveTexture(GL_TEXTURE0);
2164 				glBindTexture(GL_TEXTURE_2D, sky->radiance);
2165 				shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::SOURCE_MIP_LEVEL, float(lod - 1)); //read from previous to ensure better blur
2166 			}
2167 
2168 			for (int i = 0; i < 2; i++) {
2169 				glViewport(0, i * size, size, size);
2170 				glBindVertexArray(resources.quadie_array);
2171 
2172 				shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP, i > 0);
2173 				shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS, lod / float(mipmaps - 1));
2174 
2175 				glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2176 				glBindVertexArray(0);
2177 			}
2178 
2179 			glBindFramebuffer(GL_DRAW_FRAMEBUFFER, tmp_fb);
2180 			glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, sky->radiance, lod);
2181 			glBindFramebuffer(GL_READ_FRAMEBUFFER, tmp_fb2);
2182 			glReadBuffer(GL_COLOR_ATTACHMENT0);
2183 			glBlitFramebuffer(0, 0, size, size * 2, 0, 0, size, size * 2, GL_COLOR_BUFFER_BIT, GL_NEAREST);
2184 			glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
2185 			glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
2186 
2187 			if (size > 1)
2188 				size >>= 1;
2189 			lod++;
2190 			mm_level--;
2191 		}
2192 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, false);
2193 		shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_SOURCE_PANORAMA, false);
2194 
2195 		//restore ranges
2196 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
2197 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, lod - 1);
2198 
2199 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
2200 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2201 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2202 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2203 
2204 		//reset flags on Sky Texture that may have changed
2205 		texture_set_flags(sky->panorama, texture->flags);
2206 
2207 		glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
2208 		glDeleteFramebuffers(1, &tmp_fb);
2209 		glDeleteFramebuffers(1, &tmp_fb2);
2210 		glDeleteTextures(1, &tmp_tex);
2211 	}
2212 }
2213 
2214 /* SHADER API */
2215 
2216 RID RasterizerStorageGLES3::shader_create() {
2217 
2218 	Shader *shader = memnew(Shader);
2219 	shader->mode = VS::SHADER_SPATIAL;
2220 	shader->shader = &scene->state.scene_shader;
2221 	RID rid = shader_owner.make_rid(shader);
2222 	_shader_make_dirty(shader);
2223 	shader->self = rid;
2224 
2225 	return rid;
2226 }
2227 
2228 void RasterizerStorageGLES3::_shader_make_dirty(Shader *p_shader) {
2229 
2230 	if (p_shader->dirty_list.in_list())
2231 		return;
2232 
2233 	_shader_dirty_list.add(&p_shader->dirty_list);
2234 }
2235 
2236 void RasterizerStorageGLES3::shader_set_code(RID p_shader, const String &p_code) {
2237 
2238 	Shader *shader = shader_owner.get(p_shader);
2239 	ERR_FAIL_COND(!shader);
2240 
2241 	shader->code = p_code;
2242 
2243 	String mode_string = ShaderLanguage::get_shader_type(p_code);
2244 	VS::ShaderMode mode;
2245 
2246 	if (mode_string == "canvas_item")
2247 		mode = VS::SHADER_CANVAS_ITEM;
2248 	else if (mode_string == "particles")
2249 		mode = VS::SHADER_PARTICLES;
2250 	else
2251 		mode = VS::SHADER_SPATIAL;
2252 
2253 	if (shader->custom_code_id && mode != shader->mode) {
2254 
2255 		shader->shader->free_custom_shader(shader->custom_code_id);
2256 		shader->custom_code_id = 0;
2257 	}
2258 
2259 	shader->mode = mode;
2260 
2261 	ShaderGLES3 *shaders[VS::SHADER_MAX] = {
2262 		&scene->state.scene_shader,
2263 		&canvas->state.canvas_shader,
2264 		&this->shaders.particles,
2265 
2266 	};
2267 
2268 	shader->shader = shaders[mode];
2269 
2270 	if (shader->custom_code_id == 0) {
2271 		shader->custom_code_id = shader->shader->create_custom_shader();
2272 	}
2273 
2274 	_shader_make_dirty(shader);
2275 }
2276 String RasterizerStorageGLES3::shader_get_code(RID p_shader) const {
2277 
2278 	const Shader *shader = shader_owner.get(p_shader);
2279 	ERR_FAIL_COND_V(!shader, String());
2280 
2281 	return shader->code;
2282 }
2283 
2284 void RasterizerStorageGLES3::_update_shader(Shader *p_shader) const {
2285 
2286 	_shader_dirty_list.remove(&p_shader->dirty_list);
2287 
2288 	p_shader->valid = false;
2289 	p_shader->ubo_size = 0;
2290 
2291 	p_shader->uniforms.clear();
2292 
2293 	if (p_shader->code == String()) {
2294 		return; //just invalid, but no error
2295 	}
2296 
2297 	ShaderCompilerGLES3::GeneratedCode gen_code;
2298 	ShaderCompilerGLES3::IdentifierActions *actions = NULL;
2299 
2300 	switch (p_shader->mode) {
2301 		case VS::SHADER_CANVAS_ITEM: {
2302 
2303 			p_shader->canvas_item.light_mode = Shader::CanvasItem::LIGHT_MODE_NORMAL;
2304 			p_shader->canvas_item.blend_mode = Shader::CanvasItem::BLEND_MODE_MIX;
2305 			p_shader->canvas_item.uses_screen_texture = false;
2306 			p_shader->canvas_item.uses_screen_uv = false;
2307 			p_shader->canvas_item.uses_time = false;
2308 
2309 			shaders.actions_canvas.render_mode_values["blend_add"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_ADD);
2310 			shaders.actions_canvas.render_mode_values["blend_mix"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_MIX);
2311 			shaders.actions_canvas.render_mode_values["blend_sub"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_SUB);
2312 			shaders.actions_canvas.render_mode_values["blend_mul"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_MUL);
2313 			shaders.actions_canvas.render_mode_values["blend_premul_alpha"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_PMALPHA);
2314 			shaders.actions_canvas.render_mode_values["blend_disabled"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_DISABLED);
2315 
2316 			shaders.actions_canvas.render_mode_values["unshaded"] = Pair<int *, int>(&p_shader->canvas_item.light_mode, Shader::CanvasItem::LIGHT_MODE_UNSHADED);
2317 			shaders.actions_canvas.render_mode_values["light_only"] = Pair<int *, int>(&p_shader->canvas_item.light_mode, Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY);
2318 
2319 			shaders.actions_canvas.usage_flag_pointers["SCREEN_UV"] = &p_shader->canvas_item.uses_screen_uv;
2320 			shaders.actions_canvas.usage_flag_pointers["SCREEN_PIXEL_SIZE"] = &p_shader->canvas_item.uses_screen_uv;
2321 			shaders.actions_canvas.usage_flag_pointers["SCREEN_TEXTURE"] = &p_shader->canvas_item.uses_screen_texture;
2322 			shaders.actions_canvas.usage_flag_pointers["TIME"] = &p_shader->canvas_item.uses_time;
2323 
2324 			actions = &shaders.actions_canvas;
2325 			actions->uniforms = &p_shader->uniforms;
2326 
2327 		} break;
2328 
2329 		case VS::SHADER_SPATIAL: {
2330 
2331 			p_shader->spatial.blend_mode = Shader::Spatial::BLEND_MODE_MIX;
2332 			p_shader->spatial.depth_draw_mode = Shader::Spatial::DEPTH_DRAW_OPAQUE;
2333 			p_shader->spatial.cull_mode = Shader::Spatial::CULL_MODE_BACK;
2334 			p_shader->spatial.uses_alpha = false;
2335 			p_shader->spatial.uses_alpha_scissor = false;
2336 			p_shader->spatial.uses_discard = false;
2337 			p_shader->spatial.unshaded = false;
2338 			p_shader->spatial.no_depth_test = false;
2339 			p_shader->spatial.uses_sss = false;
2340 			p_shader->spatial.uses_time = false;
2341 			p_shader->spatial.uses_vertex_lighting = false;
2342 			p_shader->spatial.uses_screen_texture = false;
2343 			p_shader->spatial.uses_depth_texture = false;
2344 			p_shader->spatial.uses_vertex = false;
2345 			p_shader->spatial.writes_modelview_or_projection = false;
2346 			p_shader->spatial.uses_world_coordinates = false;
2347 
2348 			shaders.actions_scene.render_mode_values["blend_add"] = Pair<int *, int>(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_ADD);
2349 			shaders.actions_scene.render_mode_values["blend_mix"] = Pair<int *, int>(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_MIX);
2350 			shaders.actions_scene.render_mode_values["blend_sub"] = Pair<int *, int>(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_SUB);
2351 			shaders.actions_scene.render_mode_values["blend_mul"] = Pair<int *, int>(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_MUL);
2352 
2353 			shaders.actions_scene.render_mode_values["depth_draw_opaque"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_OPAQUE);
2354 			shaders.actions_scene.render_mode_values["depth_draw_always"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_ALWAYS);
2355 			shaders.actions_scene.render_mode_values["depth_draw_never"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_NEVER);
2356 			shaders.actions_scene.render_mode_values["depth_draw_alpha_prepass"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS);
2357 
2358 			shaders.actions_scene.render_mode_values["cull_front"] = Pair<int *, int>(&p_shader->spatial.cull_mode, Shader::Spatial::CULL_MODE_FRONT);
2359 			shaders.actions_scene.render_mode_values["cull_back"] = Pair<int *, int>(&p_shader->spatial.cull_mode, Shader::Spatial::CULL_MODE_BACK);
2360 			shaders.actions_scene.render_mode_values["cull_disabled"] = Pair<int *, int>(&p_shader->spatial.cull_mode, Shader::Spatial::CULL_MODE_DISABLED);
2361 
2362 			shaders.actions_scene.render_mode_flags["unshaded"] = &p_shader->spatial.unshaded;
2363 			shaders.actions_scene.render_mode_flags["depth_test_disable"] = &p_shader->spatial.no_depth_test;
2364 
2365 			shaders.actions_scene.render_mode_flags["vertex_lighting"] = &p_shader->spatial.uses_vertex_lighting;
2366 
2367 			shaders.actions_scene.render_mode_flags["world_vertex_coords"] = &p_shader->spatial.uses_world_coordinates;
2368 
2369 			shaders.actions_scene.usage_flag_pointers["ALPHA"] = &p_shader->spatial.uses_alpha;
2370 			shaders.actions_scene.usage_flag_pointers["ALPHA_SCISSOR"] = &p_shader->spatial.uses_alpha_scissor;
2371 
2372 			shaders.actions_scene.usage_flag_pointers["SSS_STRENGTH"] = &p_shader->spatial.uses_sss;
2373 			shaders.actions_scene.usage_flag_pointers["DISCARD"] = &p_shader->spatial.uses_discard;
2374 			shaders.actions_scene.usage_flag_pointers["SCREEN_TEXTURE"] = &p_shader->spatial.uses_screen_texture;
2375 			shaders.actions_scene.usage_flag_pointers["DEPTH_TEXTURE"] = &p_shader->spatial.uses_depth_texture;
2376 			shaders.actions_scene.usage_flag_pointers["TIME"] = &p_shader->spatial.uses_time;
2377 
2378 			shaders.actions_scene.write_flag_pointers["MODELVIEW_MATRIX"] = &p_shader->spatial.writes_modelview_or_projection;
2379 			shaders.actions_scene.write_flag_pointers["PROJECTION_MATRIX"] = &p_shader->spatial.writes_modelview_or_projection;
2380 			shaders.actions_scene.write_flag_pointers["VERTEX"] = &p_shader->spatial.uses_vertex;
2381 
2382 			actions = &shaders.actions_scene;
2383 			actions->uniforms = &p_shader->uniforms;
2384 
2385 		} break;
2386 		case VS::SHADER_PARTICLES: {
2387 
2388 			actions = &shaders.actions_particles;
2389 			actions->uniforms = &p_shader->uniforms;
2390 		} break;
2391 		case VS::SHADER_MAX:
2392 			break; // Can't happen, but silences warning
2393 	}
2394 
2395 	Error err = shaders.compiler.compile(p_shader->mode, p_shader->code, actions, p_shader->path, gen_code);
2396 	if (err != OK) {
2397 		return;
2398 	}
2399 
2400 	p_shader->shader->set_custom_shader_code(p_shader->custom_code_id, gen_code.vertex, gen_code.vertex_global, gen_code.fragment, gen_code.light, gen_code.fragment_global, gen_code.uniforms, gen_code.texture_uniforms, gen_code.defines);
2401 
2402 	p_shader->ubo_size = gen_code.uniform_total_size;
2403 	p_shader->ubo_offsets = gen_code.uniform_offsets;
2404 	p_shader->texture_count = gen_code.texture_uniforms.size();
2405 	p_shader->texture_hints = gen_code.texture_hints;
2406 	p_shader->texture_types = gen_code.texture_types;
2407 
2408 	p_shader->uses_vertex_time = gen_code.uses_vertex_time;
2409 	p_shader->uses_fragment_time = gen_code.uses_fragment_time;
2410 
2411 	//all materials using this shader will have to be invalidated, unfortunately
2412 
2413 	for (SelfList<Material> *E = p_shader->materials.first(); E; E = E->next()) {
2414 
2415 		_material_make_dirty(E->self());
2416 	}
2417 
2418 	p_shader->valid = true;
2419 	p_shader->version++;
2420 }
2421 
2422 void RasterizerStorageGLES3::update_dirty_shaders() {
2423 
2424 	while (_shader_dirty_list.first()) {
2425 		_update_shader(_shader_dirty_list.first()->self());
2426 	}
2427 }
2428 
2429 void RasterizerStorageGLES3::shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const {
2430 
2431 	Shader *shader = shader_owner.get(p_shader);
2432 	ERR_FAIL_COND(!shader);
2433 
2434 	if (shader->dirty_list.in_list())
2435 		_update_shader(shader); // ok should be not anymore dirty
2436 
2437 	Map<int, StringName> order;
2438 
2439 	for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = shader->uniforms.front(); E; E = E->next()) {
2440 
2441 		if (E->get().texture_order >= 0) {
2442 			order[E->get().texture_order + 100000] = E->key();
2443 		} else {
2444 			order[E->get().order] = E->key();
2445 		}
2446 	}
2447 
2448 	for (Map<int, StringName>::Element *E = order.front(); E; E = E->next()) {
2449 
2450 		PropertyInfo pi;
2451 		ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[E->get()];
2452 		pi.name = E->get();
2453 		switch (u.type) {
2454 			case ShaderLanguage::TYPE_VOID: pi.type = Variant::NIL; break;
2455 			case ShaderLanguage::TYPE_BOOL: pi.type = Variant::BOOL; break;
2456 			case ShaderLanguage::TYPE_BVEC2:
2457 				pi.type = Variant::INT;
2458 				pi.hint = PROPERTY_HINT_FLAGS;
2459 				pi.hint_string = "x,y";
2460 				break;
2461 			case ShaderLanguage::TYPE_BVEC3:
2462 				pi.type = Variant::INT;
2463 				pi.hint = PROPERTY_HINT_FLAGS;
2464 				pi.hint_string = "x,y,z";
2465 				break;
2466 			case ShaderLanguage::TYPE_BVEC4:
2467 				pi.type = Variant::INT;
2468 				pi.hint = PROPERTY_HINT_FLAGS;
2469 				pi.hint_string = "x,y,z,w";
2470 				break;
2471 			case ShaderLanguage::TYPE_UINT:
2472 			case ShaderLanguage::TYPE_INT: {
2473 				pi.type = Variant::INT;
2474 				if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
2475 					pi.hint = PROPERTY_HINT_RANGE;
2476 					pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]);
2477 				}
2478 
2479 			} break;
2480 			case ShaderLanguage::TYPE_IVEC2:
2481 			case ShaderLanguage::TYPE_IVEC3:
2482 			case ShaderLanguage::TYPE_IVEC4:
2483 			case ShaderLanguage::TYPE_UVEC2:
2484 			case ShaderLanguage::TYPE_UVEC3:
2485 			case ShaderLanguage::TYPE_UVEC4: {
2486 
2487 				pi.type = Variant::POOL_INT_ARRAY;
2488 			} break;
2489 			case ShaderLanguage::TYPE_FLOAT: {
2490 				pi.type = Variant::REAL;
2491 				if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
2492 					pi.hint = PROPERTY_HINT_RANGE;
2493 					pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]);
2494 				}
2495 
2496 			} break;
2497 			case ShaderLanguage::TYPE_VEC2: pi.type = Variant::VECTOR2; break;
2498 			case ShaderLanguage::TYPE_VEC3: pi.type = Variant::VECTOR3; break;
2499 			case ShaderLanguage::TYPE_VEC4: {
2500 				if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) {
2501 					pi.type = Variant::COLOR;
2502 				} else {
2503 					pi.type = Variant::PLANE;
2504 				}
2505 			} break;
2506 			case ShaderLanguage::TYPE_MAT2: pi.type = Variant::TRANSFORM2D; break;
2507 			case ShaderLanguage::TYPE_MAT3: pi.type = Variant::BASIS; break;
2508 			case ShaderLanguage::TYPE_MAT4: pi.type = Variant::TRANSFORM; break;
2509 			case ShaderLanguage::TYPE_SAMPLER2D:
2510 			case ShaderLanguage::TYPE_SAMPLEREXT:
2511 			case ShaderLanguage::TYPE_ISAMPLER2D:
2512 			case ShaderLanguage::TYPE_USAMPLER2D: {
2513 
2514 				pi.type = Variant::OBJECT;
2515 				pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
2516 				pi.hint_string = "Texture";
2517 			} break;
2518 			case ShaderLanguage::TYPE_SAMPLER2DARRAY:
2519 			case ShaderLanguage::TYPE_ISAMPLER2DARRAY:
2520 			case ShaderLanguage::TYPE_USAMPLER2DARRAY: {
2521 
2522 				pi.type = Variant::OBJECT;
2523 				pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
2524 				pi.hint_string = "TextureArray";
2525 			} break;
2526 			case ShaderLanguage::TYPE_SAMPLER3D:
2527 			case ShaderLanguage::TYPE_ISAMPLER3D:
2528 			case ShaderLanguage::TYPE_USAMPLER3D: {
2529 				pi.type = Variant::OBJECT;
2530 				pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
2531 				pi.hint_string = "Texture3D";
2532 			} break;
2533 			case ShaderLanguage::TYPE_SAMPLERCUBE: {
2534 
2535 				pi.type = Variant::OBJECT;
2536 				pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
2537 				pi.hint_string = "CubeMap";
2538 			} break;
2539 		};
2540 
2541 		p_param_list->push_back(pi);
2542 	}
2543 }
2544 
2545 void RasterizerStorageGLES3::shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) {
2546 
2547 	Shader *shader = shader_owner.get(p_shader);
2548 	ERR_FAIL_COND(!shader);
2549 	ERR_FAIL_COND(p_texture.is_valid() && !texture_owner.owns(p_texture));
2550 
2551 	if (p_texture.is_valid())
2552 		shader->default_textures[p_name] = p_texture;
2553 	else
2554 		shader->default_textures.erase(p_name);
2555 
2556 	_shader_make_dirty(shader);
2557 }
2558 RID RasterizerStorageGLES3::shader_get_default_texture_param(RID p_shader, const StringName &p_name) const {
2559 
2560 	const Shader *shader = shader_owner.get(p_shader);
2561 	ERR_FAIL_COND_V(!shader, RID());
2562 
2563 	const Map<StringName, RID>::Element *E = shader->default_textures.find(p_name);
2564 	if (!E)
2565 		return RID();
2566 	return E->get();
2567 }
2568 
2569 void RasterizerStorageGLES3::shader_add_custom_define(RID p_shader, const String &p_define) {
2570 
2571 	Shader *shader = shader_owner.get(p_shader);
2572 	ERR_FAIL_COND(!shader);
2573 
2574 	shader->shader->add_custom_define(p_define);
2575 
2576 	_shader_make_dirty(shader);
2577 }
2578 
2579 void RasterizerStorageGLES3::shader_get_custom_defines(RID p_shader, Vector<String> *p_defines) const {
2580 
2581 	Shader *shader = shader_owner.get(p_shader);
2582 	ERR_FAIL_COND(!shader);
2583 
2584 	shader->shader->get_custom_defines(p_defines);
2585 }
2586 
2587 void RasterizerStorageGLES3::shader_remove_custom_define(RID p_shader, const String &p_define) {
2588 
2589 	Shader *shader = shader_owner.get(p_shader);
2590 	ERR_FAIL_COND(!shader);
2591 
2592 	shader->shader->remove_custom_define(p_define);
2593 
2594 	_shader_make_dirty(shader);
2595 }
2596 
2597 /* COMMON MATERIAL API */
2598 
2599 void RasterizerStorageGLES3::_material_make_dirty(Material *p_material) const {
2600 
2601 	if (p_material->dirty_list.in_list())
2602 		return;
2603 
2604 	_material_dirty_list.add(&p_material->dirty_list);
2605 }
2606 
2607 RID RasterizerStorageGLES3::material_create() {
2608 
2609 	Material *material = memnew(Material);
2610 
2611 	return material_owner.make_rid(material);
2612 }
2613 
2614 void RasterizerStorageGLES3::material_set_shader(RID p_material, RID p_shader) {
2615 
2616 	Material *material = material_owner.get(p_material);
2617 	ERR_FAIL_COND(!material);
2618 
2619 	Shader *shader = shader_owner.getornull(p_shader);
2620 
2621 	if (material->shader) {
2622 		//if shader, remove from previous shader material list
2623 		material->shader->materials.remove(&material->list);
2624 	}
2625 	material->shader = shader;
2626 
2627 	if (shader) {
2628 		shader->materials.add(&material->list);
2629 	}
2630 
2631 	_material_make_dirty(material);
2632 }
2633 
2634 RID RasterizerStorageGLES3::material_get_shader(RID p_material) const {
2635 
2636 	const Material *material = material_owner.get(p_material);
2637 	ERR_FAIL_COND_V(!material, RID());
2638 
2639 	if (material->shader)
2640 		return material->shader->self;
2641 
2642 	return RID();
2643 }
2644 
2645 void RasterizerStorageGLES3::material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) {
2646 
2647 	Material *material = material_owner.get(p_material);
2648 	ERR_FAIL_COND(!material);
2649 
2650 	if (p_value.get_type() == Variant::NIL)
2651 		material->params.erase(p_param);
2652 	else
2653 		material->params[p_param] = p_value;
2654 
2655 	_material_make_dirty(material);
2656 }
2657 Variant RasterizerStorageGLES3::material_get_param(RID p_material, const StringName &p_param) const {
2658 
2659 	const Material *material = material_owner.get(p_material);
2660 	ERR_FAIL_COND_V(!material, Variant());
2661 
2662 	if (material->params.has(p_param))
2663 		return material->params[p_param];
2664 
2665 	return material_get_param_default(p_material, p_param);
2666 }
2667 
2668 Variant RasterizerStorageGLES3::material_get_param_default(RID p_material, const StringName &p_param) const {
2669 	const Material *material = material_owner.get(p_material);
2670 	ERR_FAIL_COND_V(!material, Variant());
2671 
2672 	if (material->shader) {
2673 		if (material->shader->uniforms.has(p_param)) {
2674 			ShaderLanguage::ShaderNode::Uniform uniform = material->shader->uniforms[p_param];
2675 			Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value;
2676 			return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint);
2677 		}
2678 	}
2679 	return Variant();
2680 }
2681 
2682 void RasterizerStorageGLES3::material_set_line_width(RID p_material, float p_width) {
2683 
2684 	Material *material = material_owner.get(p_material);
2685 	ERR_FAIL_COND(!material);
2686 
2687 	material->line_width = p_width;
2688 }
2689 
2690 void RasterizerStorageGLES3::material_set_next_pass(RID p_material, RID p_next_material) {
2691 
2692 	Material *material = material_owner.get(p_material);
2693 	ERR_FAIL_COND(!material);
2694 
2695 	material->next_pass = p_next_material;
2696 }
2697 
2698 bool RasterizerStorageGLES3::material_is_animated(RID p_material) {
2699 
2700 	Material *material = material_owner.get(p_material);
2701 	ERR_FAIL_COND_V(!material, false);
2702 	if (material->dirty_list.in_list()) {
2703 		_update_material(material);
2704 	}
2705 
2706 	bool animated = material->is_animated_cache;
2707 	if (!animated && material->next_pass.is_valid()) {
2708 		animated = material_is_animated(material->next_pass);
2709 	}
2710 	return animated;
2711 }
2712 bool RasterizerStorageGLES3::material_casts_shadows(RID p_material) {
2713 
2714 	Material *material = material_owner.get(p_material);
2715 	ERR_FAIL_COND_V(!material, false);
2716 	if (material->dirty_list.in_list()) {
2717 		_update_material(material);
2718 	}
2719 
2720 	bool casts_shadows = material->can_cast_shadow_cache;
2721 
2722 	if (!casts_shadows && material->next_pass.is_valid()) {
2723 		casts_shadows = material_casts_shadows(material->next_pass);
2724 	}
2725 
2726 	return casts_shadows;
2727 }
2728 
2729 void RasterizerStorageGLES3::material_add_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) {
2730 
2731 	Material *material = material_owner.get(p_material);
2732 	ERR_FAIL_COND(!material);
2733 
2734 	Map<RasterizerScene::InstanceBase *, int>::Element *E = material->instance_owners.find(p_instance);
2735 	if (E) {
2736 		E->get()++;
2737 	} else {
2738 		material->instance_owners[p_instance] = 1;
2739 	}
2740 }
2741 
2742 void RasterizerStorageGLES3::material_remove_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) {
2743 
2744 	Material *material = material_owner.get(p_material);
2745 	ERR_FAIL_COND(!material);
2746 
2747 	Map<RasterizerScene::InstanceBase *, int>::Element *E = material->instance_owners.find(p_instance);
2748 	ERR_FAIL_COND(!E);
2749 	E->get()--;
2750 
2751 	if (E->get() == 0) {
2752 		material->instance_owners.erase(E);
2753 	}
2754 }
2755 
2756 void RasterizerStorageGLES3::material_set_render_priority(RID p_material, int priority) {
2757 
2758 	ERR_FAIL_COND(priority < VS::MATERIAL_RENDER_PRIORITY_MIN);
2759 	ERR_FAIL_COND(priority > VS::MATERIAL_RENDER_PRIORITY_MAX);
2760 
2761 	Material *material = material_owner.get(p_material);
2762 	ERR_FAIL_COND(!material);
2763 
2764 	material->render_priority = priority;
2765 }
2766 
2767 _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataType type, const Variant &value, uint8_t *data, bool p_linear_color) {
2768 	switch (type) {
2769 		case ShaderLanguage::TYPE_BOOL: {
2770 
2771 			bool v = value;
2772 
2773 			GLuint *gui = (GLuint *)data;
2774 			*gui = v ? GL_TRUE : GL_FALSE;
2775 		} break;
2776 		case ShaderLanguage::TYPE_BVEC2: {
2777 
2778 			int v = value;
2779 			GLuint *gui = (GLuint *)data;
2780 			gui[0] = (v & 1) ? GL_TRUE : GL_FALSE;
2781 			gui[1] = (v & 2) ? GL_TRUE : GL_FALSE;
2782 
2783 		} break;
2784 		case ShaderLanguage::TYPE_BVEC3: {
2785 
2786 			int v = value;
2787 			GLuint *gui = (GLuint *)data;
2788 			gui[0] = (v & 1) ? GL_TRUE : GL_FALSE;
2789 			gui[1] = (v & 2) ? GL_TRUE : GL_FALSE;
2790 			gui[2] = (v & 4) ? GL_TRUE : GL_FALSE;
2791 
2792 		} break;
2793 		case ShaderLanguage::TYPE_BVEC4: {
2794 
2795 			int v = value;
2796 			GLuint *gui = (GLuint *)data;
2797 			gui[0] = (v & 1) ? GL_TRUE : GL_FALSE;
2798 			gui[1] = (v & 2) ? GL_TRUE : GL_FALSE;
2799 			gui[2] = (v & 4) ? GL_TRUE : GL_FALSE;
2800 			gui[3] = (v & 8) ? GL_TRUE : GL_FALSE;
2801 
2802 		} break;
2803 		case ShaderLanguage::TYPE_INT: {
2804 
2805 			int v = value;
2806 			GLint *gui = (GLint *)data;
2807 			gui[0] = v;
2808 
2809 		} break;
2810 		case ShaderLanguage::TYPE_IVEC2: {
2811 
2812 			PoolVector<int> iv = value;
2813 			int s = iv.size();
2814 			GLint *gui = (GLint *)data;
2815 
2816 			PoolVector<int>::Read r = iv.read();
2817 
2818 			for (int i = 0; i < 2; i++) {
2819 				if (i < s)
2820 					gui[i] = r[i];
2821 				else
2822 					gui[i] = 0;
2823 			}
2824 
2825 		} break;
2826 		case ShaderLanguage::TYPE_IVEC3: {
2827 
2828 			PoolVector<int> iv = value;
2829 			int s = iv.size();
2830 			GLint *gui = (GLint *)data;
2831 
2832 			PoolVector<int>::Read r = iv.read();
2833 
2834 			for (int i = 0; i < 3; i++) {
2835 				if (i < s)
2836 					gui[i] = r[i];
2837 				else
2838 					gui[i] = 0;
2839 			}
2840 		} break;
2841 		case ShaderLanguage::TYPE_IVEC4: {
2842 
2843 			PoolVector<int> iv = value;
2844 			int s = iv.size();
2845 			GLint *gui = (GLint *)data;
2846 
2847 			PoolVector<int>::Read r = iv.read();
2848 
2849 			for (int i = 0; i < 4; i++) {
2850 				if (i < s)
2851 					gui[i] = r[i];
2852 				else
2853 					gui[i] = 0;
2854 			}
2855 		} break;
2856 		case ShaderLanguage::TYPE_UINT: {
2857 
2858 			int v = value;
2859 			GLuint *gui = (GLuint *)data;
2860 			gui[0] = v;
2861 
2862 		} break;
2863 		case ShaderLanguage::TYPE_UVEC2: {
2864 
2865 			PoolVector<int> iv = value;
2866 			int s = iv.size();
2867 			GLuint *gui = (GLuint *)data;
2868 
2869 			PoolVector<int>::Read r = iv.read();
2870 
2871 			for (int i = 0; i < 2; i++) {
2872 				if (i < s)
2873 					gui[i] = r[i];
2874 				else
2875 					gui[i] = 0;
2876 			}
2877 		} break;
2878 		case ShaderLanguage::TYPE_UVEC3: {
2879 			PoolVector<int> iv = value;
2880 			int s = iv.size();
2881 			GLuint *gui = (GLuint *)data;
2882 
2883 			PoolVector<int>::Read r = iv.read();
2884 
2885 			for (int i = 0; i < 3; i++) {
2886 				if (i < s)
2887 					gui[i] = r[i];
2888 				else
2889 					gui[i] = 0;
2890 			}
2891 
2892 		} break;
2893 		case ShaderLanguage::TYPE_UVEC4: {
2894 			PoolVector<int> iv = value;
2895 			int s = iv.size();
2896 			GLuint *gui = (GLuint *)data;
2897 
2898 			PoolVector<int>::Read r = iv.read();
2899 
2900 			for (int i = 0; i < 4; i++) {
2901 				if (i < s)
2902 					gui[i] = r[i];
2903 				else
2904 					gui[i] = 0;
2905 			}
2906 		} break;
2907 		case ShaderLanguage::TYPE_FLOAT: {
2908 			float v = value;
2909 			GLfloat *gui = (GLfloat *)data;
2910 			gui[0] = v;
2911 
2912 		} break;
2913 		case ShaderLanguage::TYPE_VEC2: {
2914 			Vector2 v = value;
2915 			GLfloat *gui = (GLfloat *)data;
2916 			gui[0] = v.x;
2917 			gui[1] = v.y;
2918 
2919 		} break;
2920 		case ShaderLanguage::TYPE_VEC3: {
2921 			Vector3 v = value;
2922 			GLfloat *gui = (GLfloat *)data;
2923 			gui[0] = v.x;
2924 			gui[1] = v.y;
2925 			gui[2] = v.z;
2926 
2927 		} break;
2928 		case ShaderLanguage::TYPE_VEC4: {
2929 
2930 			GLfloat *gui = (GLfloat *)data;
2931 
2932 			if (value.get_type() == Variant::COLOR) {
2933 				Color v = value;
2934 
2935 				if (p_linear_color) {
2936 					v = v.to_linear();
2937 				}
2938 
2939 				gui[0] = v.r;
2940 				gui[1] = v.g;
2941 				gui[2] = v.b;
2942 				gui[3] = v.a;
2943 			} else if (value.get_type() == Variant::RECT2) {
2944 				Rect2 v = value;
2945 
2946 				gui[0] = v.position.x;
2947 				gui[1] = v.position.y;
2948 				gui[2] = v.size.x;
2949 				gui[3] = v.size.y;
2950 			} else if (value.get_type() == Variant::QUAT) {
2951 				Quat v = value;
2952 
2953 				gui[0] = v.x;
2954 				gui[1] = v.y;
2955 				gui[2] = v.z;
2956 				gui[3] = v.w;
2957 			} else {
2958 				Plane v = value;
2959 
2960 				gui[0] = v.normal.x;
2961 				gui[1] = v.normal.y;
2962 				gui[2] = v.normal.z;
2963 				gui[3] = v.d;
2964 			}
2965 		} break;
2966 		case ShaderLanguage::TYPE_MAT2: {
2967 			Transform2D v = value;
2968 			GLfloat *gui = (GLfloat *)data;
2969 
2970 			//in std140 members of mat2 are treated as vec4s
2971 			gui[0] = v.elements[0][0];
2972 			gui[1] = v.elements[0][1];
2973 			gui[2] = 0;
2974 			gui[3] = 0;
2975 			gui[4] = v.elements[1][0];
2976 			gui[5] = v.elements[1][1];
2977 			gui[6] = 0;
2978 			gui[7] = 0;
2979 		} break;
2980 		case ShaderLanguage::TYPE_MAT3: {
2981 
2982 			Basis v = value;
2983 			GLfloat *gui = (GLfloat *)data;
2984 
2985 			gui[0] = v.elements[0][0];
2986 			gui[1] = v.elements[1][0];
2987 			gui[2] = v.elements[2][0];
2988 			gui[3] = 0;
2989 			gui[4] = v.elements[0][1];
2990 			gui[5] = v.elements[1][1];
2991 			gui[6] = v.elements[2][1];
2992 			gui[7] = 0;
2993 			gui[8] = v.elements[0][2];
2994 			gui[9] = v.elements[1][2];
2995 			gui[10] = v.elements[2][2];
2996 			gui[11] = 0;
2997 		} break;
2998 		case ShaderLanguage::TYPE_MAT4: {
2999 
3000 			Transform v = value;
3001 			GLfloat *gui = (GLfloat *)data;
3002 
3003 			gui[0] = v.basis.elements[0][0];
3004 			gui[1] = v.basis.elements[1][0];
3005 			gui[2] = v.basis.elements[2][0];
3006 			gui[3] = 0;
3007 			gui[4] = v.basis.elements[0][1];
3008 			gui[5] = v.basis.elements[1][1];
3009 			gui[6] = v.basis.elements[2][1];
3010 			gui[7] = 0;
3011 			gui[8] = v.basis.elements[0][2];
3012 			gui[9] = v.basis.elements[1][2];
3013 			gui[10] = v.basis.elements[2][2];
3014 			gui[11] = 0;
3015 			gui[12] = v.origin.x;
3016 			gui[13] = v.origin.y;
3017 			gui[14] = v.origin.z;
3018 			gui[15] = 1;
3019 		} break;
3020 		default: {
3021 		}
3022 	}
3023 }
3024 
3025 _FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type, const Vector<ShaderLanguage::ConstantNode::Value> &value, uint8_t *data) {
3026 
3027 	switch (type) {
3028 		case ShaderLanguage::TYPE_BOOL: {
3029 
3030 			GLuint *gui = (GLuint *)data;
3031 			*gui = value[0].boolean ? GL_TRUE : GL_FALSE;
3032 		} break;
3033 		case ShaderLanguage::TYPE_BVEC2: {
3034 
3035 			GLuint *gui = (GLuint *)data;
3036 			gui[0] = value[0].boolean ? GL_TRUE : GL_FALSE;
3037 			gui[1] = value[1].boolean ? GL_TRUE : GL_FALSE;
3038 
3039 		} break;
3040 		case ShaderLanguage::TYPE_BVEC3: {
3041 
3042 			GLuint *gui = (GLuint *)data;
3043 			gui[0] = value[0].boolean ? GL_TRUE : GL_FALSE;
3044 			gui[1] = value[1].boolean ? GL_TRUE : GL_FALSE;
3045 			gui[2] = value[2].boolean ? GL_TRUE : GL_FALSE;
3046 
3047 		} break;
3048 		case ShaderLanguage::TYPE_BVEC4: {
3049 
3050 			GLuint *gui = (GLuint *)data;
3051 			gui[0] = value[0].boolean ? GL_TRUE : GL_FALSE;
3052 			gui[1] = value[1].boolean ? GL_TRUE : GL_FALSE;
3053 			gui[2] = value[2].boolean ? GL_TRUE : GL_FALSE;
3054 			gui[3] = value[3].boolean ? GL_TRUE : GL_FALSE;
3055 
3056 		} break;
3057 		case ShaderLanguage::TYPE_INT: {
3058 
3059 			GLint *gui = (GLint *)data;
3060 			gui[0] = value[0].sint;
3061 
3062 		} break;
3063 		case ShaderLanguage::TYPE_IVEC2: {
3064 
3065 			GLint *gui = (GLint *)data;
3066 
3067 			for (int i = 0; i < 2; i++) {
3068 				gui[i] = value[i].sint;
3069 			}
3070 
3071 		} break;
3072 		case ShaderLanguage::TYPE_IVEC3: {
3073 
3074 			GLint *gui = (GLint *)data;
3075 
3076 			for (int i = 0; i < 3; i++) {
3077 				gui[i] = value[i].sint;
3078 			}
3079 
3080 		} break;
3081 		case ShaderLanguage::TYPE_IVEC4: {
3082 
3083 			GLint *gui = (GLint *)data;
3084 
3085 			for (int i = 0; i < 4; i++) {
3086 				gui[i] = value[i].sint;
3087 			}
3088 
3089 		} break;
3090 		case ShaderLanguage::TYPE_UINT: {
3091 
3092 			GLuint *gui = (GLuint *)data;
3093 			gui[0] = value[0].uint;
3094 
3095 		} break;
3096 		case ShaderLanguage::TYPE_UVEC2: {
3097 
3098 			GLint *gui = (GLint *)data;
3099 
3100 			for (int i = 0; i < 2; i++) {
3101 				gui[i] = value[i].uint;
3102 			}
3103 		} break;
3104 		case ShaderLanguage::TYPE_UVEC3: {
3105 			GLint *gui = (GLint *)data;
3106 
3107 			for (int i = 0; i < 3; i++) {
3108 				gui[i] = value[i].uint;
3109 			}
3110 
3111 		} break;
3112 		case ShaderLanguage::TYPE_UVEC4: {
3113 			GLint *gui = (GLint *)data;
3114 
3115 			for (int i = 0; i < 4; i++) {
3116 				gui[i] = value[i].uint;
3117 			}
3118 		} break;
3119 		case ShaderLanguage::TYPE_FLOAT: {
3120 
3121 			GLfloat *gui = (GLfloat *)data;
3122 			gui[0] = value[0].real;
3123 
3124 		} break;
3125 		case ShaderLanguage::TYPE_VEC2: {
3126 
3127 			GLfloat *gui = (GLfloat *)data;
3128 
3129 			for (int i = 0; i < 2; i++) {
3130 				gui[i] = value[i].real;
3131 			}
3132 
3133 		} break;
3134 		case ShaderLanguage::TYPE_VEC3: {
3135 
3136 			GLfloat *gui = (GLfloat *)data;
3137 
3138 			for (int i = 0; i < 3; i++) {
3139 				gui[i] = value[i].real;
3140 			}
3141 
3142 		} break;
3143 		case ShaderLanguage::TYPE_VEC4: {
3144 
3145 			GLfloat *gui = (GLfloat *)data;
3146 
3147 			for (int i = 0; i < 4; i++) {
3148 				gui[i] = value[i].real;
3149 			}
3150 		} break;
3151 		case ShaderLanguage::TYPE_MAT2: {
3152 			GLfloat *gui = (GLfloat *)data;
3153 
3154 			//in std140 members of mat2 are treated as vec4s
3155 			gui[0] = value[0].real;
3156 			gui[1] = value[1].real;
3157 			gui[2] = 0;
3158 			gui[3] = 0;
3159 			gui[4] = value[2].real;
3160 			gui[5] = value[3].real;
3161 			gui[6] = 0;
3162 			gui[7] = 0;
3163 		} break;
3164 		case ShaderLanguage::TYPE_MAT3: {
3165 
3166 			GLfloat *gui = (GLfloat *)data;
3167 
3168 			gui[0] = value[0].real;
3169 			gui[1] = value[1].real;
3170 			gui[2] = value[2].real;
3171 			gui[3] = 0;
3172 			gui[4] = value[3].real;
3173 			gui[5] = value[4].real;
3174 			gui[6] = value[5].real;
3175 			gui[7] = 0;
3176 			gui[8] = value[6].real;
3177 			gui[9] = value[7].real;
3178 			gui[10] = value[8].real;
3179 			gui[11] = 0;
3180 		} break;
3181 		case ShaderLanguage::TYPE_MAT4: {
3182 
3183 			GLfloat *gui = (GLfloat *)data;
3184 
3185 			for (int i = 0; i < 16; i++) {
3186 				gui[i] = value[i].real;
3187 			}
3188 		} break;
3189 		default: {
3190 		}
3191 	}
3192 }
3193 
3194 _FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type, uint8_t *data) {
3195 
3196 	switch (type) {
3197 
3198 		case ShaderLanguage::TYPE_BOOL:
3199 		case ShaderLanguage::TYPE_INT:
3200 		case ShaderLanguage::TYPE_UINT:
3201 		case ShaderLanguage::TYPE_FLOAT: {
3202 			zeromem(data, 4);
3203 		} break;
3204 		case ShaderLanguage::TYPE_BVEC2:
3205 		case ShaderLanguage::TYPE_IVEC2:
3206 		case ShaderLanguage::TYPE_UVEC2:
3207 		case ShaderLanguage::TYPE_VEC2: {
3208 			zeromem(data, 8);
3209 		} break;
3210 		case ShaderLanguage::TYPE_BVEC3:
3211 		case ShaderLanguage::TYPE_IVEC3:
3212 		case ShaderLanguage::TYPE_UVEC3:
3213 		case ShaderLanguage::TYPE_VEC3: {
3214 			zeromem(data, 12);
3215 		} break;
3216 		case ShaderLanguage::TYPE_BVEC4:
3217 		case ShaderLanguage::TYPE_IVEC4:
3218 		case ShaderLanguage::TYPE_UVEC4:
3219 		case ShaderLanguage::TYPE_VEC4: {
3220 
3221 			zeromem(data, 16);
3222 		} break;
3223 		case ShaderLanguage::TYPE_MAT2: {
3224 
3225 			zeromem(data, 32);
3226 		} break;
3227 		case ShaderLanguage::TYPE_MAT3: {
3228 
3229 			zeromem(data, 48);
3230 		} break;
3231 		case ShaderLanguage::TYPE_MAT4: {
3232 			zeromem(data, 64);
3233 		} break;
3234 
3235 		default: {
3236 		}
3237 	}
3238 }
3239 
3240 void RasterizerStorageGLES3::_update_material(Material *material) {
3241 
3242 	if (material->dirty_list.in_list())
3243 		_material_dirty_list.remove(&material->dirty_list);
3244 
3245 	if (material->shader && material->shader->dirty_list.in_list()) {
3246 		_update_shader(material->shader);
3247 	}
3248 
3249 	if (material->shader && !material->shader->valid)
3250 		return;
3251 
3252 	//update caches
3253 
3254 	{
3255 		bool can_cast_shadow = false;
3256 		bool is_animated = false;
3257 
3258 		if (material->shader && material->shader->mode == VS::SHADER_SPATIAL) {
3259 
3260 			if (material->shader->spatial.blend_mode == Shader::Spatial::BLEND_MODE_MIX &&
3261 					(!material->shader->spatial.uses_alpha || material->shader->spatial.depth_draw_mode == Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS)) {
3262 				can_cast_shadow = true;
3263 			}
3264 
3265 			if (material->shader->spatial.uses_discard && material->shader->uses_fragment_time) {
3266 				is_animated = true;
3267 			}
3268 
3269 			if (material->shader->spatial.uses_vertex && material->shader->uses_vertex_time) {
3270 				is_animated = true;
3271 			}
3272 
3273 			if (can_cast_shadow != material->can_cast_shadow_cache || is_animated != material->is_animated_cache) {
3274 				material->can_cast_shadow_cache = can_cast_shadow;
3275 				material->is_animated_cache = is_animated;
3276 
3277 				for (Map<Geometry *, int>::Element *E = material->geometry_owners.front(); E; E = E->next()) {
3278 					E->key()->material_changed_notify();
3279 				}
3280 
3281 				for (Map<RasterizerScene::InstanceBase *, int>::Element *E = material->instance_owners.front(); E; E = E->next()) {
3282 					E->key()->base_changed(false, true);
3283 				}
3284 			}
3285 		}
3286 	}
3287 
3288 	//clear ubo if it needs to be cleared
3289 	if (material->ubo_size) {
3290 
3291 		if (!material->shader || material->shader->ubo_size != material->ubo_size) {
3292 			//by by ubo
3293 			glDeleteBuffers(1, &material->ubo_id);
3294 			material->ubo_id = 0;
3295 			material->ubo_size = 0;
3296 		}
3297 	}
3298 
3299 	//create ubo if it needs to be created
3300 	if (material->ubo_size == 0 && material->shader && material->shader->ubo_size) {
3301 
3302 		glGenBuffers(1, &material->ubo_id);
3303 		glBindBuffer(GL_UNIFORM_BUFFER, material->ubo_id);
3304 		glBufferData(GL_UNIFORM_BUFFER, material->shader->ubo_size, NULL, GL_STATIC_DRAW);
3305 		glBindBuffer(GL_UNIFORM_BUFFER, 0);
3306 		material->ubo_size = material->shader->ubo_size;
3307 	}
3308 
3309 	//fill up the UBO if it needs to be filled
3310 	if (material->shader && material->ubo_size) {
3311 		uint8_t *local_ubo = (uint8_t *)alloca(material->ubo_size);
3312 
3313 		for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = material->shader->uniforms.front(); E; E = E->next()) {
3314 
3315 			if (E->get().order < 0)
3316 				continue; // texture, does not go here
3317 
3318 			//regular uniform
3319 			uint8_t *data = &local_ubo[material->shader->ubo_offsets[E->get().order]];
3320 
3321 			Map<StringName, Variant>::Element *V = material->params.find(E->key());
3322 
3323 			if (V) {
3324 				//user provided
3325 				_fill_std140_variant_ubo_value(E->get().type, V->get(), data, material->shader->mode == VS::SHADER_SPATIAL);
3326 
3327 			} else if (E->get().default_value.size()) {
3328 				//default value
3329 				_fill_std140_ubo_value(E->get().type, E->get().default_value, data);
3330 				//value=E->get().default_value;
3331 			} else {
3332 				//zero because it was not provided
3333 				if (E->get().type == ShaderLanguage::TYPE_VEC4 && E->get().hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) {
3334 					//colors must be set as black, with alpha as 1.0
3335 					_fill_std140_variant_ubo_value(E->get().type, Color(0, 0, 0, 1), data, material->shader->mode == VS::SHADER_SPATIAL);
3336 				} else {
3337 					//else just zero it out
3338 					_fill_std140_ubo_empty(E->get().type, data);
3339 				}
3340 			}
3341 		}
3342 
3343 		glBindBuffer(GL_UNIFORM_BUFFER, material->ubo_id);
3344 		glBufferData(GL_UNIFORM_BUFFER, material->ubo_size, local_ubo, GL_STATIC_DRAW);
3345 		glBindBuffer(GL_UNIFORM_BUFFER, 0);
3346 	}
3347 
3348 	//set up the texture array, for easy access when it needs to be drawn
3349 	if (material->shader && material->shader->texture_count) {
3350 
3351 		material->texture_is_3d.resize(material->shader->texture_count);
3352 		material->textures.resize(material->shader->texture_count);
3353 
3354 		for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = material->shader->uniforms.front(); E; E = E->next()) {
3355 
3356 			if (E->get().texture_order < 0)
3357 				continue; // not a texture, does not go here
3358 
3359 			RID texture;
3360 
3361 			switch (E->get().type) {
3362 				case ShaderLanguage::TYPE_SAMPLER3D:
3363 				case ShaderLanguage::TYPE_SAMPLER2DARRAY: {
3364 					material->texture_is_3d.write[E->get().texture_order] = true;
3365 				} break;
3366 				default: {
3367 					material->texture_is_3d.write[E->get().texture_order] = false;
3368 				} break;
3369 			}
3370 
3371 			Map<StringName, Variant>::Element *V = material->params.find(E->key());
3372 			if (V) {
3373 				texture = V->get();
3374 			}
3375 
3376 			if (!texture.is_valid()) {
3377 				Map<StringName, RID>::Element *W = material->shader->default_textures.find(E->key());
3378 				if (W) {
3379 					texture = W->get();
3380 				}
3381 			}
3382 
3383 			material->textures.write[E->get().texture_order] = texture;
3384 		}
3385 
3386 	} else {
3387 		material->textures.clear();
3388 		material->texture_is_3d.clear();
3389 	}
3390 }
3391 
3392 void RasterizerStorageGLES3::_material_add_geometry(RID p_material, Geometry *p_geometry) {
3393 
3394 	Material *material = material_owner.getornull(p_material);
3395 	ERR_FAIL_COND(!material);
3396 
3397 	Map<Geometry *, int>::Element *I = material->geometry_owners.find(p_geometry);
3398 
3399 	if (I) {
3400 		I->get()++;
3401 	} else {
3402 		material->geometry_owners[p_geometry] = 1;
3403 	}
3404 }
3405 
3406 void RasterizerStorageGLES3::_material_remove_geometry(RID p_material, Geometry *p_geometry) {
3407 
3408 	Material *material = material_owner.getornull(p_material);
3409 	ERR_FAIL_COND(!material);
3410 
3411 	Map<Geometry *, int>::Element *I = material->geometry_owners.find(p_geometry);
3412 	ERR_FAIL_COND(!I);
3413 
3414 	I->get()--;
3415 	if (I->get() == 0) {
3416 		material->geometry_owners.erase(I);
3417 	}
3418 }
3419 
3420 void RasterizerStorageGLES3::update_dirty_materials() {
3421 
3422 	while (_material_dirty_list.first()) {
3423 
3424 		Material *material = _material_dirty_list.first()->self();
3425 
3426 		_update_material(material);
3427 	}
3428 }
3429 
3430 /* MESH API */
3431 
3432 RID RasterizerStorageGLES3::mesh_create() {
3433 
3434 	Mesh *mesh = memnew(Mesh);
3435 
3436 	return mesh_owner.make_rid(mesh);
3437 }
3438 
3439 void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh, uint32_t p_format, VS::PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes, const Vector<AABB> &p_bone_aabbs) {
3440 
3441 	PoolVector<uint8_t> array = p_array;
3442 
3443 	Mesh *mesh = mesh_owner.getornull(p_mesh);
3444 	ERR_FAIL_COND(!mesh);
3445 
3446 	ERR_FAIL_COND(!(p_format & VS::ARRAY_FORMAT_VERTEX));
3447 
3448 	//must have index and bones, both.
3449 	{
3450 		uint32_t bones_weight = VS::ARRAY_FORMAT_BONES | VS::ARRAY_FORMAT_WEIGHTS;
3451 		ERR_FAIL_COND_MSG((p_format & bones_weight) && (p_format & bones_weight) != bones_weight, "Array must have both bones and weights in format or none.");
3452 	}
3453 
3454 	//bool has_morph = p_blend_shapes.size();
3455 
3456 	Surface::Attrib attribs[VS::ARRAY_MAX];
3457 
3458 	int stride = 0;
3459 
3460 	for (int i = 0; i < VS::ARRAY_MAX; i++) {
3461 
3462 		attribs[i].index = i;
3463 
3464 		if (!(p_format & (1 << i))) {
3465 			attribs[i].enabled = false;
3466 			attribs[i].integer = false;
3467 			continue;
3468 		}
3469 
3470 		attribs[i].enabled = true;
3471 		attribs[i].offset = stride;
3472 		attribs[i].integer = false;
3473 
3474 		switch (i) {
3475 
3476 			case VS::ARRAY_VERTEX: {
3477 
3478 				if (p_format & VS::ARRAY_FLAG_USE_2D_VERTICES) {
3479 					attribs[i].size = 2;
3480 				} else {
3481 					attribs[i].size = (p_format & VS::ARRAY_COMPRESS_VERTEX) ? 4 : 3;
3482 				}
3483 
3484 				if (p_format & VS::ARRAY_COMPRESS_VERTEX) {
3485 					attribs[i].type = GL_HALF_FLOAT;
3486 					stride += attribs[i].size * 2;
3487 				} else {
3488 					attribs[i].type = GL_FLOAT;
3489 					stride += attribs[i].size * 4;
3490 				}
3491 
3492 				attribs[i].normalized = GL_FALSE;
3493 
3494 			} break;
3495 			case VS::ARRAY_NORMAL: {
3496 
3497 				attribs[i].size = 3;
3498 
3499 				if (p_format & VS::ARRAY_COMPRESS_NORMAL) {
3500 					attribs[i].type = GL_BYTE;
3501 					stride += 4; //pad extra byte
3502 					attribs[i].normalized = GL_TRUE;
3503 				} else {
3504 					attribs[i].type = GL_FLOAT;
3505 					stride += 12;
3506 					attribs[i].normalized = GL_FALSE;
3507 				}
3508 
3509 			} break;
3510 			case VS::ARRAY_TANGENT: {
3511 
3512 				attribs[i].size = 4;
3513 
3514 				if (p_format & VS::ARRAY_COMPRESS_TANGENT) {
3515 					attribs[i].type = GL_BYTE;
3516 					stride += 4;
3517 					attribs[i].normalized = GL_TRUE;
3518 				} else {
3519 					attribs[i].type = GL_FLOAT;
3520 					stride += 16;
3521 					attribs[i].normalized = GL_FALSE;
3522 				}
3523 
3524 			} break;
3525 			case VS::ARRAY_COLOR: {
3526 
3527 				attribs[i].size = 4;
3528 
3529 				if (p_format & VS::ARRAY_COMPRESS_COLOR) {
3530 					attribs[i].type = GL_UNSIGNED_BYTE;
3531 					stride += 4;
3532 					attribs[i].normalized = GL_TRUE;
3533 				} else {
3534 					attribs[i].type = GL_FLOAT;
3535 					stride += 16;
3536 					attribs[i].normalized = GL_FALSE;
3537 				}
3538 
3539 			} break;
3540 			case VS::ARRAY_TEX_UV: {
3541 
3542 				attribs[i].size = 2;
3543 
3544 				if (p_format & VS::ARRAY_COMPRESS_TEX_UV) {
3545 					attribs[i].type = GL_HALF_FLOAT;
3546 					stride += 4;
3547 				} else {
3548 					attribs[i].type = GL_FLOAT;
3549 					stride += 8;
3550 				}
3551 
3552 				attribs[i].normalized = GL_FALSE;
3553 
3554 			} break;
3555 			case VS::ARRAY_TEX_UV2: {
3556 
3557 				attribs[i].size = 2;
3558 
3559 				if (p_format & VS::ARRAY_COMPRESS_TEX_UV2) {
3560 					attribs[i].type = GL_HALF_FLOAT;
3561 					stride += 4;
3562 				} else {
3563 					attribs[i].type = GL_FLOAT;
3564 					stride += 8;
3565 				}
3566 				attribs[i].normalized = GL_FALSE;
3567 
3568 			} break;
3569 			case VS::ARRAY_BONES: {
3570 
3571 				attribs[i].size = 4;
3572 
3573 				if (p_format & VS::ARRAY_FLAG_USE_16_BIT_BONES) {
3574 					attribs[i].type = GL_UNSIGNED_SHORT;
3575 					stride += 8;
3576 				} else {
3577 					attribs[i].type = GL_UNSIGNED_BYTE;
3578 					stride += 4;
3579 				}
3580 
3581 				attribs[i].normalized = GL_FALSE;
3582 				attribs[i].integer = true;
3583 
3584 			} break;
3585 			case VS::ARRAY_WEIGHTS: {
3586 
3587 				attribs[i].size = 4;
3588 
3589 				if (p_format & VS::ARRAY_COMPRESS_WEIGHTS) {
3590 
3591 					attribs[i].type = GL_UNSIGNED_SHORT;
3592 					stride += 8;
3593 					attribs[i].normalized = GL_TRUE;
3594 				} else {
3595 					attribs[i].type = GL_FLOAT;
3596 					stride += 16;
3597 					attribs[i].normalized = GL_FALSE;
3598 				}
3599 
3600 			} break;
3601 			case VS::ARRAY_INDEX: {
3602 
3603 				attribs[i].size = 1;
3604 
3605 				if (p_vertex_count >= (1 << 16)) {
3606 					attribs[i].type = GL_UNSIGNED_INT;
3607 					attribs[i].stride = 4;
3608 				} else {
3609 					attribs[i].type = GL_UNSIGNED_SHORT;
3610 					attribs[i].stride = 2;
3611 				}
3612 
3613 				attribs[i].normalized = GL_FALSE;
3614 
3615 			} break;
3616 		}
3617 	}
3618 
3619 	for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
3620 		attribs[i].stride = stride;
3621 	}
3622 
3623 	//validate sizes
3624 
3625 	int array_size = stride * p_vertex_count;
3626 	int index_array_size = 0;
3627 	if (array.size() != array_size && array.size() + p_vertex_count * 2 == array_size) {
3628 		//old format, convert
3629 		array = PoolVector<uint8_t>();
3630 
3631 		array.resize(p_array.size() + p_vertex_count * 2);
3632 
3633 		PoolVector<uint8_t>::Write w = array.write();
3634 		PoolVector<uint8_t>::Read r = p_array.read();
3635 
3636 		uint16_t *w16 = (uint16_t *)w.ptr();
3637 		const uint16_t *r16 = (uint16_t *)r.ptr();
3638 
3639 		uint16_t one = Math::make_half_float(1);
3640 
3641 		for (int i = 0; i < p_vertex_count; i++) {
3642 
3643 			*w16++ = *r16++;
3644 			*w16++ = *r16++;
3645 			*w16++ = *r16++;
3646 			*w16++ = one;
3647 			for (int j = 0; j < (stride / 2) - 4; j++) {
3648 				*w16++ = *r16++;
3649 			}
3650 		}
3651 	}
3652 
3653 	ERR_FAIL_COND(array.size() != array_size);
3654 
3655 	if (p_format & VS::ARRAY_FORMAT_INDEX) {
3656 
3657 		index_array_size = attribs[VS::ARRAY_INDEX].stride * p_index_count;
3658 	}
3659 
3660 	ERR_FAIL_COND(p_index_array.size() != index_array_size);
3661 
3662 	ERR_FAIL_COND(p_blend_shapes.size() != mesh->blend_shape_count);
3663 
3664 	for (int i = 0; i < p_blend_shapes.size(); i++) {
3665 		ERR_FAIL_COND(p_blend_shapes[i].size() != array_size);
3666 	}
3667 
3668 	//ok all valid, create stuff
3669 
3670 	Surface *surface = memnew(Surface);
3671 
3672 	surface->active = true;
3673 	surface->array_len = p_vertex_count;
3674 	surface->index_array_len = p_index_count;
3675 	surface->array_byte_size = array.size();
3676 	surface->index_array_byte_size = p_index_array.size();
3677 	surface->primitive = p_primitive;
3678 	surface->mesh = mesh;
3679 	surface->format = p_format;
3680 	surface->skeleton_bone_aabb = p_bone_aabbs;
3681 	surface->skeleton_bone_used.resize(surface->skeleton_bone_aabb.size());
3682 	surface->aabb = p_aabb;
3683 	surface->max_bone = p_bone_aabbs.size();
3684 	surface->total_data_size += surface->array_byte_size + surface->index_array_byte_size;
3685 
3686 	for (int i = 0; i < surface->skeleton_bone_used.size(); i++) {
3687 		if (surface->skeleton_bone_aabb[i].size.x < 0 || surface->skeleton_bone_aabb[i].size.y < 0 || surface->skeleton_bone_aabb[i].size.z < 0) {
3688 			surface->skeleton_bone_used.write[i] = false;
3689 		} else {
3690 			surface->skeleton_bone_used.write[i] = true;
3691 		}
3692 	}
3693 
3694 	for (int i = 0; i < VS::ARRAY_MAX; i++) {
3695 		surface->attribs[i] = attribs[i];
3696 	}
3697 
3698 	{
3699 
3700 		PoolVector<uint8_t>::Read vr = array.read();
3701 
3702 		glGenBuffers(1, &surface->vertex_id);
3703 		glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
3704 		glBufferData(GL_ARRAY_BUFFER, array_size, vr.ptr(), (p_format & VS::ARRAY_FLAG_USE_DYNAMIC_UPDATE) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
3705 		glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
3706 
3707 		if (p_format & VS::ARRAY_FORMAT_INDEX) {
3708 
3709 			PoolVector<uint8_t>::Read ir = p_index_array.read();
3710 
3711 			glGenBuffers(1, &surface->index_id);
3712 			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id);
3713 			glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_array_size, ir.ptr(), GL_STATIC_DRAW);
3714 			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
3715 		}
3716 
3717 		//generate arrays for faster state switching
3718 
3719 		for (int ai = 0; ai < 2; ai++) {
3720 
3721 			if (ai == 0) {
3722 				//for normal draw
3723 				glGenVertexArrays(1, &surface->array_id);
3724 				glBindVertexArray(surface->array_id);
3725 				glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
3726 			} else if (ai == 1) {
3727 				//for instancing draw (can be changed and no one cares)
3728 				glGenVertexArrays(1, &surface->instancing_array_id);
3729 				glBindVertexArray(surface->instancing_array_id);
3730 				glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
3731 			}
3732 
3733 			for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
3734 
3735 				if (!attribs[i].enabled)
3736 					continue;
3737 
3738 				if (attribs[i].integer) {
3739 					glVertexAttribIPointer(attribs[i].index, attribs[i].size, attribs[i].type, attribs[i].stride, CAST_INT_TO_UCHAR_PTR(attribs[i].offset));
3740 				} else {
3741 					glVertexAttribPointer(attribs[i].index, attribs[i].size, attribs[i].type, attribs[i].normalized, attribs[i].stride, CAST_INT_TO_UCHAR_PTR(attribs[i].offset));
3742 				}
3743 				glEnableVertexAttribArray(attribs[i].index);
3744 			}
3745 
3746 			if (surface->index_id) {
3747 				glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id);
3748 			}
3749 
3750 			glBindVertexArray(0);
3751 			glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
3752 			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
3753 		}
3754 
3755 #ifdef DEBUG_ENABLED
3756 
3757 		if (config.generate_wireframes && p_primitive == VS::PRIMITIVE_TRIANGLES) {
3758 			//generate wireframes, this is used mostly by editor
3759 			PoolVector<uint32_t> wf_indices;
3760 			int index_count;
3761 
3762 			if (p_format & VS::ARRAY_FORMAT_INDEX) {
3763 
3764 				index_count = p_index_count * 2;
3765 				wf_indices.resize(index_count);
3766 
3767 				PoolVector<uint8_t>::Read ir = p_index_array.read();
3768 				PoolVector<uint32_t>::Write wr = wf_indices.write();
3769 
3770 				if (p_vertex_count < (1 << 16)) {
3771 					//read 16 bit indices
3772 					const uint16_t *src_idx = (const uint16_t *)ir.ptr();
3773 					for (int i = 0; i + 5 < index_count; i += 6) {
3774 
3775 						wr[i + 0] = src_idx[i / 2];
3776 						wr[i + 1] = src_idx[i / 2 + 1];
3777 						wr[i + 2] = src_idx[i / 2 + 1];
3778 						wr[i + 3] = src_idx[i / 2 + 2];
3779 						wr[i + 4] = src_idx[i / 2 + 2];
3780 						wr[i + 5] = src_idx[i / 2];
3781 					}
3782 
3783 				} else {
3784 
3785 					//read 16 bit indices
3786 					const uint32_t *src_idx = (const uint32_t *)ir.ptr();
3787 					for (int i = 0; i + 5 < index_count; i += 6) {
3788 
3789 						wr[i + 0] = src_idx[i / 2];
3790 						wr[i + 1] = src_idx[i / 2 + 1];
3791 						wr[i + 2] = src_idx[i / 2 + 1];
3792 						wr[i + 3] = src_idx[i / 2 + 2];
3793 						wr[i + 4] = src_idx[i / 2 + 2];
3794 						wr[i + 5] = src_idx[i / 2];
3795 					}
3796 				}
3797 
3798 			} else {
3799 
3800 				index_count = p_vertex_count * 2;
3801 				wf_indices.resize(index_count);
3802 				PoolVector<uint32_t>::Write wr = wf_indices.write();
3803 				for (int i = 0; i + 5 < index_count; i += 6) {
3804 
3805 					wr[i + 0] = i / 2;
3806 					wr[i + 1] = i / 2 + 1;
3807 					wr[i + 2] = i / 2 + 1;
3808 					wr[i + 3] = i / 2 + 2;
3809 					wr[i + 4] = i / 2 + 2;
3810 					wr[i + 5] = i / 2;
3811 				}
3812 			}
3813 			{
3814 				PoolVector<uint32_t>::Read ir = wf_indices.read();
3815 
3816 				glGenBuffers(1, &surface->index_wireframe_id);
3817 				glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_wireframe_id);
3818 				glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_count * sizeof(uint32_t), ir.ptr(), GL_STATIC_DRAW);
3819 				glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
3820 
3821 				surface->index_wireframe_len = index_count;
3822 			}
3823 
3824 			for (int ai = 0; ai < 2; ai++) {
3825 
3826 				if (ai == 0) {
3827 					//for normal draw
3828 					glGenVertexArrays(1, &surface->array_wireframe_id);
3829 					glBindVertexArray(surface->array_wireframe_id);
3830 					glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
3831 				} else if (ai == 1) {
3832 					//for instancing draw (can be changed and no one cares)
3833 					glGenVertexArrays(1, &surface->instancing_array_wireframe_id);
3834 					glBindVertexArray(surface->instancing_array_wireframe_id);
3835 					glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
3836 				}
3837 
3838 				for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
3839 
3840 					if (!attribs[i].enabled)
3841 						continue;
3842 
3843 					if (attribs[i].integer) {
3844 						glVertexAttribIPointer(attribs[i].index, attribs[i].size, attribs[i].type, attribs[i].stride, CAST_INT_TO_UCHAR_PTR(attribs[i].offset));
3845 					} else {
3846 						glVertexAttribPointer(attribs[i].index, attribs[i].size, attribs[i].type, attribs[i].normalized, attribs[i].stride, CAST_INT_TO_UCHAR_PTR(attribs[i].offset));
3847 					}
3848 					glEnableVertexAttribArray(attribs[i].index);
3849 				}
3850 
3851 				glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_wireframe_id);
3852 
3853 				glBindVertexArray(0);
3854 				glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
3855 				glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
3856 			}
3857 		}
3858 
3859 #endif
3860 	}
3861 
3862 	{
3863 
3864 		//blend shapes
3865 
3866 		for (int i = 0; i < p_blend_shapes.size(); i++) {
3867 
3868 			Surface::BlendShape mt;
3869 
3870 			PoolVector<uint8_t>::Read vr = p_blend_shapes[i].read();
3871 
3872 			surface->total_data_size += array_size;
3873 
3874 			glGenBuffers(1, &mt.vertex_id);
3875 			glBindBuffer(GL_ARRAY_BUFFER, mt.vertex_id);
3876 			glBufferData(GL_ARRAY_BUFFER, array_size, vr.ptr(), GL_STATIC_DRAW);
3877 			glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
3878 
3879 			glGenVertexArrays(1, &mt.array_id);
3880 			glBindVertexArray(mt.array_id);
3881 			glBindBuffer(GL_ARRAY_BUFFER, mt.vertex_id);
3882 
3883 			for (int j = 0; j < VS::ARRAY_MAX - 1; j++) {
3884 
3885 				if (!attribs[j].enabled)
3886 					continue;
3887 
3888 				if (attribs[j].integer) {
3889 					glVertexAttribIPointer(attribs[j].index, attribs[j].size, attribs[j].type, attribs[j].stride, CAST_INT_TO_UCHAR_PTR(attribs[j].offset));
3890 				} else {
3891 					glVertexAttribPointer(attribs[j].index, attribs[j].size, attribs[j].type, attribs[j].normalized, attribs[j].stride, CAST_INT_TO_UCHAR_PTR(attribs[j].offset));
3892 				}
3893 				glEnableVertexAttribArray(attribs[j].index);
3894 			}
3895 
3896 			glBindVertexArray(0);
3897 			glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
3898 
3899 			surface->blend_shapes.push_back(mt);
3900 		}
3901 	}
3902 
3903 	mesh->surfaces.push_back(surface);
3904 	mesh->instance_change_notify(true, true);
3905 
3906 	info.vertex_mem += surface->total_data_size;
3907 }
3908 
3909 void RasterizerStorageGLES3::mesh_set_blend_shape_count(RID p_mesh, int p_amount) {
3910 
3911 	Mesh *mesh = mesh_owner.getornull(p_mesh);
3912 	ERR_FAIL_COND(!mesh);
3913 
3914 	ERR_FAIL_COND(mesh->surfaces.size() != 0);
3915 	ERR_FAIL_COND(p_amount < 0);
3916 
3917 	mesh->blend_shape_count = p_amount;
3918 	mesh->instance_change_notify(true, false);
3919 }
3920 int RasterizerStorageGLES3::mesh_get_blend_shape_count(RID p_mesh) const {
3921 
3922 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
3923 	ERR_FAIL_COND_V(!mesh, 0);
3924 
3925 	return mesh->blend_shape_count;
3926 }
3927 
3928 void RasterizerStorageGLES3::mesh_set_blend_shape_mode(RID p_mesh, VS::BlendShapeMode p_mode) {
3929 
3930 	Mesh *mesh = mesh_owner.getornull(p_mesh);
3931 	ERR_FAIL_COND(!mesh);
3932 
3933 	mesh->blend_shape_mode = p_mode;
3934 }
3935 VS::BlendShapeMode RasterizerStorageGLES3::mesh_get_blend_shape_mode(RID p_mesh) const {
3936 
3937 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
3938 	ERR_FAIL_COND_V(!mesh, VS::BLEND_SHAPE_MODE_NORMALIZED);
3939 
3940 	return mesh->blend_shape_mode;
3941 }
3942 
3943 void RasterizerStorageGLES3::mesh_surface_update_region(RID p_mesh, int p_surface, int p_offset, const PoolVector<uint8_t> &p_data) {
3944 
3945 	Mesh *mesh = mesh_owner.getornull(p_mesh);
3946 	ERR_FAIL_COND(!mesh);
3947 	ERR_FAIL_INDEX(p_surface, mesh->surfaces.size());
3948 
3949 	int total_size = p_data.size();
3950 	ERR_FAIL_COND(p_offset + total_size > mesh->surfaces[p_surface]->array_byte_size);
3951 
3952 	PoolVector<uint8_t>::Read r = p_data.read();
3953 
3954 	glBindBuffer(GL_ARRAY_BUFFER, mesh->surfaces[p_surface]->vertex_id);
3955 	glBufferSubData(GL_ARRAY_BUFFER, p_offset, total_size, r.ptr());
3956 	glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
3957 }
3958 
3959 void RasterizerStorageGLES3::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) {
3960 
3961 	Mesh *mesh = mesh_owner.getornull(p_mesh);
3962 	ERR_FAIL_COND(!mesh);
3963 	ERR_FAIL_INDEX(p_surface, mesh->surfaces.size());
3964 
3965 	if (mesh->surfaces[p_surface]->material == p_material)
3966 		return;
3967 
3968 	if (mesh->surfaces[p_surface]->material.is_valid()) {
3969 		_material_remove_geometry(mesh->surfaces[p_surface]->material, mesh->surfaces[p_surface]);
3970 	}
3971 
3972 	mesh->surfaces[p_surface]->material = p_material;
3973 
3974 	if (mesh->surfaces[p_surface]->material.is_valid()) {
3975 		_material_add_geometry(mesh->surfaces[p_surface]->material, mesh->surfaces[p_surface]);
3976 	}
3977 
3978 	mesh->instance_change_notify(false, true);
3979 }
3980 RID RasterizerStorageGLES3::mesh_surface_get_material(RID p_mesh, int p_surface) const {
3981 
3982 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
3983 	ERR_FAIL_COND_V(!mesh, RID());
3984 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), RID());
3985 
3986 	return mesh->surfaces[p_surface]->material;
3987 }
3988 
3989 int RasterizerStorageGLES3::mesh_surface_get_array_len(RID p_mesh, int p_surface) const {
3990 
3991 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
3992 	ERR_FAIL_COND_V(!mesh, 0);
3993 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0);
3994 
3995 	return mesh->surfaces[p_surface]->array_len;
3996 }
3997 int RasterizerStorageGLES3::mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const {
3998 
3999 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4000 	ERR_FAIL_COND_V(!mesh, 0);
4001 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0);
4002 
4003 	return mesh->surfaces[p_surface]->index_array_len;
4004 }
4005 
4006 PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_array(RID p_mesh, int p_surface) const {
4007 
4008 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4009 	ERR_FAIL_COND_V(!mesh, PoolVector<uint8_t>());
4010 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), PoolVector<uint8_t>());
4011 
4012 	Surface *surface = mesh->surfaces[p_surface];
4013 
4014 	PoolVector<uint8_t> ret;
4015 	ret.resize(surface->array_byte_size);
4016 	glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
4017 
4018 #if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__)
4019 	{
4020 		PoolVector<uint8_t>::Write w = ret.write();
4021 		glGetBufferSubData(GL_ARRAY_BUFFER, 0, surface->array_byte_size, w.ptr());
4022 	}
4023 #else
4024 	void *data = glMapBufferRange(GL_ARRAY_BUFFER, 0, surface->array_byte_size, GL_MAP_READ_BIT);
4025 	ERR_FAIL_NULL_V(data, PoolVector<uint8_t>());
4026 	{
4027 		PoolVector<uint8_t>::Write w = ret.write();
4028 		copymem(w.ptr(), data, surface->array_byte_size);
4029 	}
4030 	glUnmapBuffer(GL_ARRAY_BUFFER);
4031 #endif
4032 
4033 	glBindBuffer(GL_ARRAY_BUFFER, 0);
4034 	return ret;
4035 }
4036 
4037 PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_index_array(RID p_mesh, int p_surface) const {
4038 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4039 	ERR_FAIL_COND_V(!mesh, PoolVector<uint8_t>());
4040 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), PoolVector<uint8_t>());
4041 
4042 	Surface *surface = mesh->surfaces[p_surface];
4043 
4044 	PoolVector<uint8_t> ret;
4045 	ret.resize(surface->index_array_byte_size);
4046 
4047 	if (surface->index_array_byte_size > 0) {
4048 		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id);
4049 
4050 #if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__)
4051 		{
4052 			PoolVector<uint8_t>::Write w = ret.write();
4053 			glGetBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, surface->index_array_byte_size, w.ptr());
4054 		}
4055 #else
4056 		void *data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, surface->index_array_byte_size, GL_MAP_READ_BIT);
4057 		ERR_FAIL_NULL_V(data, PoolVector<uint8_t>());
4058 		{
4059 			PoolVector<uint8_t>::Write w = ret.write();
4060 			copymem(w.ptr(), data, surface->index_array_byte_size);
4061 		}
4062 		glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
4063 #endif
4064 
4065 		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
4066 	}
4067 
4068 	return ret;
4069 }
4070 
4071 uint32_t RasterizerStorageGLES3::mesh_surface_get_format(RID p_mesh, int p_surface) const {
4072 
4073 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4074 
4075 	ERR_FAIL_COND_V(!mesh, 0);
4076 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0);
4077 
4078 	return mesh->surfaces[p_surface]->format;
4079 }
4080 
4081 VS::PrimitiveType RasterizerStorageGLES3::mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const {
4082 
4083 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4084 	ERR_FAIL_COND_V(!mesh, VS::PRIMITIVE_MAX);
4085 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), VS::PRIMITIVE_MAX);
4086 
4087 	return mesh->surfaces[p_surface]->primitive;
4088 }
4089 
4090 AABB RasterizerStorageGLES3::mesh_surface_get_aabb(RID p_mesh, int p_surface) const {
4091 
4092 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4093 	ERR_FAIL_COND_V(!mesh, AABB());
4094 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), AABB());
4095 
4096 	return mesh->surfaces[p_surface]->aabb;
4097 }
4098 Vector<PoolVector<uint8_t> > RasterizerStorageGLES3::mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const {
4099 
4100 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4101 	ERR_FAIL_COND_V(!mesh, Vector<PoolVector<uint8_t> >());
4102 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), Vector<PoolVector<uint8_t> >());
4103 
4104 	Vector<PoolVector<uint8_t> > bsarr;
4105 
4106 	for (int i = 0; i < mesh->surfaces[p_surface]->blend_shapes.size(); i++) {
4107 
4108 		PoolVector<uint8_t> ret;
4109 		ret.resize(mesh->surfaces[p_surface]->array_byte_size);
4110 		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->surfaces[p_surface]->blend_shapes[i].vertex_id);
4111 
4112 #if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__)
4113 		{
4114 			PoolVector<uint8_t>::Write w = ret.write();
4115 			glGetBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, mesh->surfaces[p_surface]->array_byte_size, w.ptr());
4116 		}
4117 #else
4118 		void *data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, mesh->surfaces[p_surface]->array_byte_size, GL_MAP_READ_BIT);
4119 		ERR_FAIL_COND_V(!data, Vector<PoolVector<uint8_t> >());
4120 		{
4121 			PoolVector<uint8_t>::Write w = ret.write();
4122 			copymem(w.ptr(), data, mesh->surfaces[p_surface]->array_byte_size);
4123 		}
4124 		glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
4125 #endif
4126 
4127 		bsarr.push_back(ret);
4128 	}
4129 
4130 	return bsarr;
4131 }
4132 
4133 Vector<AABB> RasterizerStorageGLES3::mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const {
4134 
4135 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4136 	ERR_FAIL_COND_V(!mesh, Vector<AABB>());
4137 	ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), Vector<AABB>());
4138 
4139 	return mesh->surfaces[p_surface]->skeleton_bone_aabb;
4140 }
4141 
4142 void RasterizerStorageGLES3::mesh_remove_surface(RID p_mesh, int p_surface) {
4143 
4144 	Mesh *mesh = mesh_owner.getornull(p_mesh);
4145 	ERR_FAIL_COND(!mesh);
4146 	ERR_FAIL_INDEX(p_surface, mesh->surfaces.size());
4147 
4148 	Surface *surface = mesh->surfaces[p_surface];
4149 
4150 	if (surface->material.is_valid()) {
4151 		_material_remove_geometry(surface->material, mesh->surfaces[p_surface]);
4152 	}
4153 
4154 	glDeleteBuffers(1, &surface->vertex_id);
4155 	if (surface->index_id) {
4156 		glDeleteBuffers(1, &surface->index_id);
4157 	}
4158 
4159 	glDeleteVertexArrays(1, &surface->array_id);
4160 	glDeleteVertexArrays(1, &surface->instancing_array_id);
4161 
4162 	for (int i = 0; i < surface->blend_shapes.size(); i++) {
4163 
4164 		glDeleteBuffers(1, &surface->blend_shapes[i].vertex_id);
4165 		glDeleteVertexArrays(1, &surface->blend_shapes[i].array_id);
4166 	}
4167 
4168 	if (surface->index_wireframe_id) {
4169 		glDeleteBuffers(1, &surface->index_wireframe_id);
4170 		glDeleteVertexArrays(1, &surface->array_wireframe_id);
4171 		glDeleteVertexArrays(1, &surface->instancing_array_wireframe_id);
4172 	}
4173 
4174 	info.vertex_mem -= surface->total_data_size;
4175 
4176 	memdelete(surface);
4177 
4178 	mesh->surfaces.remove(p_surface);
4179 
4180 	mesh->instance_change_notify(true, true);
4181 }
4182 
4183 int RasterizerStorageGLES3::mesh_get_surface_count(RID p_mesh) const {
4184 
4185 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4186 	ERR_FAIL_COND_V(!mesh, 0);
4187 	return mesh->surfaces.size();
4188 }
4189 
4190 void RasterizerStorageGLES3::mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) {
4191 
4192 	Mesh *mesh = mesh_owner.getornull(p_mesh);
4193 	ERR_FAIL_COND(!mesh);
4194 
4195 	mesh->custom_aabb = p_aabb;
4196 	mesh->instance_change_notify(true, false);
4197 }
4198 
4199 AABB RasterizerStorageGLES3::mesh_get_custom_aabb(RID p_mesh) const {
4200 
4201 	const Mesh *mesh = mesh_owner.getornull(p_mesh);
4202 	ERR_FAIL_COND_V(!mesh, AABB());
4203 
4204 	return mesh->custom_aabb;
4205 }
4206 
4207 AABB RasterizerStorageGLES3::mesh_get_aabb(RID p_mesh, RID p_skeleton) const {
4208 
4209 	Mesh *mesh = mesh_owner.get(p_mesh);
4210 	ERR_FAIL_COND_V(!mesh, AABB());
4211 
4212 	if (mesh->custom_aabb != AABB()) {
4213 		return mesh->custom_aabb;
4214 	}
4215 
4216 	Skeleton *sk = NULL;
4217 	if (p_skeleton.is_valid()) {
4218 		sk = skeleton_owner.get(p_skeleton);
4219 	}
4220 
4221 	AABB aabb;
4222 
4223 	if (sk && sk->size != 0) {
4224 
4225 		for (int i = 0; i < mesh->surfaces.size(); i++) {
4226 
4227 			AABB laabb;
4228 			if ((mesh->surfaces[i]->format & VS::ARRAY_FORMAT_BONES) && mesh->surfaces[i]->skeleton_bone_aabb.size()) {
4229 
4230 				int bs = mesh->surfaces[i]->skeleton_bone_aabb.size();
4231 				const AABB *skbones = mesh->surfaces[i]->skeleton_bone_aabb.ptr();
4232 				const bool *skused = mesh->surfaces[i]->skeleton_bone_used.ptr();
4233 
4234 				int sbs = sk->size;
4235 				ERR_CONTINUE(bs > sbs);
4236 				const float *texture = sk->skel_texture.ptr();
4237 
4238 				bool first = true;
4239 				if (sk->use_2d) {
4240 					for (int j = 0; j < bs; j++) {
4241 
4242 						if (!skused[j])
4243 							continue;
4244 
4245 						int base_ofs = ((j / 256) * 256) * 2 * 4 + (j % 256) * 4;
4246 
4247 						Transform mtx;
4248 
4249 						mtx.basis[0].x = texture[base_ofs + 0];
4250 						mtx.basis[0].y = texture[base_ofs + 1];
4251 						mtx.origin.x = texture[base_ofs + 3];
4252 						base_ofs += 256 * 4;
4253 						mtx.basis[1].x = texture[base_ofs + 0];
4254 						mtx.basis[1].y = texture[base_ofs + 1];
4255 						mtx.origin.y = texture[base_ofs + 3];
4256 
4257 						AABB baabb = mtx.xform(skbones[j]);
4258 
4259 						if (first) {
4260 							laabb = baabb;
4261 							first = false;
4262 						} else {
4263 							laabb.merge_with(baabb);
4264 						}
4265 					}
4266 				} else {
4267 					for (int j = 0; j < bs; j++) {
4268 
4269 						if (!skused[j])
4270 							continue;
4271 
4272 						int base_ofs = ((j / 256) * 256) * 3 * 4 + (j % 256) * 4;
4273 
4274 						Transform mtx;
4275 
4276 						mtx.basis[0].x = texture[base_ofs + 0];
4277 						mtx.basis[0].y = texture[base_ofs + 1];
4278 						mtx.basis[0].z = texture[base_ofs + 2];
4279 						mtx.origin.x = texture[base_ofs + 3];
4280 						base_ofs += 256 * 4;
4281 						mtx.basis[1].x = texture[base_ofs + 0];
4282 						mtx.basis[1].y = texture[base_ofs + 1];
4283 						mtx.basis[1].z = texture[base_ofs + 2];
4284 						mtx.origin.y = texture[base_ofs + 3];
4285 						base_ofs += 256 * 4;
4286 						mtx.basis[2].x = texture[base_ofs + 0];
4287 						mtx.basis[2].y = texture[base_ofs + 1];
4288 						mtx.basis[2].z = texture[base_ofs + 2];
4289 						mtx.origin.z = texture[base_ofs + 3];
4290 
4291 						AABB baabb = mtx.xform(skbones[j]);
4292 						if (first) {
4293 							laabb = baabb;
4294 							first = false;
4295 						} else {
4296 							laabb.merge_with(baabb);
4297 						}
4298 					}
4299 				}
4300 
4301 			} else {
4302 
4303 				laabb = mesh->surfaces[i]->aabb;
4304 			}
4305 
4306 			if (i == 0)
4307 				aabb = laabb;
4308 			else
4309 				aabb.merge_with(laabb);
4310 		}
4311 	} else {
4312 
4313 		for (int i = 0; i < mesh->surfaces.size(); i++) {
4314 
4315 			if (i == 0)
4316 				aabb = mesh->surfaces[i]->aabb;
4317 			else
4318 				aabb.merge_with(mesh->surfaces[i]->aabb);
4319 		}
4320 	}
4321 
4322 	return aabb;
4323 }
4324 void RasterizerStorageGLES3::mesh_clear(RID p_mesh) {
4325 
4326 	Mesh *mesh = mesh_owner.getornull(p_mesh);
4327 	ERR_FAIL_COND(!mesh);
4328 
4329 	while (mesh->surfaces.size()) {
4330 		mesh_remove_surface(p_mesh, 0);
4331 	}
4332 }
4333 
4334 void RasterizerStorageGLES3::mesh_render_blend_shapes(Surface *s, const float *p_weights) {
4335 
4336 	glBindVertexArray(s->array_id);
4337 
4338 	BlendShapeShaderGLES3::Conditionals cond[VS::ARRAY_MAX - 1] = {
4339 		BlendShapeShaderGLES3::ENABLE_NORMAL, //will be ignored
4340 		BlendShapeShaderGLES3::ENABLE_NORMAL,
4341 		BlendShapeShaderGLES3::ENABLE_TANGENT,
4342 		BlendShapeShaderGLES3::ENABLE_COLOR,
4343 		BlendShapeShaderGLES3::ENABLE_UV,
4344 		BlendShapeShaderGLES3::ENABLE_UV2,
4345 		BlendShapeShaderGLES3::ENABLE_SKELETON,
4346 		BlendShapeShaderGLES3::ENABLE_SKELETON,
4347 	};
4348 
4349 	int stride = 0;
4350 
4351 	if (s->format & VS::ARRAY_FLAG_USE_2D_VERTICES) {
4352 		stride = 2 * 4;
4353 	} else {
4354 		stride = 3 * 4;
4355 	}
4356 
4357 	static const int sizes[VS::ARRAY_MAX - 1] = {
4358 		3 * 4,
4359 		3 * 4,
4360 		4 * 4,
4361 		4 * 4,
4362 		2 * 4,
4363 		2 * 4,
4364 		4 * 4,
4365 		4 * 4
4366 	};
4367 
4368 	for (int i = 1; i < VS::ARRAY_MAX - 1; i++) {
4369 		shaders.blend_shapes.set_conditional(cond[i], s->format & (1 << i)); //enable conditional for format
4370 		if (s->format & (1 << i)) {
4371 			stride += sizes[i];
4372 		}
4373 	}
4374 
4375 	//copy all first
4376 	float base_weight = 1.0;
4377 
4378 	int mtc = s->blend_shapes.size();
4379 
4380 	if (s->mesh->blend_shape_mode == VS::BLEND_SHAPE_MODE_NORMALIZED) {
4381 
4382 		for (int i = 0; i < mtc; i++) {
4383 			base_weight -= p_weights[i];
4384 		}
4385 	}
4386 
4387 	shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::ENABLE_BLEND, false); //first pass does not blend
4388 	shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::USE_2D_VERTEX, s->format & VS::ARRAY_FLAG_USE_2D_VERTICES); //use 2D vertices if needed
4389 
4390 	shaders.blend_shapes.bind();
4391 
4392 	shaders.blend_shapes.set_uniform(BlendShapeShaderGLES3::BLEND_AMOUNT, base_weight);
4393 	glEnable(GL_RASTERIZER_DISCARD);
4394 
4395 	glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, resources.transform_feedback_buffers[0]);
4396 	glBeginTransformFeedback(GL_POINTS);
4397 	glDrawArrays(GL_POINTS, 0, s->array_len);
4398 	glEndTransformFeedback();
4399 
4400 	shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::ENABLE_BLEND, true); //first pass does not blend
4401 	shaders.blend_shapes.bind();
4402 
4403 	for (int ti = 0; ti < mtc; ti++) {
4404 		float weight = p_weights[ti];
4405 
4406 		if (weight < 0.00001) //not bother with this one
4407 			continue;
4408 
4409 		glBindVertexArray(s->blend_shapes[ti].array_id);
4410 		glBindBuffer(GL_ARRAY_BUFFER, resources.transform_feedback_buffers[0]);
4411 		glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, resources.transform_feedback_buffers[1]);
4412 
4413 		shaders.blend_shapes.set_uniform(BlendShapeShaderGLES3::BLEND_AMOUNT, weight);
4414 
4415 		int ofs = 0;
4416 		for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
4417 
4418 			if (s->format & (1 << i)) {
4419 				glEnableVertexAttribArray(i + 8);
4420 				switch (i) {
4421 
4422 					case VS::ARRAY_VERTEX: {
4423 						if (s->format & VS::ARRAY_FLAG_USE_2D_VERTICES) {
4424 							glVertexAttribPointer(i + 8, 2, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4425 							ofs += 2 * 4;
4426 						} else {
4427 							glVertexAttribPointer(i + 8, 3, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4428 							ofs += 3 * 4;
4429 						}
4430 					} break;
4431 					case VS::ARRAY_NORMAL: {
4432 						glVertexAttribPointer(i + 8, 3, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4433 						ofs += 3 * 4;
4434 					} break;
4435 					case VS::ARRAY_TANGENT: {
4436 						glVertexAttribPointer(i + 8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4437 						ofs += 4 * 4;
4438 
4439 					} break;
4440 					case VS::ARRAY_COLOR: {
4441 						glVertexAttribPointer(i + 8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4442 						ofs += 4 * 4;
4443 
4444 					} break;
4445 					case VS::ARRAY_TEX_UV: {
4446 						glVertexAttribPointer(i + 8, 2, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4447 						ofs += 2 * 4;
4448 
4449 					} break;
4450 					case VS::ARRAY_TEX_UV2: {
4451 						glVertexAttribPointer(i + 8, 2, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4452 						ofs += 2 * 4;
4453 
4454 					} break;
4455 					case VS::ARRAY_BONES: {
4456 						glVertexAttribIPointer(i + 8, 4, GL_UNSIGNED_INT, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4457 						ofs += 4 * 4;
4458 
4459 					} break;
4460 					case VS::ARRAY_WEIGHTS: {
4461 						glVertexAttribPointer(i + 8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4462 						ofs += 4 * 4;
4463 
4464 					} break;
4465 				}
4466 
4467 			} else {
4468 				glDisableVertexAttribArray(i + 8);
4469 			}
4470 		}
4471 
4472 		glBeginTransformFeedback(GL_POINTS);
4473 		glDrawArrays(GL_POINTS, 0, s->array_len);
4474 		glEndTransformFeedback();
4475 
4476 		SWAP(resources.transform_feedback_buffers[0], resources.transform_feedback_buffers[1]);
4477 	}
4478 
4479 	glDisable(GL_RASTERIZER_DISCARD);
4480 	glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
4481 
4482 	glBindVertexArray(resources.transform_feedback_array);
4483 	glBindBuffer(GL_ARRAY_BUFFER, resources.transform_feedback_buffers[0]);
4484 
4485 	int ofs = 0;
4486 	for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
4487 
4488 		if (s->format & (1 << i)) {
4489 			glEnableVertexAttribArray(i);
4490 			switch (i) {
4491 
4492 				case VS::ARRAY_VERTEX: {
4493 					if (s->format & VS::ARRAY_FLAG_USE_2D_VERTICES) {
4494 						glVertexAttribPointer(i, 2, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4495 						ofs += 2 * 4;
4496 					} else {
4497 						glVertexAttribPointer(i, 3, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4498 						ofs += 3 * 4;
4499 					}
4500 				} break;
4501 				case VS::ARRAY_NORMAL: {
4502 					glVertexAttribPointer(i, 3, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4503 					ofs += 3 * 4;
4504 				} break;
4505 				case VS::ARRAY_TANGENT: {
4506 					glVertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4507 					ofs += 4 * 4;
4508 
4509 				} break;
4510 				case VS::ARRAY_COLOR: {
4511 					glVertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4512 					ofs += 4 * 4;
4513 
4514 				} break;
4515 				case VS::ARRAY_TEX_UV: {
4516 					glVertexAttribPointer(i, 2, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4517 					ofs += 2 * 4;
4518 
4519 				} break;
4520 				case VS::ARRAY_TEX_UV2: {
4521 					glVertexAttribPointer(i, 2, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4522 					ofs += 2 * 4;
4523 
4524 				} break;
4525 				case VS::ARRAY_BONES: {
4526 					glVertexAttribIPointer(i, 4, GL_UNSIGNED_INT, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4527 					ofs += 4 * 4;
4528 
4529 				} break;
4530 				case VS::ARRAY_WEIGHTS: {
4531 					glVertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(ofs));
4532 					ofs += 4 * 4;
4533 
4534 				} break;
4535 			}
4536 
4537 		} else {
4538 			glDisableVertexAttribArray(i);
4539 		}
4540 	}
4541 
4542 	if (s->index_array_len) {
4543 		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id);
4544 	}
4545 }
4546 
4547 /* MULTIMESH API */
4548 
4549 RID RasterizerStorageGLES3::multimesh_create() {
4550 
4551 	MultiMesh *multimesh = memnew(MultiMesh);
4552 	return multimesh_owner.make_rid(multimesh);
4553 }
4554 
4555 void RasterizerStorageGLES3::multimesh_allocate(RID p_multimesh, int p_instances, VS::MultimeshTransformFormat p_transform_format, VS::MultimeshColorFormat p_color_format, VS::MultimeshCustomDataFormat p_data_format) {
4556 
4557 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4558 	ERR_FAIL_COND(!multimesh);
4559 
4560 	if (multimesh->size == p_instances && multimesh->transform_format == p_transform_format && multimesh->color_format == p_color_format && multimesh->custom_data_format == p_data_format)
4561 		return;
4562 
4563 	if (multimesh->buffer) {
4564 		glDeleteBuffers(1, &multimesh->buffer);
4565 		multimesh->data.resize(0);
4566 		multimesh->buffer = 0;
4567 	}
4568 
4569 	multimesh->size = p_instances;
4570 	multimesh->transform_format = p_transform_format;
4571 	multimesh->color_format = p_color_format;
4572 	multimesh->custom_data_format = p_data_format;
4573 
4574 	if (multimesh->size) {
4575 
4576 		if (multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D) {
4577 			multimesh->xform_floats = 8;
4578 		} else {
4579 			multimesh->xform_floats = 12;
4580 		}
4581 
4582 		if (multimesh->color_format == VS::MULTIMESH_COLOR_8BIT) {
4583 			multimesh->color_floats = 1;
4584 		} else if (multimesh->color_format == VS::MULTIMESH_COLOR_FLOAT) {
4585 			multimesh->color_floats = 4;
4586 		} else {
4587 			multimesh->color_floats = 0;
4588 		}
4589 
4590 		if (multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_8BIT) {
4591 			multimesh->custom_data_floats = 1;
4592 		} else if (multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_FLOAT) {
4593 			multimesh->custom_data_floats = 4;
4594 		} else {
4595 			multimesh->custom_data_floats = 0;
4596 		}
4597 
4598 		int format_floats = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
4599 
4600 		multimesh->data.resize(format_floats * p_instances);
4601 
4602 		float *dataptr = multimesh->data.ptrw();
4603 
4604 		for (int i = 0; i < p_instances * format_floats; i += format_floats) {
4605 
4606 			int color_from = 0;
4607 			int custom_data_from = 0;
4608 
4609 			if (multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D) {
4610 				dataptr[i + 0] = 1.0;
4611 				dataptr[i + 1] = 0.0;
4612 				dataptr[i + 2] = 0.0;
4613 				dataptr[i + 3] = 0.0;
4614 				dataptr[i + 4] = 0.0;
4615 				dataptr[i + 5] = 1.0;
4616 				dataptr[i + 6] = 0.0;
4617 				dataptr[i + 7] = 0.0;
4618 				color_from = 8;
4619 				custom_data_from = 8;
4620 			} else {
4621 				dataptr[i + 0] = 1.0;
4622 				dataptr[i + 1] = 0.0;
4623 				dataptr[i + 2] = 0.0;
4624 				dataptr[i + 3] = 0.0;
4625 				dataptr[i + 4] = 0.0;
4626 				dataptr[i + 5] = 1.0;
4627 				dataptr[i + 6] = 0.0;
4628 				dataptr[i + 7] = 0.0;
4629 				dataptr[i + 8] = 0.0;
4630 				dataptr[i + 9] = 0.0;
4631 				dataptr[i + 10] = 1.0;
4632 				dataptr[i + 11] = 0.0;
4633 				color_from = 12;
4634 				custom_data_from = 12;
4635 			}
4636 
4637 			if (multimesh->color_format == VS::MULTIMESH_COLOR_NONE) {
4638 				//none
4639 			} else if (multimesh->color_format == VS::MULTIMESH_COLOR_8BIT) {
4640 
4641 				union {
4642 					uint32_t colu;
4643 					float colf;
4644 				} cu;
4645 
4646 				cu.colu = 0xFFFFFFFF;
4647 				dataptr[i + color_from + 0] = cu.colf;
4648 				custom_data_from = color_from + 1;
4649 
4650 			} else if (multimesh->color_format == VS::MULTIMESH_COLOR_FLOAT) {
4651 				dataptr[i + color_from + 0] = 1.0;
4652 				dataptr[i + color_from + 1] = 1.0;
4653 				dataptr[i + color_from + 2] = 1.0;
4654 				dataptr[i + color_from + 3] = 1.0;
4655 				custom_data_from = color_from + 4;
4656 			}
4657 
4658 			if (multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_NONE) {
4659 				//none
4660 			} else if (multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_8BIT) {
4661 
4662 				union {
4663 					uint32_t colu;
4664 					float colf;
4665 				} cu;
4666 
4667 				cu.colu = 0;
4668 				dataptr[i + custom_data_from + 0] = cu.colf;
4669 
4670 			} else if (multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_FLOAT) {
4671 				dataptr[i + custom_data_from + 0] = 0.0;
4672 				dataptr[i + custom_data_from + 1] = 0.0;
4673 				dataptr[i + custom_data_from + 2] = 0.0;
4674 				dataptr[i + custom_data_from + 3] = 0.0;
4675 			}
4676 		}
4677 
4678 		glGenBuffers(1, &multimesh->buffer);
4679 		glBindBuffer(GL_ARRAY_BUFFER, multimesh->buffer);
4680 		glBufferData(GL_ARRAY_BUFFER, multimesh->data.size() * sizeof(float), NULL, GL_STATIC_DRAW);
4681 		glBindBuffer(GL_ARRAY_BUFFER, 0);
4682 	}
4683 
4684 	multimesh->dirty_data = true;
4685 	multimesh->dirty_aabb = true;
4686 
4687 	if (!multimesh->update_list.in_list()) {
4688 		multimesh_update_list.add(&multimesh->update_list);
4689 	}
4690 }
4691 
4692 int RasterizerStorageGLES3::multimesh_get_instance_count(RID p_multimesh) const {
4693 
4694 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4695 	ERR_FAIL_COND_V(!multimesh, 0);
4696 
4697 	return multimesh->size;
4698 }
4699 
4700 void RasterizerStorageGLES3::multimesh_set_mesh(RID p_multimesh, RID p_mesh) {
4701 
4702 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4703 	ERR_FAIL_COND(!multimesh);
4704 
4705 	if (multimesh->mesh.is_valid()) {
4706 		Mesh *mesh = mesh_owner.getornull(multimesh->mesh);
4707 		if (mesh) {
4708 			mesh->multimeshes.remove(&multimesh->mesh_list);
4709 		}
4710 	}
4711 
4712 	multimesh->mesh = p_mesh;
4713 
4714 	if (multimesh->mesh.is_valid()) {
4715 		Mesh *mesh = mesh_owner.getornull(multimesh->mesh);
4716 		if (mesh) {
4717 			mesh->multimeshes.add(&multimesh->mesh_list);
4718 		}
4719 	}
4720 
4721 	multimesh->dirty_aabb = true;
4722 
4723 	if (!multimesh->update_list.in_list()) {
4724 		multimesh_update_list.add(&multimesh->update_list);
4725 	}
4726 }
4727 
4728 void RasterizerStorageGLES3::multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform) {
4729 
4730 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4731 	ERR_FAIL_COND(!multimesh);
4732 	ERR_FAIL_INDEX(p_index, multimesh->size);
4733 	ERR_FAIL_COND(multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D);
4734 
4735 	int stride = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
4736 	float *dataptr = &multimesh->data.write[stride * p_index];
4737 
4738 	dataptr[0] = p_transform.basis.elements[0][0];
4739 	dataptr[1] = p_transform.basis.elements[0][1];
4740 	dataptr[2] = p_transform.basis.elements[0][2];
4741 	dataptr[3] = p_transform.origin.x;
4742 	dataptr[4] = p_transform.basis.elements[1][0];
4743 	dataptr[5] = p_transform.basis.elements[1][1];
4744 	dataptr[6] = p_transform.basis.elements[1][2];
4745 	dataptr[7] = p_transform.origin.y;
4746 	dataptr[8] = p_transform.basis.elements[2][0];
4747 	dataptr[9] = p_transform.basis.elements[2][1];
4748 	dataptr[10] = p_transform.basis.elements[2][2];
4749 	dataptr[11] = p_transform.origin.z;
4750 
4751 	multimesh->dirty_data = true;
4752 	multimesh->dirty_aabb = true;
4753 
4754 	if (!multimesh->update_list.in_list()) {
4755 		multimesh_update_list.add(&multimesh->update_list);
4756 	}
4757 }
4758 
4759 void RasterizerStorageGLES3::multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) {
4760 
4761 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4762 	ERR_FAIL_COND(!multimesh);
4763 	ERR_FAIL_INDEX(p_index, multimesh->size);
4764 	ERR_FAIL_COND(multimesh->transform_format == VS::MULTIMESH_TRANSFORM_3D);
4765 
4766 	int stride = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
4767 	float *dataptr = &multimesh->data.write[stride * p_index];
4768 
4769 	dataptr[0] = p_transform.elements[0][0];
4770 	dataptr[1] = p_transform.elements[1][0];
4771 	dataptr[2] = 0;
4772 	dataptr[3] = p_transform.elements[2][0];
4773 	dataptr[4] = p_transform.elements[0][1];
4774 	dataptr[5] = p_transform.elements[1][1];
4775 	dataptr[6] = 0;
4776 	dataptr[7] = p_transform.elements[2][1];
4777 
4778 	multimesh->dirty_data = true;
4779 	multimesh->dirty_aabb = true;
4780 
4781 	if (!multimesh->update_list.in_list()) {
4782 		multimesh_update_list.add(&multimesh->update_list);
4783 	}
4784 }
4785 void RasterizerStorageGLES3::multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) {
4786 
4787 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4788 	ERR_FAIL_COND(!multimesh);
4789 	ERR_FAIL_INDEX(p_index, multimesh->size);
4790 	ERR_FAIL_COND(multimesh->color_format == VS::MULTIMESH_COLOR_NONE);
4791 	ERR_FAIL_INDEX(multimesh->color_format, VS::MULTIMESH_COLOR_MAX);
4792 
4793 	int stride = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
4794 	float *dataptr = &multimesh->data.write[stride * p_index + multimesh->xform_floats];
4795 
4796 	if (multimesh->color_format == VS::MULTIMESH_COLOR_8BIT) {
4797 
4798 		uint8_t *data8 = (uint8_t *)dataptr;
4799 		data8[0] = CLAMP(p_color.r * 255.0, 0, 255);
4800 		data8[1] = CLAMP(p_color.g * 255.0, 0, 255);
4801 		data8[2] = CLAMP(p_color.b * 255.0, 0, 255);
4802 		data8[3] = CLAMP(p_color.a * 255.0, 0, 255);
4803 
4804 	} else if (multimesh->color_format == VS::MULTIMESH_COLOR_FLOAT) {
4805 		dataptr[0] = p_color.r;
4806 		dataptr[1] = p_color.g;
4807 		dataptr[2] = p_color.b;
4808 		dataptr[3] = p_color.a;
4809 	}
4810 
4811 	multimesh->dirty_data = true;
4812 	multimesh->dirty_aabb = true;
4813 
4814 	if (!multimesh->update_list.in_list()) {
4815 		multimesh_update_list.add(&multimesh->update_list);
4816 	}
4817 }
4818 
4819 void RasterizerStorageGLES3::multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_custom_data) {
4820 
4821 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4822 	ERR_FAIL_COND(!multimesh);
4823 	ERR_FAIL_INDEX(p_index, multimesh->size);
4824 	ERR_FAIL_COND(multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_NONE);
4825 	ERR_FAIL_INDEX(multimesh->custom_data_format, VS::MULTIMESH_CUSTOM_DATA_MAX);
4826 
4827 	int stride = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
4828 	float *dataptr = &multimesh->data.write[stride * p_index + multimesh->xform_floats + multimesh->color_floats];
4829 
4830 	if (multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_8BIT) {
4831 
4832 		uint8_t *data8 = (uint8_t *)dataptr;
4833 		data8[0] = CLAMP(p_custom_data.r * 255.0, 0, 255);
4834 		data8[1] = CLAMP(p_custom_data.g * 255.0, 0, 255);
4835 		data8[2] = CLAMP(p_custom_data.b * 255.0, 0, 255);
4836 		data8[3] = CLAMP(p_custom_data.a * 255.0, 0, 255);
4837 
4838 	} else if (multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_FLOAT) {
4839 		dataptr[0] = p_custom_data.r;
4840 		dataptr[1] = p_custom_data.g;
4841 		dataptr[2] = p_custom_data.b;
4842 		dataptr[3] = p_custom_data.a;
4843 	}
4844 
4845 	multimesh->dirty_data = true;
4846 	multimesh->dirty_aabb = true;
4847 
4848 	if (!multimesh->update_list.in_list()) {
4849 		multimesh_update_list.add(&multimesh->update_list);
4850 	}
4851 }
4852 RID RasterizerStorageGLES3::multimesh_get_mesh(RID p_multimesh) const {
4853 
4854 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4855 	ERR_FAIL_COND_V(!multimesh, RID());
4856 
4857 	return multimesh->mesh;
4858 }
4859 
4860 Transform RasterizerStorageGLES3::multimesh_instance_get_transform(RID p_multimesh, int p_index) const {
4861 
4862 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4863 	ERR_FAIL_COND_V(!multimesh, Transform());
4864 	ERR_FAIL_INDEX_V(p_index, multimesh->size, Transform());
4865 	ERR_FAIL_COND_V(multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D, Transform());
4866 
4867 	int stride = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
4868 	float *dataptr = &multimesh->data.write[stride * p_index];
4869 
4870 	Transform xform;
4871 
4872 	xform.basis.elements[0][0] = dataptr[0];
4873 	xform.basis.elements[0][1] = dataptr[1];
4874 	xform.basis.elements[0][2] = dataptr[2];
4875 	xform.origin.x = dataptr[3];
4876 	xform.basis.elements[1][0] = dataptr[4];
4877 	xform.basis.elements[1][1] = dataptr[5];
4878 	xform.basis.elements[1][2] = dataptr[6];
4879 	xform.origin.y = dataptr[7];
4880 	xform.basis.elements[2][0] = dataptr[8];
4881 	xform.basis.elements[2][1] = dataptr[9];
4882 	xform.basis.elements[2][2] = dataptr[10];
4883 	xform.origin.z = dataptr[11];
4884 
4885 	return xform;
4886 }
4887 Transform2D RasterizerStorageGLES3::multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const {
4888 
4889 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4890 	ERR_FAIL_COND_V(!multimesh, Transform2D());
4891 	ERR_FAIL_INDEX_V(p_index, multimesh->size, Transform2D());
4892 	ERR_FAIL_COND_V(multimesh->transform_format == VS::MULTIMESH_TRANSFORM_3D, Transform2D());
4893 
4894 	int stride = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
4895 	float *dataptr = &multimesh->data.write[stride * p_index];
4896 
4897 	Transform2D xform;
4898 
4899 	xform.elements[0][0] = dataptr[0];
4900 	xform.elements[1][0] = dataptr[1];
4901 	xform.elements[2][0] = dataptr[3];
4902 	xform.elements[0][1] = dataptr[4];
4903 	xform.elements[1][1] = dataptr[5];
4904 	xform.elements[2][1] = dataptr[7];
4905 
4906 	return xform;
4907 }
4908 
4909 Color RasterizerStorageGLES3::multimesh_instance_get_color(RID p_multimesh, int p_index) const {
4910 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4911 	ERR_FAIL_COND_V(!multimesh, Color());
4912 	ERR_FAIL_INDEX_V(p_index, multimesh->size, Color());
4913 	ERR_FAIL_COND_V(multimesh->color_format == VS::MULTIMESH_COLOR_NONE, Color());
4914 	ERR_FAIL_INDEX_V(multimesh->color_format, VS::MULTIMESH_COLOR_MAX, Color());
4915 
4916 	int stride = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
4917 	float *dataptr = &multimesh->data.write[stride * p_index + multimesh->xform_floats];
4918 
4919 	if (multimesh->color_format == VS::MULTIMESH_COLOR_8BIT) {
4920 		union {
4921 			uint32_t colu;
4922 			float colf;
4923 		} cu;
4924 
4925 		cu.colf = dataptr[0];
4926 
4927 		return Color::hex(BSWAP32(cu.colu));
4928 
4929 	} else if (multimesh->color_format == VS::MULTIMESH_COLOR_FLOAT) {
4930 		Color c;
4931 		c.r = dataptr[0];
4932 		c.g = dataptr[1];
4933 		c.b = dataptr[2];
4934 		c.a = dataptr[3];
4935 
4936 		return c;
4937 	}
4938 
4939 	return Color();
4940 }
4941 
4942 Color RasterizerStorageGLES3::multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const {
4943 
4944 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4945 	ERR_FAIL_COND_V(!multimesh, Color());
4946 	ERR_FAIL_INDEX_V(p_index, multimesh->size, Color());
4947 	ERR_FAIL_COND_V(multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_NONE, Color());
4948 	ERR_FAIL_INDEX_V(multimesh->custom_data_format, VS::MULTIMESH_CUSTOM_DATA_MAX, Color());
4949 
4950 	int stride = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
4951 	float *dataptr = &multimesh->data.write[stride * p_index + multimesh->xform_floats + multimesh->color_floats];
4952 
4953 	if (multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_8BIT) {
4954 		union {
4955 			uint32_t colu;
4956 			float colf;
4957 		} cu;
4958 
4959 		cu.colf = dataptr[0];
4960 
4961 		return Color::hex(BSWAP32(cu.colu));
4962 
4963 	} else if (multimesh->custom_data_format == VS::MULTIMESH_CUSTOM_DATA_FLOAT) {
4964 		Color c;
4965 		c.r = dataptr[0];
4966 		c.g = dataptr[1];
4967 		c.b = dataptr[2];
4968 		c.a = dataptr[3];
4969 
4970 		return c;
4971 	}
4972 
4973 	return Color();
4974 }
4975 
4976 void RasterizerStorageGLES3::multimesh_set_as_bulk_array(RID p_multimesh, const PoolVector<float> &p_array) {
4977 
4978 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
4979 	ERR_FAIL_COND(!multimesh);
4980 	ERR_FAIL_COND(!multimesh->data.ptr());
4981 
4982 	int dsize = multimesh->data.size();
4983 
4984 	ERR_FAIL_COND(dsize != p_array.size());
4985 
4986 	PoolVector<float>::Read r = p_array.read();
4987 	copymem(multimesh->data.ptrw(), r.ptr(), dsize * sizeof(float));
4988 
4989 	multimesh->dirty_data = true;
4990 	multimesh->dirty_aabb = true;
4991 
4992 	if (!multimesh->update_list.in_list()) {
4993 		multimesh_update_list.add(&multimesh->update_list);
4994 	}
4995 }
4996 
4997 void RasterizerStorageGLES3::multimesh_set_visible_instances(RID p_multimesh, int p_visible) {
4998 
4999 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
5000 	ERR_FAIL_COND(!multimesh);
5001 
5002 	multimesh->visible_instances = p_visible;
5003 }
5004 int RasterizerStorageGLES3::multimesh_get_visible_instances(RID p_multimesh) const {
5005 
5006 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
5007 	ERR_FAIL_COND_V(!multimesh, -1);
5008 
5009 	return multimesh->visible_instances;
5010 }
5011 
5012 AABB RasterizerStorageGLES3::multimesh_get_aabb(RID p_multimesh) const {
5013 
5014 	MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
5015 	ERR_FAIL_COND_V(!multimesh, AABB());
5016 
5017 	const_cast<RasterizerStorageGLES3 *>(this)->update_dirty_multimeshes(); //update pending AABBs
5018 
5019 	return multimesh->aabb;
5020 }
5021 
5022 void RasterizerStorageGLES3::update_dirty_multimeshes() {
5023 
5024 	while (multimesh_update_list.first()) {
5025 
5026 		MultiMesh *multimesh = multimesh_update_list.first()->self();
5027 
5028 		if (multimesh->size && multimesh->dirty_data) {
5029 
5030 			glBindBuffer(GL_ARRAY_BUFFER, multimesh->buffer);
5031 			glBufferSubData(GL_ARRAY_BUFFER, 0, multimesh->data.size() * sizeof(float), multimesh->data.ptr());
5032 			glBindBuffer(GL_ARRAY_BUFFER, 0);
5033 		}
5034 
5035 		if (multimesh->size && multimesh->dirty_aabb) {
5036 
5037 			AABB mesh_aabb;
5038 
5039 			if (multimesh->mesh.is_valid()) {
5040 				mesh_aabb = mesh_get_aabb(multimesh->mesh, RID());
5041 			} else {
5042 				mesh_aabb.size += Vector3(0.001, 0.001, 0.001);
5043 			}
5044 
5045 			int stride = multimesh->color_floats + multimesh->xform_floats + multimesh->custom_data_floats;
5046 			int count = multimesh->data.size();
5047 			float *data = multimesh->data.ptrw();
5048 
5049 			AABB aabb;
5050 
5051 			if (multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D) {
5052 
5053 				for (int i = 0; i < count; i += stride) {
5054 
5055 					float *dataptr = &data[i];
5056 					Transform xform;
5057 					xform.basis[0][0] = dataptr[0];
5058 					xform.basis[0][1] = dataptr[1];
5059 					xform.origin[0] = dataptr[3];
5060 					xform.basis[1][0] = dataptr[4];
5061 					xform.basis[1][1] = dataptr[5];
5062 					xform.origin[1] = dataptr[7];
5063 
5064 					AABB laabb = xform.xform(mesh_aabb);
5065 					if (i == 0)
5066 						aabb = laabb;
5067 					else
5068 						aabb.merge_with(laabb);
5069 				}
5070 			} else {
5071 
5072 				for (int i = 0; i < count; i += stride) {
5073 
5074 					float *dataptr = &data[i];
5075 					Transform xform;
5076 
5077 					xform.basis.elements[0][0] = dataptr[0];
5078 					xform.basis.elements[0][1] = dataptr[1];
5079 					xform.basis.elements[0][2] = dataptr[2];
5080 					xform.origin.x = dataptr[3];
5081 					xform.basis.elements[1][0] = dataptr[4];
5082 					xform.basis.elements[1][1] = dataptr[5];
5083 					xform.basis.elements[1][2] = dataptr[6];
5084 					xform.origin.y = dataptr[7];
5085 					xform.basis.elements[2][0] = dataptr[8];
5086 					xform.basis.elements[2][1] = dataptr[9];
5087 					xform.basis.elements[2][2] = dataptr[10];
5088 					xform.origin.z = dataptr[11];
5089 
5090 					AABB laabb = xform.xform(mesh_aabb);
5091 					if (i == 0)
5092 						aabb = laabb;
5093 					else
5094 						aabb.merge_with(laabb);
5095 				}
5096 			}
5097 
5098 			multimesh->aabb = aabb;
5099 		}
5100 		multimesh->dirty_aabb = false;
5101 		multimesh->dirty_data = false;
5102 
5103 		multimesh->instance_change_notify(true, false);
5104 
5105 		multimesh_update_list.remove(multimesh_update_list.first());
5106 	}
5107 }
5108 
5109 /* IMMEDIATE API */
5110 
5111 RID RasterizerStorageGLES3::immediate_create() {
5112 
5113 	Immediate *im = memnew(Immediate);
5114 	return immediate_owner.make_rid(im);
5115 }
5116 
5117 void RasterizerStorageGLES3::immediate_begin(RID p_immediate, VS::PrimitiveType p_primitive, RID p_texture) {
5118 
5119 	ERR_FAIL_INDEX(p_primitive, (int)VS::PRIMITIVE_MAX);
5120 	Immediate *im = immediate_owner.get(p_immediate);
5121 	ERR_FAIL_COND(!im);
5122 	ERR_FAIL_COND(im->building);
5123 
5124 	Immediate::Chunk ic;
5125 	ic.texture = p_texture;
5126 	ic.primitive = p_primitive;
5127 	im->chunks.push_back(ic);
5128 	im->mask = 0;
5129 	im->building = true;
5130 }
5131 void RasterizerStorageGLES3::immediate_vertex(RID p_immediate, const Vector3 &p_vertex) {
5132 
5133 	Immediate *im = immediate_owner.get(p_immediate);
5134 	ERR_FAIL_COND(!im);
5135 	ERR_FAIL_COND(!im->building);
5136 
5137 	Immediate::Chunk *c = &im->chunks.back()->get();
5138 
5139 	if (c->vertices.empty() && im->chunks.size() == 1) {
5140 
5141 		im->aabb.position = p_vertex;
5142 		im->aabb.size = Vector3();
5143 	} else {
5144 		im->aabb.expand_to(p_vertex);
5145 	}
5146 
5147 	if (im->mask & VS::ARRAY_FORMAT_NORMAL)
5148 		c->normals.push_back(chunk_normal);
5149 	if (im->mask & VS::ARRAY_FORMAT_TANGENT)
5150 		c->tangents.push_back(chunk_tangent);
5151 	if (im->mask & VS::ARRAY_FORMAT_COLOR)
5152 		c->colors.push_back(chunk_color);
5153 	if (im->mask & VS::ARRAY_FORMAT_TEX_UV)
5154 		c->uvs.push_back(chunk_uv);
5155 	if (im->mask & VS::ARRAY_FORMAT_TEX_UV2)
5156 		c->uvs2.push_back(chunk_uv2);
5157 	im->mask |= VS::ARRAY_FORMAT_VERTEX;
5158 	c->vertices.push_back(p_vertex);
5159 }
5160 
5161 void RasterizerStorageGLES3::immediate_normal(RID p_immediate, const Vector3 &p_normal) {
5162 
5163 	Immediate *im = immediate_owner.get(p_immediate);
5164 	ERR_FAIL_COND(!im);
5165 	ERR_FAIL_COND(!im->building);
5166 
5167 	im->mask |= VS::ARRAY_FORMAT_NORMAL;
5168 	chunk_normal = p_normal;
5169 }
5170 void RasterizerStorageGLES3::immediate_tangent(RID p_immediate, const Plane &p_tangent) {
5171 
5172 	Immediate *im = immediate_owner.get(p_immediate);
5173 	ERR_FAIL_COND(!im);
5174 	ERR_FAIL_COND(!im->building);
5175 
5176 	im->mask |= VS::ARRAY_FORMAT_TANGENT;
5177 	chunk_tangent = p_tangent;
5178 }
5179 void RasterizerStorageGLES3::immediate_color(RID p_immediate, const Color &p_color) {
5180 
5181 	Immediate *im = immediate_owner.get(p_immediate);
5182 	ERR_FAIL_COND(!im);
5183 	ERR_FAIL_COND(!im->building);
5184 
5185 	im->mask |= VS::ARRAY_FORMAT_COLOR;
5186 	chunk_color = p_color;
5187 }
5188 void RasterizerStorageGLES3::immediate_uv(RID p_immediate, const Vector2 &tex_uv) {
5189 
5190 	Immediate *im = immediate_owner.get(p_immediate);
5191 	ERR_FAIL_COND(!im);
5192 	ERR_FAIL_COND(!im->building);
5193 
5194 	im->mask |= VS::ARRAY_FORMAT_TEX_UV;
5195 	chunk_uv = tex_uv;
5196 }
5197 void RasterizerStorageGLES3::immediate_uv2(RID p_immediate, const Vector2 &tex_uv) {
5198 
5199 	Immediate *im = immediate_owner.get(p_immediate);
5200 	ERR_FAIL_COND(!im);
5201 	ERR_FAIL_COND(!im->building);
5202 
5203 	im->mask |= VS::ARRAY_FORMAT_TEX_UV2;
5204 	chunk_uv2 = tex_uv;
5205 }
5206 
5207 void RasterizerStorageGLES3::immediate_end(RID p_immediate) {
5208 
5209 	Immediate *im = immediate_owner.get(p_immediate);
5210 	ERR_FAIL_COND(!im);
5211 	ERR_FAIL_COND(!im->building);
5212 
5213 	im->building = false;
5214 
5215 	im->instance_change_notify(true, false);
5216 }
5217 void RasterizerStorageGLES3::immediate_clear(RID p_immediate) {
5218 
5219 	Immediate *im = immediate_owner.get(p_immediate);
5220 	ERR_FAIL_COND(!im);
5221 	ERR_FAIL_COND(im->building);
5222 
5223 	im->chunks.clear();
5224 	im->instance_change_notify(true, false);
5225 }
5226 
5227 AABB RasterizerStorageGLES3::immediate_get_aabb(RID p_immediate) const {
5228 
5229 	Immediate *im = immediate_owner.get(p_immediate);
5230 	ERR_FAIL_COND_V(!im, AABB());
5231 	return im->aabb;
5232 }
5233 
5234 void RasterizerStorageGLES3::immediate_set_material(RID p_immediate, RID p_material) {
5235 
5236 	Immediate *im = immediate_owner.get(p_immediate);
5237 	ERR_FAIL_COND(!im);
5238 	im->material = p_material;
5239 	im->instance_change_notify(false, true);
5240 }
5241 
5242 RID RasterizerStorageGLES3::immediate_get_material(RID p_immediate) const {
5243 
5244 	const Immediate *im = immediate_owner.get(p_immediate);
5245 	ERR_FAIL_COND_V(!im, RID());
5246 	return im->material;
5247 }
5248 
5249 /* SKELETON API */
5250 
5251 RID RasterizerStorageGLES3::skeleton_create() {
5252 
5253 	Skeleton *skeleton = memnew(Skeleton);
5254 
5255 	glGenTextures(1, &skeleton->texture);
5256 
5257 	return skeleton_owner.make_rid(skeleton);
5258 }
5259 
5260 void RasterizerStorageGLES3::skeleton_allocate(RID p_skeleton, int p_bones, bool p_2d_skeleton) {
5261 
5262 	Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
5263 	ERR_FAIL_COND(!skeleton);
5264 	ERR_FAIL_COND(p_bones < 0);
5265 
5266 	if (skeleton->size == p_bones && skeleton->use_2d == p_2d_skeleton)
5267 		return;
5268 
5269 	skeleton->size = p_bones;
5270 	skeleton->use_2d = p_2d_skeleton;
5271 
5272 	int height = p_bones / 256;
5273 	if (p_bones % 256)
5274 		height++;
5275 
5276 	glActiveTexture(GL_TEXTURE0);
5277 	glBindTexture(GL_TEXTURE_2D, skeleton->texture);
5278 
5279 	if (skeleton->use_2d) {
5280 		skeleton->skel_texture.resize(256 * height * 2 * 4);
5281 		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 256, height * 2, 0, GL_RGBA, GL_FLOAT, NULL);
5282 	} else {
5283 		skeleton->skel_texture.resize(256 * height * 3 * 4);
5284 		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 256, height * 3, 0, GL_RGBA, GL_FLOAT, NULL);
5285 	}
5286 
5287 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
5288 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
5289 	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
5290 	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
5291 
5292 	if (!skeleton->update_list.in_list()) {
5293 		skeleton_update_list.add(&skeleton->update_list);
5294 	}
5295 }
5296 int RasterizerStorageGLES3::skeleton_get_bone_count(RID p_skeleton) const {
5297 
5298 	Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
5299 	ERR_FAIL_COND_V(!skeleton, 0);
5300 
5301 	return skeleton->size;
5302 }
5303 
5304 void RasterizerStorageGLES3::skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform) {
5305 
5306 	Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
5307 
5308 	ERR_FAIL_COND(!skeleton);
5309 	ERR_FAIL_INDEX(p_bone, skeleton->size);
5310 	ERR_FAIL_COND(skeleton->use_2d);
5311 
5312 	float *texture = skeleton->skel_texture.ptrw();
5313 
5314 	int base_ofs = ((p_bone / 256) * 256) * 3 * 4 + (p_bone % 256) * 4;
5315 
5316 	texture[base_ofs + 0] = p_transform.basis[0].x;
5317 	texture[base_ofs + 1] = p_transform.basis[0].y;
5318 	texture[base_ofs + 2] = p_transform.basis[0].z;
5319 	texture[base_ofs + 3] = p_transform.origin.x;
5320 	base_ofs += 256 * 4;
5321 	texture[base_ofs + 0] = p_transform.basis[1].x;
5322 	texture[base_ofs + 1] = p_transform.basis[1].y;
5323 	texture[base_ofs + 2] = p_transform.basis[1].z;
5324 	texture[base_ofs + 3] = p_transform.origin.y;
5325 	base_ofs += 256 * 4;
5326 	texture[base_ofs + 0] = p_transform.basis[2].x;
5327 	texture[base_ofs + 1] = p_transform.basis[2].y;
5328 	texture[base_ofs + 2] = p_transform.basis[2].z;
5329 	texture[base_ofs + 3] = p_transform.origin.z;
5330 
5331 	if (!skeleton->update_list.in_list()) {
5332 		skeleton_update_list.add(&skeleton->update_list);
5333 	}
5334 }
5335 
5336 Transform RasterizerStorageGLES3::skeleton_bone_get_transform(RID p_skeleton, int p_bone) const {
5337 
5338 	Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
5339 
5340 	ERR_FAIL_COND_V(!skeleton, Transform());
5341 	ERR_FAIL_INDEX_V(p_bone, skeleton->size, Transform());
5342 	ERR_FAIL_COND_V(skeleton->use_2d, Transform());
5343 
5344 	const float *texture = skeleton->skel_texture.ptr();
5345 
5346 	Transform ret;
5347 
5348 	int base_ofs = ((p_bone / 256) * 256) * 3 * 4 + (p_bone % 256) * 4;
5349 
5350 	ret.basis[0].x = texture[base_ofs + 0];
5351 	ret.basis[0].y = texture[base_ofs + 1];
5352 	ret.basis[0].z = texture[base_ofs + 2];
5353 	ret.origin.x = texture[base_ofs + 3];
5354 	base_ofs += 256 * 4;
5355 	ret.basis[1].x = texture[base_ofs + 0];
5356 	ret.basis[1].y = texture[base_ofs + 1];
5357 	ret.basis[1].z = texture[base_ofs + 2];
5358 	ret.origin.y = texture[base_ofs + 3];
5359 	base_ofs += 256 * 4;
5360 	ret.basis[2].x = texture[base_ofs + 0];
5361 	ret.basis[2].y = texture[base_ofs + 1];
5362 	ret.basis[2].z = texture[base_ofs + 2];
5363 	ret.origin.z = texture[base_ofs + 3];
5364 
5365 	return ret;
5366 }
5367 void RasterizerStorageGLES3::skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) {
5368 
5369 	Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
5370 
5371 	ERR_FAIL_COND(!skeleton);
5372 	ERR_FAIL_INDEX(p_bone, skeleton->size);
5373 	ERR_FAIL_COND(!skeleton->use_2d);
5374 
5375 	float *texture = skeleton->skel_texture.ptrw();
5376 
5377 	int base_ofs = ((p_bone / 256) * 256) * 2 * 4 + (p_bone % 256) * 4;
5378 
5379 	texture[base_ofs + 0] = p_transform[0][0];
5380 	texture[base_ofs + 1] = p_transform[1][0];
5381 	texture[base_ofs + 2] = 0;
5382 	texture[base_ofs + 3] = p_transform[2][0];
5383 	base_ofs += 256 * 4;
5384 	texture[base_ofs + 0] = p_transform[0][1];
5385 	texture[base_ofs + 1] = p_transform[1][1];
5386 	texture[base_ofs + 2] = 0;
5387 	texture[base_ofs + 3] = p_transform[2][1];
5388 
5389 	if (!skeleton->update_list.in_list()) {
5390 		skeleton_update_list.add(&skeleton->update_list);
5391 	}
5392 }
5393 Transform2D RasterizerStorageGLES3::skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const {
5394 
5395 	Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
5396 
5397 	ERR_FAIL_COND_V(!skeleton, Transform2D());
5398 	ERR_FAIL_INDEX_V(p_bone, skeleton->size, Transform2D());
5399 	ERR_FAIL_COND_V(!skeleton->use_2d, Transform2D());
5400 
5401 	const float *texture = skeleton->skel_texture.ptr();
5402 
5403 	Transform2D ret;
5404 
5405 	int base_ofs = ((p_bone / 256) * 256) * 2 * 4 + (p_bone % 256) * 4;
5406 
5407 	ret[0][0] = texture[base_ofs + 0];
5408 	ret[1][0] = texture[base_ofs + 1];
5409 	ret[2][0] = texture[base_ofs + 3];
5410 	base_ofs += 256 * 4;
5411 	ret[0][1] = texture[base_ofs + 0];
5412 	ret[1][1] = texture[base_ofs + 1];
5413 	ret[2][1] = texture[base_ofs + 3];
5414 
5415 	return ret;
5416 }
5417 
5418 void RasterizerStorageGLES3::skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) {
5419 
5420 	Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
5421 
5422 	ERR_FAIL_COND(!skeleton->use_2d);
5423 
5424 	skeleton->base_transform_2d = p_base_transform;
5425 }
5426 
5427 void RasterizerStorageGLES3::update_dirty_skeletons() {
5428 
5429 	glActiveTexture(GL_TEXTURE0);
5430 
5431 	while (skeleton_update_list.first()) {
5432 
5433 		Skeleton *skeleton = skeleton_update_list.first()->self();
5434 		if (skeleton->size) {
5435 
5436 			int height = skeleton->size / 256;
5437 			if (skeleton->size % 256)
5438 				height++;
5439 
5440 			glBindTexture(GL_TEXTURE_2D, skeleton->texture);
5441 			glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 256, height * (skeleton->use_2d ? 2 : 3), GL_RGBA, GL_FLOAT, skeleton->skel_texture.ptr());
5442 		}
5443 
5444 		for (Set<RasterizerScene::InstanceBase *>::Element *E = skeleton->instances.front(); E; E = E->next()) {
5445 			E->get()->base_changed(true, false);
5446 		}
5447 
5448 		skeleton_update_list.remove(skeleton_update_list.first());
5449 	}
5450 }
5451 
5452 /* Light API */
5453 
5454 RID RasterizerStorageGLES3::light_create(VS::LightType p_type) {
5455 
5456 	Light *light = memnew(Light);
5457 	light->type = p_type;
5458 
5459 	light->param[VS::LIGHT_PARAM_ENERGY] = 1.0;
5460 	light->param[VS::LIGHT_PARAM_INDIRECT_ENERGY] = 1.0;
5461 	light->param[VS::LIGHT_PARAM_SPECULAR] = 0.5;
5462 	light->param[VS::LIGHT_PARAM_RANGE] = 1.0;
5463 	light->param[VS::LIGHT_PARAM_SPOT_ANGLE] = 45;
5464 	light->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE] = 45;
5465 	light->param[VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE] = 0;
5466 	light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET] = 0.1;
5467 	light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_2_OFFSET] = 0.3;
5468 	light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_3_OFFSET] = 0.6;
5469 	light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS] = 0.1;
5470 	light->param[VS::LIGHT_PARAM_SHADOW_BIAS_SPLIT_SCALE] = 0.1;
5471 
5472 	light->color = Color(1, 1, 1, 1);
5473 	light->shadow = false;
5474 	light->negative = false;
5475 	light->cull_mask = 0xFFFFFFFF;
5476 	light->directional_shadow_mode = VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL;
5477 	light->omni_shadow_mode = VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID;
5478 	light->omni_shadow_detail = VS::LIGHT_OMNI_SHADOW_DETAIL_VERTICAL;
5479 	light->directional_blend_splits = false;
5480 	light->directional_range_mode = VS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE;
5481 	light->reverse_cull = false;
5482 	light->use_gi = true;
5483 	light->version = 0;
5484 
5485 	return light_owner.make_rid(light);
5486 }
5487 
5488 void RasterizerStorageGLES3::light_set_color(RID p_light, const Color &p_color) {
5489 
5490 	Light *light = light_owner.getornull(p_light);
5491 	ERR_FAIL_COND(!light);
5492 
5493 	light->color = p_color;
5494 }
5495 void RasterizerStorageGLES3::light_set_param(RID p_light, VS::LightParam p_param, float p_value) {
5496 
5497 	Light *light = light_owner.getornull(p_light);
5498 	ERR_FAIL_COND(!light);
5499 	ERR_FAIL_INDEX(p_param, VS::LIGHT_PARAM_MAX);
5500 
5501 	switch (p_param) {
5502 		case VS::LIGHT_PARAM_RANGE:
5503 		case VS::LIGHT_PARAM_SPOT_ANGLE:
5504 		case VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE:
5505 		case VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET:
5506 		case VS::LIGHT_PARAM_SHADOW_SPLIT_2_OFFSET:
5507 		case VS::LIGHT_PARAM_SHADOW_SPLIT_3_OFFSET:
5508 		case VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS:
5509 		case VS::LIGHT_PARAM_SHADOW_BIAS: {
5510 
5511 			light->version++;
5512 			light->instance_change_notify(true, false);
5513 		} break;
5514 		default: {
5515 		}
5516 	}
5517 
5518 	light->param[p_param] = p_value;
5519 }
5520 void RasterizerStorageGLES3::light_set_shadow(RID p_light, bool p_enabled) {
5521 
5522 	Light *light = light_owner.getornull(p_light);
5523 	ERR_FAIL_COND(!light);
5524 	light->shadow = p_enabled;
5525 
5526 	light->version++;
5527 	light->instance_change_notify(true, false);
5528 }
5529 
5530 void RasterizerStorageGLES3::light_set_shadow_color(RID p_light, const Color &p_color) {
5531 
5532 	Light *light = light_owner.getornull(p_light);
5533 	ERR_FAIL_COND(!light);
5534 	light->shadow_color = p_color;
5535 }
5536 
5537 void RasterizerStorageGLES3::light_set_projector(RID p_light, RID p_texture) {
5538 
5539 	Light *light = light_owner.getornull(p_light);
5540 	ERR_FAIL_COND(!light);
5541 
5542 	light->projector = p_texture;
5543 }
5544 
5545 void RasterizerStorageGLES3::light_set_negative(RID p_light, bool p_enable) {
5546 
5547 	Light *light = light_owner.getornull(p_light);
5548 	ERR_FAIL_COND(!light);
5549 
5550 	light->negative = p_enable;
5551 }
5552 void RasterizerStorageGLES3::light_set_cull_mask(RID p_light, uint32_t p_mask) {
5553 
5554 	Light *light = light_owner.getornull(p_light);
5555 	ERR_FAIL_COND(!light);
5556 
5557 	light->cull_mask = p_mask;
5558 
5559 	light->version++;
5560 	light->instance_change_notify(true, false);
5561 }
5562 
5563 void RasterizerStorageGLES3::light_set_reverse_cull_face_mode(RID p_light, bool p_enabled) {
5564 
5565 	Light *light = light_owner.getornull(p_light);
5566 	ERR_FAIL_COND(!light);
5567 
5568 	light->reverse_cull = p_enabled;
5569 
5570 	light->version++;
5571 	light->instance_change_notify(true, false);
5572 }
5573 
5574 void RasterizerStorageGLES3::light_set_use_gi(RID p_light, bool p_enabled) {
5575 	Light *light = light_owner.getornull(p_light);
5576 	ERR_FAIL_COND(!light);
5577 
5578 	light->use_gi = p_enabled;
5579 
5580 	light->version++;
5581 	light->instance_change_notify(true, false);
5582 }
5583 void RasterizerStorageGLES3::light_omni_set_shadow_mode(RID p_light, VS::LightOmniShadowMode p_mode) {
5584 
5585 	Light *light = light_owner.getornull(p_light);
5586 	ERR_FAIL_COND(!light);
5587 
5588 	light->omni_shadow_mode = p_mode;
5589 
5590 	light->version++;
5591 	light->instance_change_notify(true, false);
5592 }
5593 
5594 VS::LightOmniShadowMode RasterizerStorageGLES3::light_omni_get_shadow_mode(RID p_light) {
5595 
5596 	const Light *light = light_owner.getornull(p_light);
5597 	ERR_FAIL_COND_V(!light, VS::LIGHT_OMNI_SHADOW_CUBE);
5598 
5599 	return light->omni_shadow_mode;
5600 }
5601 
5602 void RasterizerStorageGLES3::light_omni_set_shadow_detail(RID p_light, VS::LightOmniShadowDetail p_detail) {
5603 
5604 	Light *light = light_owner.getornull(p_light);
5605 	ERR_FAIL_COND(!light);
5606 
5607 	light->omni_shadow_detail = p_detail;
5608 	light->version++;
5609 	light->instance_change_notify(true, false);
5610 }
5611 
5612 void RasterizerStorageGLES3::light_directional_set_shadow_mode(RID p_light, VS::LightDirectionalShadowMode p_mode) {
5613 
5614 	Light *light = light_owner.getornull(p_light);
5615 	ERR_FAIL_COND(!light);
5616 
5617 	light->directional_shadow_mode = p_mode;
5618 	light->version++;
5619 	light->instance_change_notify(true, false);
5620 }
5621 
5622 void RasterizerStorageGLES3::light_directional_set_blend_splits(RID p_light, bool p_enable) {
5623 
5624 	Light *light = light_owner.getornull(p_light);
5625 	ERR_FAIL_COND(!light);
5626 
5627 	light->directional_blend_splits = p_enable;
5628 	light->version++;
5629 	light->instance_change_notify(true, false);
5630 }
5631 
5632 bool RasterizerStorageGLES3::light_directional_get_blend_splits(RID p_light) const {
5633 
5634 	const Light *light = light_owner.getornull(p_light);
5635 	ERR_FAIL_COND_V(!light, false);
5636 
5637 	return light->directional_blend_splits;
5638 }
5639 
5640 VS::LightDirectionalShadowMode RasterizerStorageGLES3::light_directional_get_shadow_mode(RID p_light) {
5641 
5642 	const Light *light = light_owner.getornull(p_light);
5643 	ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL);
5644 
5645 	return light->directional_shadow_mode;
5646 }
5647 
5648 void RasterizerStorageGLES3::light_directional_set_shadow_depth_range_mode(RID p_light, VS::LightDirectionalShadowDepthRangeMode p_range_mode) {
5649 
5650 	Light *light = light_owner.getornull(p_light);
5651 	ERR_FAIL_COND(!light);
5652 
5653 	light->directional_range_mode = p_range_mode;
5654 }
5655 
5656 VS::LightDirectionalShadowDepthRangeMode RasterizerStorageGLES3::light_directional_get_shadow_depth_range_mode(RID p_light) const {
5657 
5658 	const Light *light = light_owner.getornull(p_light);
5659 	ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE);
5660 
5661 	return light->directional_range_mode;
5662 }
5663 
5664 VS::LightType RasterizerStorageGLES3::light_get_type(RID p_light) const {
5665 
5666 	const Light *light = light_owner.getornull(p_light);
5667 	ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL);
5668 
5669 	return light->type;
5670 }
5671 
5672 float RasterizerStorageGLES3::light_get_param(RID p_light, VS::LightParam p_param) {
5673 
5674 	const Light *light = light_owner.getornull(p_light);
5675 	ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL);
5676 
5677 	return light->param[p_param];
5678 }
5679 
5680 Color RasterizerStorageGLES3::light_get_color(RID p_light) {
5681 
5682 	const Light *light = light_owner.getornull(p_light);
5683 	ERR_FAIL_COND_V(!light, Color());
5684 
5685 	return light->color;
5686 }
5687 
5688 bool RasterizerStorageGLES3::light_get_use_gi(RID p_light) {
5689 	Light *light = light_owner.getornull(p_light);
5690 	ERR_FAIL_COND_V(!light, false);
5691 
5692 	return light->use_gi;
5693 }
5694 
5695 bool RasterizerStorageGLES3::light_has_shadow(RID p_light) const {
5696 
5697 	const Light *light = light_owner.getornull(p_light);
5698 	ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL);
5699 
5700 	return light->shadow;
5701 }
5702 
5703 uint64_t RasterizerStorageGLES3::light_get_version(RID p_light) const {
5704 
5705 	const Light *light = light_owner.getornull(p_light);
5706 	ERR_FAIL_COND_V(!light, 0);
5707 
5708 	return light->version;
5709 }
5710 
5711 AABB RasterizerStorageGLES3::light_get_aabb(RID p_light) const {
5712 
5713 	const Light *light = light_owner.getornull(p_light);
5714 	ERR_FAIL_COND_V(!light, AABB());
5715 
5716 	switch (light->type) {
5717 
5718 		case VS::LIGHT_SPOT: {
5719 
5720 			float len = light->param[VS::LIGHT_PARAM_RANGE];
5721 			float size = Math::tan(Math::deg2rad(light->param[VS::LIGHT_PARAM_SPOT_ANGLE])) * len;
5722 			return AABB(Vector3(-size, -size, -len), Vector3(size * 2, size * 2, len));
5723 		};
5724 		case VS::LIGHT_OMNI: {
5725 
5726 			float r = light->param[VS::LIGHT_PARAM_RANGE];
5727 			return AABB(-Vector3(r, r, r), Vector3(r, r, r) * 2);
5728 		};
5729 		case VS::LIGHT_DIRECTIONAL: {
5730 
5731 			return AABB();
5732 		};
5733 	}
5734 
5735 	ERR_FAIL_V(AABB());
5736 }
5737 
5738 /* PROBE API */
5739 
5740 RID RasterizerStorageGLES3::reflection_probe_create() {
5741 
5742 	ReflectionProbe *reflection_probe = memnew(ReflectionProbe);
5743 
5744 	reflection_probe->intensity = 1.0;
5745 	reflection_probe->interior_ambient = Color();
5746 	reflection_probe->interior_ambient_energy = 1.0;
5747 	reflection_probe->interior_ambient_probe_contrib = 0.0;
5748 
5749 	reflection_probe->max_distance = 0;
5750 	reflection_probe->extents = Vector3(1, 1, 1);
5751 	reflection_probe->origin_offset = Vector3(0, 0, 0);
5752 	reflection_probe->interior = false;
5753 	reflection_probe->box_projection = false;
5754 	reflection_probe->enable_shadows = false;
5755 	reflection_probe->cull_mask = (1 << 20) - 1;
5756 	reflection_probe->update_mode = VS::REFLECTION_PROBE_UPDATE_ONCE;
5757 
5758 	return reflection_probe_owner.make_rid(reflection_probe);
5759 }
5760 
5761 void RasterizerStorageGLES3::reflection_probe_set_update_mode(RID p_probe, VS::ReflectionProbeUpdateMode p_mode) {
5762 
5763 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5764 	ERR_FAIL_COND(!reflection_probe);
5765 
5766 	reflection_probe->update_mode = p_mode;
5767 	reflection_probe->instance_change_notify(true, false);
5768 }
5769 
5770 void RasterizerStorageGLES3::reflection_probe_set_intensity(RID p_probe, float p_intensity) {
5771 
5772 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5773 	ERR_FAIL_COND(!reflection_probe);
5774 
5775 	reflection_probe->intensity = p_intensity;
5776 }
5777 
5778 void RasterizerStorageGLES3::reflection_probe_set_interior_ambient(RID p_probe, const Color &p_ambient) {
5779 
5780 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5781 	ERR_FAIL_COND(!reflection_probe);
5782 
5783 	reflection_probe->interior_ambient = p_ambient;
5784 }
5785 
5786 void RasterizerStorageGLES3::reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy) {
5787 
5788 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5789 	ERR_FAIL_COND(!reflection_probe);
5790 
5791 	reflection_probe->interior_ambient_energy = p_energy;
5792 }
5793 
5794 void RasterizerStorageGLES3::reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib) {
5795 
5796 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5797 	ERR_FAIL_COND(!reflection_probe);
5798 
5799 	reflection_probe->interior_ambient_probe_contrib = p_contrib;
5800 }
5801 
5802 void RasterizerStorageGLES3::reflection_probe_set_max_distance(RID p_probe, float p_distance) {
5803 
5804 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5805 	ERR_FAIL_COND(!reflection_probe);
5806 
5807 	reflection_probe->max_distance = p_distance;
5808 	reflection_probe->instance_change_notify(true, false);
5809 }
5810 void RasterizerStorageGLES3::reflection_probe_set_extents(RID p_probe, const Vector3 &p_extents) {
5811 
5812 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5813 	ERR_FAIL_COND(!reflection_probe);
5814 
5815 	reflection_probe->extents = p_extents;
5816 	reflection_probe->instance_change_notify(true, false);
5817 }
5818 void RasterizerStorageGLES3::reflection_probe_set_origin_offset(RID p_probe, const Vector3 &p_offset) {
5819 
5820 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5821 	ERR_FAIL_COND(!reflection_probe);
5822 
5823 	reflection_probe->origin_offset = p_offset;
5824 	reflection_probe->instance_change_notify(true, false);
5825 }
5826 
5827 void RasterizerStorageGLES3::reflection_probe_set_as_interior(RID p_probe, bool p_enable) {
5828 
5829 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5830 	ERR_FAIL_COND(!reflection_probe);
5831 
5832 	reflection_probe->interior = p_enable;
5833 	reflection_probe->instance_change_notify(true, false);
5834 }
5835 void RasterizerStorageGLES3::reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable) {
5836 
5837 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5838 	ERR_FAIL_COND(!reflection_probe);
5839 
5840 	reflection_probe->box_projection = p_enable;
5841 }
5842 
5843 void RasterizerStorageGLES3::reflection_probe_set_enable_shadows(RID p_probe, bool p_enable) {
5844 
5845 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5846 	ERR_FAIL_COND(!reflection_probe);
5847 
5848 	reflection_probe->enable_shadows = p_enable;
5849 	reflection_probe->instance_change_notify(true, false);
5850 }
5851 void RasterizerStorageGLES3::reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers) {
5852 
5853 	ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5854 	ERR_FAIL_COND(!reflection_probe);
5855 
5856 	reflection_probe->cull_mask = p_layers;
5857 	reflection_probe->instance_change_notify(true, false);
5858 }
5859 
5860 void RasterizerStorageGLES3::reflection_probe_set_resolution(RID p_probe, int p_resolution) {
5861 }
5862 
5863 AABB RasterizerStorageGLES3::reflection_probe_get_aabb(RID p_probe) const {
5864 	const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5865 	ERR_FAIL_COND_V(!reflection_probe, AABB());
5866 
5867 	AABB aabb;
5868 	aabb.position = -reflection_probe->extents;
5869 	aabb.size = reflection_probe->extents * 2.0;
5870 
5871 	return aabb;
5872 }
5873 VS::ReflectionProbeUpdateMode RasterizerStorageGLES3::reflection_probe_get_update_mode(RID p_probe) const {
5874 
5875 	const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5876 	ERR_FAIL_COND_V(!reflection_probe, VS::REFLECTION_PROBE_UPDATE_ALWAYS);
5877 
5878 	return reflection_probe->update_mode;
5879 }
5880 
5881 uint32_t RasterizerStorageGLES3::reflection_probe_get_cull_mask(RID p_probe) const {
5882 
5883 	const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5884 	ERR_FAIL_COND_V(!reflection_probe, 0);
5885 
5886 	return reflection_probe->cull_mask;
5887 }
5888 
5889 Vector3 RasterizerStorageGLES3::reflection_probe_get_extents(RID p_probe) const {
5890 
5891 	const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5892 	ERR_FAIL_COND_V(!reflection_probe, Vector3());
5893 
5894 	return reflection_probe->extents;
5895 }
5896 Vector3 RasterizerStorageGLES3::reflection_probe_get_origin_offset(RID p_probe) const {
5897 
5898 	const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5899 	ERR_FAIL_COND_V(!reflection_probe, Vector3());
5900 
5901 	return reflection_probe->origin_offset;
5902 }
5903 
5904 bool RasterizerStorageGLES3::reflection_probe_renders_shadows(RID p_probe) const {
5905 
5906 	const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5907 	ERR_FAIL_COND_V(!reflection_probe, false);
5908 
5909 	return reflection_probe->enable_shadows;
5910 }
5911 
5912 float RasterizerStorageGLES3::reflection_probe_get_origin_max_distance(RID p_probe) const {
5913 
5914 	const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
5915 	ERR_FAIL_COND_V(!reflection_probe, 0);
5916 
5917 	return reflection_probe->max_distance;
5918 }
5919 
5920 RID RasterizerStorageGLES3::gi_probe_create() {
5921 
5922 	GIProbe *gip = memnew(GIProbe);
5923 
5924 	gip->bounds = AABB(Vector3(), Vector3(1, 1, 1));
5925 	gip->dynamic_range = 1.0;
5926 	gip->energy = 1.0;
5927 	gip->propagation = 1.0;
5928 	gip->bias = 0.4;
5929 	gip->normal_bias = 0.4;
5930 	gip->interior = false;
5931 	gip->compress = false;
5932 	gip->version = 1;
5933 	gip->cell_size = 1.0;
5934 
5935 	return gi_probe_owner.make_rid(gip);
5936 }
5937 
5938 void RasterizerStorageGLES3::gi_probe_set_bounds(RID p_probe, const AABB &p_bounds) {
5939 
5940 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
5941 	ERR_FAIL_COND(!gip);
5942 
5943 	gip->bounds = p_bounds;
5944 	gip->version++;
5945 	gip->instance_change_notify(true, false);
5946 }
5947 AABB RasterizerStorageGLES3::gi_probe_get_bounds(RID p_probe) const {
5948 
5949 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
5950 	ERR_FAIL_COND_V(!gip, AABB());
5951 
5952 	return gip->bounds;
5953 }
5954 
5955 void RasterizerStorageGLES3::gi_probe_set_cell_size(RID p_probe, float p_size) {
5956 
5957 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
5958 	ERR_FAIL_COND(!gip);
5959 
5960 	gip->cell_size = p_size;
5961 	gip->version++;
5962 	gip->instance_change_notify(true, false);
5963 }
5964 
5965 float RasterizerStorageGLES3::gi_probe_get_cell_size(RID p_probe) const {
5966 
5967 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
5968 	ERR_FAIL_COND_V(!gip, 0);
5969 
5970 	return gip->cell_size;
5971 }
5972 
5973 void RasterizerStorageGLES3::gi_probe_set_to_cell_xform(RID p_probe, const Transform &p_xform) {
5974 
5975 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
5976 	ERR_FAIL_COND(!gip);
5977 
5978 	gip->to_cell = p_xform;
5979 }
5980 
5981 Transform RasterizerStorageGLES3::gi_probe_get_to_cell_xform(RID p_probe) const {
5982 
5983 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
5984 	ERR_FAIL_COND_V(!gip, Transform());
5985 
5986 	return gip->to_cell;
5987 }
5988 
5989 void RasterizerStorageGLES3::gi_probe_set_dynamic_data(RID p_probe, const PoolVector<int> &p_data) {
5990 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
5991 	ERR_FAIL_COND(!gip);
5992 
5993 	gip->dynamic_data = p_data;
5994 	gip->version++;
5995 	gip->instance_change_notify(true, false);
5996 }
5997 PoolVector<int> RasterizerStorageGLES3::gi_probe_get_dynamic_data(RID p_probe) const {
5998 
5999 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
6000 	ERR_FAIL_COND_V(!gip, PoolVector<int>());
6001 
6002 	return gip->dynamic_data;
6003 }
6004 
6005 void RasterizerStorageGLES3::gi_probe_set_dynamic_range(RID p_probe, int p_range) {
6006 
6007 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
6008 	ERR_FAIL_COND(!gip);
6009 
6010 	gip->dynamic_range = p_range;
6011 }
6012 int RasterizerStorageGLES3::gi_probe_get_dynamic_range(RID p_probe) const {
6013 
6014 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
6015 	ERR_FAIL_COND_V(!gip, 0);
6016 
6017 	return gip->dynamic_range;
6018 }
6019 
6020 void RasterizerStorageGLES3::gi_probe_set_energy(RID p_probe, float p_range) {
6021 
6022 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
6023 	ERR_FAIL_COND(!gip);
6024 
6025 	gip->energy = p_range;
6026 }
6027 
6028 void RasterizerStorageGLES3::gi_probe_set_bias(RID p_probe, float p_range) {
6029 
6030 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
6031 	ERR_FAIL_COND(!gip);
6032 
6033 	gip->bias = p_range;
6034 }
6035 
6036 void RasterizerStorageGLES3::gi_probe_set_normal_bias(RID p_probe, float p_range) {
6037 
6038 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
6039 	ERR_FAIL_COND(!gip);
6040 
6041 	gip->normal_bias = p_range;
6042 }
6043 
6044 void RasterizerStorageGLES3::gi_probe_set_propagation(RID p_probe, float p_range) {
6045 
6046 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
6047 	ERR_FAIL_COND(!gip);
6048 
6049 	gip->propagation = p_range;
6050 }
6051 
6052 void RasterizerStorageGLES3::gi_probe_set_interior(RID p_probe, bool p_enable) {
6053 
6054 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
6055 	ERR_FAIL_COND(!gip);
6056 
6057 	gip->interior = p_enable;
6058 }
6059 
6060 bool RasterizerStorageGLES3::gi_probe_is_interior(RID p_probe) const {
6061 
6062 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
6063 	ERR_FAIL_COND_V(!gip, false);
6064 
6065 	return gip->interior;
6066 }
6067 
6068 void RasterizerStorageGLES3::gi_probe_set_compress(RID p_probe, bool p_enable) {
6069 
6070 	GIProbe *gip = gi_probe_owner.getornull(p_probe);
6071 	ERR_FAIL_COND(!gip);
6072 
6073 	gip->compress = p_enable;
6074 }
6075 
6076 bool RasterizerStorageGLES3::gi_probe_is_compressed(RID p_probe) const {
6077 
6078 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
6079 	ERR_FAIL_COND_V(!gip, false);
6080 
6081 	return gip->compress;
6082 }
6083 float RasterizerStorageGLES3::gi_probe_get_energy(RID p_probe) const {
6084 
6085 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
6086 	ERR_FAIL_COND_V(!gip, 0);
6087 
6088 	return gip->energy;
6089 }
6090 
6091 float RasterizerStorageGLES3::gi_probe_get_bias(RID p_probe) const {
6092 
6093 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
6094 	ERR_FAIL_COND_V(!gip, 0);
6095 
6096 	return gip->bias;
6097 }
6098 
6099 float RasterizerStorageGLES3::gi_probe_get_normal_bias(RID p_probe) const {
6100 
6101 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
6102 	ERR_FAIL_COND_V(!gip, 0);
6103 
6104 	return gip->normal_bias;
6105 }
6106 
6107 float RasterizerStorageGLES3::gi_probe_get_propagation(RID p_probe) const {
6108 
6109 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
6110 	ERR_FAIL_COND_V(!gip, 0);
6111 
6112 	return gip->propagation;
6113 }
6114 
6115 uint32_t RasterizerStorageGLES3::gi_probe_get_version(RID p_probe) {
6116 
6117 	const GIProbe *gip = gi_probe_owner.getornull(p_probe);
6118 	ERR_FAIL_COND_V(!gip, 0);
6119 
6120 	return gip->version;
6121 }
6122 
6123 RasterizerStorage::GIProbeCompression RasterizerStorageGLES3::gi_probe_get_dynamic_data_get_preferred_compression() const {
6124 	if (config.s3tc_supported) {
6125 		return GI_PROBE_S3TC;
6126 	} else {
6127 		return GI_PROBE_UNCOMPRESSED;
6128 	}
6129 }
6130 
6131 RID RasterizerStorageGLES3::gi_probe_dynamic_data_create(int p_width, int p_height, int p_depth, GIProbeCompression p_compression) {
6132 
6133 	GIProbeData *gipd = memnew(GIProbeData);
6134 
6135 	gipd->width = p_width;
6136 	gipd->height = p_height;
6137 	gipd->depth = p_depth;
6138 	gipd->compression = p_compression;
6139 
6140 	glActiveTexture(GL_TEXTURE0);
6141 	glGenTextures(1, &gipd->tex_id);
6142 	glBindTexture(GL_TEXTURE_3D, gipd->tex_id);
6143 
6144 	int level = 0;
6145 	int min_size = 1;
6146 
6147 	if (gipd->compression == GI_PROBE_S3TC) {
6148 		min_size = 4;
6149 	}
6150 
6151 	while (true) {
6152 
6153 		if (gipd->compression == GI_PROBE_S3TC) {
6154 			int size = p_width * p_height * p_depth;
6155 			glCompressedTexImage3D(GL_TEXTURE_3D, level, _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT, p_width, p_height, p_depth, 0, size, NULL);
6156 		} else {
6157 			glTexImage3D(GL_TEXTURE_3D, level, GL_RGBA8, p_width, p_height, p_depth, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
6158 		}
6159 
6160 		if (p_width <= min_size || p_height <= min_size || p_depth <= min_size)
6161 			break;
6162 		p_width >>= 1;
6163 		p_height >>= 1;
6164 		p_depth >>= 1;
6165 		level++;
6166 	}
6167 
6168 	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
6169 	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
6170 	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
6171 	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
6172 	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
6173 	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0);
6174 	glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, level);
6175 
6176 	gipd->levels = level + 1;
6177 
6178 	return gi_probe_data_owner.make_rid(gipd);
6179 }
6180 
6181 void RasterizerStorageGLES3::gi_probe_dynamic_data_update(RID p_gi_probe_data, int p_depth_slice, int p_slice_count, int p_mipmap, const void *p_data) {
6182 
6183 	GIProbeData *gipd = gi_probe_data_owner.getornull(p_gi_probe_data);
6184 	ERR_FAIL_COND(!gipd);
6185 	/*
6186 	Vector<uint8_t> data;
6187 	data.resize((gipd->width>>p_mipmap)*(gipd->height>>p_mipmap)*(gipd->depth>>p_mipmap)*4);
6188 
6189 	for(int i=0;i<(gipd->width>>p_mipmap);i++) {
6190 		for(int j=0;j<(gipd->height>>p_mipmap);j++) {
6191 			for(int k=0;k<(gipd->depth>>p_mipmap);k++) {
6192 
6193 				int ofs = (k*(gipd->height>>p_mipmap)*(gipd->width>>p_mipmap)) + j *(gipd->width>>p_mipmap) + i;
6194 				ofs*=4;
6195 				data[ofs+0]=i*0xFF/(gipd->width>>p_mipmap);
6196 				data[ofs+1]=j*0xFF/(gipd->height>>p_mipmap);
6197 				data[ofs+2]=k*0xFF/(gipd->depth>>p_mipmap);
6198 				data[ofs+3]=0xFF;
6199 			}
6200 		}
6201 	}
6202 */
6203 	glActiveTexture(GL_TEXTURE0);
6204 	glBindTexture(GL_TEXTURE_3D, gipd->tex_id);
6205 	if (gipd->compression == GI_PROBE_S3TC) {
6206 		int size = (gipd->width >> p_mipmap) * (gipd->height >> p_mipmap) * p_slice_count;
6207 		glCompressedTexSubImage3D(GL_TEXTURE_3D, p_mipmap, 0, 0, p_depth_slice, gipd->width >> p_mipmap, gipd->height >> p_mipmap, p_slice_count, _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT, size, p_data);
6208 	} else {
6209 		glTexSubImage3D(GL_TEXTURE_3D, p_mipmap, 0, 0, p_depth_slice, gipd->width >> p_mipmap, gipd->height >> p_mipmap, p_slice_count, GL_RGBA, GL_UNSIGNED_BYTE, p_data);
6210 	}
6211 	//glTexImage3D(GL_TEXTURE_3D,p_mipmap,GL_RGBA8,gipd->width>>p_mipmap,gipd->height>>p_mipmap,gipd->depth>>p_mipmap,0,GL_RGBA,GL_UNSIGNED_BYTE,p_data);
6212 	//glTexImage3D(GL_TEXTURE_3D,p_mipmap,GL_RGBA8,gipd->width>>p_mipmap,gipd->height>>p_mipmap,gipd->depth>>p_mipmap,0,GL_RGBA,GL_UNSIGNED_BYTE,data.ptr());
6213 }
6214 /////////////////////////////
6215 
6216 RID RasterizerStorageGLES3::lightmap_capture_create() {
6217 
6218 	LightmapCapture *capture = memnew(LightmapCapture);
6219 	return lightmap_capture_data_owner.make_rid(capture);
6220 }
6221 
6222 void RasterizerStorageGLES3::lightmap_capture_set_bounds(RID p_capture, const AABB &p_bounds) {
6223 
6224 	LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6225 	ERR_FAIL_COND(!capture);
6226 	capture->bounds = p_bounds;
6227 	capture->instance_change_notify(true, false);
6228 }
6229 AABB RasterizerStorageGLES3::lightmap_capture_get_bounds(RID p_capture) const {
6230 
6231 	const LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6232 	ERR_FAIL_COND_V(!capture, AABB());
6233 	return capture->bounds;
6234 }
6235 void RasterizerStorageGLES3::lightmap_capture_set_octree(RID p_capture, const PoolVector<uint8_t> &p_octree) {
6236 
6237 	LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6238 	ERR_FAIL_COND(!capture);
6239 
6240 	ERR_FAIL_COND(p_octree.size() == 0 || (p_octree.size() % sizeof(LightmapCaptureOctree)) != 0);
6241 
6242 	capture->octree.resize(p_octree.size() / sizeof(LightmapCaptureOctree));
6243 	if (p_octree.size()) {
6244 		PoolVector<LightmapCaptureOctree>::Write w = capture->octree.write();
6245 		PoolVector<uint8_t>::Read r = p_octree.read();
6246 		copymem(w.ptr(), r.ptr(), p_octree.size());
6247 	}
6248 	capture->instance_change_notify(true, false);
6249 }
6250 PoolVector<uint8_t> RasterizerStorageGLES3::lightmap_capture_get_octree(RID p_capture) const {
6251 
6252 	const LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6253 	ERR_FAIL_COND_V(!capture, PoolVector<uint8_t>());
6254 
6255 	if (capture->octree.size() == 0)
6256 		return PoolVector<uint8_t>();
6257 
6258 	PoolVector<uint8_t> ret;
6259 	ret.resize(capture->octree.size() * sizeof(LightmapCaptureOctree));
6260 	{
6261 		PoolVector<LightmapCaptureOctree>::Read r = capture->octree.read();
6262 		PoolVector<uint8_t>::Write w = ret.write();
6263 		copymem(w.ptr(), r.ptr(), ret.size());
6264 	}
6265 
6266 	return ret;
6267 }
6268 
6269 void RasterizerStorageGLES3::lightmap_capture_set_octree_cell_transform(RID p_capture, const Transform &p_xform) {
6270 	LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6271 	ERR_FAIL_COND(!capture);
6272 	capture->cell_xform = p_xform;
6273 }
6274 
6275 Transform RasterizerStorageGLES3::lightmap_capture_get_octree_cell_transform(RID p_capture) const {
6276 	const LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6277 	ERR_FAIL_COND_V(!capture, Transform());
6278 	return capture->cell_xform;
6279 }
6280 
6281 void RasterizerStorageGLES3::lightmap_capture_set_octree_cell_subdiv(RID p_capture, int p_subdiv) {
6282 	LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6283 	ERR_FAIL_COND(!capture);
6284 	capture->cell_subdiv = p_subdiv;
6285 }
6286 
6287 int RasterizerStorageGLES3::lightmap_capture_get_octree_cell_subdiv(RID p_capture) const {
6288 	const LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6289 	ERR_FAIL_COND_V(!capture, 0);
6290 	return capture->cell_subdiv;
6291 }
6292 
6293 void RasterizerStorageGLES3::lightmap_capture_set_energy(RID p_capture, float p_energy) {
6294 
6295 	LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6296 	ERR_FAIL_COND(!capture);
6297 	capture->energy = p_energy;
6298 }
6299 
6300 float RasterizerStorageGLES3::lightmap_capture_get_energy(RID p_capture) const {
6301 
6302 	const LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6303 	ERR_FAIL_COND_V(!capture, 0);
6304 	return capture->energy;
6305 }
6306 
6307 const PoolVector<RasterizerStorage::LightmapCaptureOctree> *RasterizerStorageGLES3::lightmap_capture_get_octree_ptr(RID p_capture) const {
6308 	const LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture);
6309 	ERR_FAIL_COND_V(!capture, NULL);
6310 	return &capture->octree;
6311 }
6312 
6313 ///////
6314 
6315 RID RasterizerStorageGLES3::particles_create() {
6316 
6317 	Particles *particles = memnew(Particles);
6318 
6319 	return particles_owner.make_rid(particles);
6320 }
6321 
6322 void RasterizerStorageGLES3::particles_set_emitting(RID p_particles, bool p_emitting) {
6323 
6324 	Particles *particles = particles_owner.getornull(p_particles);
6325 	ERR_FAIL_COND(!particles);
6326 
6327 	particles->emitting = p_emitting;
6328 }
6329 
6330 bool RasterizerStorageGLES3::particles_get_emitting(RID p_particles) {
6331 	Particles *particles = particles_owner.getornull(p_particles);
6332 	ERR_FAIL_COND_V(!particles, false);
6333 
6334 	return particles->emitting;
6335 }
6336 
6337 void RasterizerStorageGLES3::particles_set_amount(RID p_particles, int p_amount) {
6338 
6339 	Particles *particles = particles_owner.getornull(p_particles);
6340 	ERR_FAIL_COND(!particles);
6341 
6342 	particles->amount = p_amount;
6343 
6344 	int floats = p_amount * 24;
6345 	float *data = memnew_arr(float, floats);
6346 
6347 	for (int i = 0; i < floats; i++) {
6348 		data[i] = 0;
6349 	}
6350 
6351 	for (int i = 0; i < 2; i++) {
6352 
6353 		glBindVertexArray(particles->particle_vaos[i]);
6354 
6355 		glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[i]);
6356 		glBufferData(GL_ARRAY_BUFFER, floats * sizeof(float), data, GL_STATIC_DRAW);
6357 
6358 		for (int j = 0; j < 6; j++) {
6359 			glEnableVertexAttribArray(j);
6360 			glVertexAttribPointer(j, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4 * 6, CAST_INT_TO_UCHAR_PTR(j * 16));
6361 		}
6362 	}
6363 
6364 	if (particles->histories_enabled) {
6365 
6366 		for (int i = 0; i < 2; i++) {
6367 			glBindVertexArray(particles->particle_vao_histories[i]);
6368 
6369 			glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffer_histories[i]);
6370 			glBufferData(GL_ARRAY_BUFFER, floats * sizeof(float), data, GL_DYNAMIC_COPY);
6371 
6372 			for (int j = 0; j < 6; j++) {
6373 				glEnableVertexAttribArray(j);
6374 				glVertexAttribPointer(j, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4 * 6, CAST_INT_TO_UCHAR_PTR(j * 16));
6375 			}
6376 			particles->particle_valid_histories[i] = false;
6377 		}
6378 	}
6379 
6380 	glBindVertexArray(0);
6381 
6382 	particles->prev_ticks = 0;
6383 	particles->phase = 0;
6384 	particles->prev_phase = 0;
6385 	particles->clear = true;
6386 
6387 	memdelete_arr(data);
6388 }
6389 
6390 void RasterizerStorageGLES3::particles_set_lifetime(RID p_particles, float p_lifetime) {
6391 
6392 	Particles *particles = particles_owner.getornull(p_particles);
6393 	ERR_FAIL_COND(!particles);
6394 	particles->lifetime = p_lifetime;
6395 }
6396 
6397 void RasterizerStorageGLES3::particles_set_one_shot(RID p_particles, bool p_one_shot) {
6398 
6399 	Particles *particles = particles_owner.getornull(p_particles);
6400 	ERR_FAIL_COND(!particles);
6401 	particles->one_shot = p_one_shot;
6402 }
6403 
6404 void RasterizerStorageGLES3::particles_set_pre_process_time(RID p_particles, float p_time) {
6405 
6406 	Particles *particles = particles_owner.getornull(p_particles);
6407 	ERR_FAIL_COND(!particles);
6408 	particles->pre_process_time = p_time;
6409 }
6410 void RasterizerStorageGLES3::particles_set_explosiveness_ratio(RID p_particles, float p_ratio) {
6411 
6412 	Particles *particles = particles_owner.getornull(p_particles);
6413 	ERR_FAIL_COND(!particles);
6414 	particles->explosiveness = p_ratio;
6415 }
6416 void RasterizerStorageGLES3::particles_set_randomness_ratio(RID p_particles, float p_ratio) {
6417 
6418 	Particles *particles = particles_owner.getornull(p_particles);
6419 	ERR_FAIL_COND(!particles);
6420 	particles->randomness = p_ratio;
6421 }
6422 
6423 void RasterizerStorageGLES3::_particles_update_histories(Particles *particles) {
6424 
6425 	bool needs_histories = particles->draw_order == VS::PARTICLES_DRAW_ORDER_VIEW_DEPTH;
6426 
6427 	if (needs_histories == particles->histories_enabled)
6428 		return;
6429 
6430 	particles->histories_enabled = needs_histories;
6431 
6432 	int floats = particles->amount * 24;
6433 
6434 	if (!needs_histories) {
6435 
6436 		glDeleteBuffers(2, particles->particle_buffer_histories);
6437 		glDeleteVertexArrays(2, particles->particle_vao_histories);
6438 
6439 	} else {
6440 
6441 		glGenBuffers(2, particles->particle_buffer_histories);
6442 		glGenVertexArrays(2, particles->particle_vao_histories);
6443 
6444 		for (int i = 0; i < 2; i++) {
6445 			glBindVertexArray(particles->particle_vao_histories[i]);
6446 
6447 			glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffer_histories[i]);
6448 			glBufferData(GL_ARRAY_BUFFER, floats * sizeof(float), NULL, GL_DYNAMIC_COPY);
6449 
6450 			for (int j = 0; j < 6; j++) {
6451 				glEnableVertexAttribArray(j);
6452 				glVertexAttribPointer(j, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4 * 6, CAST_INT_TO_UCHAR_PTR(j * 16));
6453 			}
6454 
6455 			particles->particle_valid_histories[i] = false;
6456 		}
6457 	}
6458 
6459 	particles->clear = true;
6460 }
6461 
6462 void RasterizerStorageGLES3::particles_set_custom_aabb(RID p_particles, const AABB &p_aabb) {
6463 
6464 	Particles *particles = particles_owner.getornull(p_particles);
6465 	ERR_FAIL_COND(!particles);
6466 	particles->custom_aabb = p_aabb;
6467 	_particles_update_histories(particles);
6468 	particles->instance_change_notify(true, false);
6469 }
6470 
6471 void RasterizerStorageGLES3::particles_set_speed_scale(RID p_particles, float p_scale) {
6472 
6473 	Particles *particles = particles_owner.getornull(p_particles);
6474 	ERR_FAIL_COND(!particles);
6475 
6476 	particles->speed_scale = p_scale;
6477 }
6478 void RasterizerStorageGLES3::particles_set_use_local_coordinates(RID p_particles, bool p_enable) {
6479 
6480 	Particles *particles = particles_owner.getornull(p_particles);
6481 	ERR_FAIL_COND(!particles);
6482 
6483 	particles->use_local_coords = p_enable;
6484 }
6485 
6486 void RasterizerStorageGLES3::particles_set_fixed_fps(RID p_particles, int p_fps) {
6487 
6488 	Particles *particles = particles_owner.getornull(p_particles);
6489 	ERR_FAIL_COND(!particles);
6490 
6491 	particles->fixed_fps = p_fps;
6492 }
6493 
6494 void RasterizerStorageGLES3::particles_set_fractional_delta(RID p_particles, bool p_enable) {
6495 
6496 	Particles *particles = particles_owner.getornull(p_particles);
6497 	ERR_FAIL_COND(!particles);
6498 
6499 	particles->fractional_delta = p_enable;
6500 }
6501 
6502 void RasterizerStorageGLES3::particles_set_process_material(RID p_particles, RID p_material) {
6503 
6504 	Particles *particles = particles_owner.getornull(p_particles);
6505 	ERR_FAIL_COND(!particles);
6506 
6507 	particles->process_material = p_material;
6508 }
6509 
6510 void RasterizerStorageGLES3::particles_set_draw_order(RID p_particles, VS::ParticlesDrawOrder p_order) {
6511 
6512 	Particles *particles = particles_owner.getornull(p_particles);
6513 	ERR_FAIL_COND(!particles);
6514 
6515 	particles->draw_order = p_order;
6516 	_particles_update_histories(particles);
6517 }
6518 
6519 void RasterizerStorageGLES3::particles_set_draw_passes(RID p_particles, int p_passes) {
6520 
6521 	Particles *particles = particles_owner.getornull(p_particles);
6522 	ERR_FAIL_COND(!particles);
6523 
6524 	particles->draw_passes.resize(p_passes);
6525 }
6526 
6527 void RasterizerStorageGLES3::particles_set_draw_pass_mesh(RID p_particles, int p_pass, RID p_mesh) {
6528 
6529 	Particles *particles = particles_owner.getornull(p_particles);
6530 	ERR_FAIL_COND(!particles);
6531 	ERR_FAIL_INDEX(p_pass, particles->draw_passes.size());
6532 	particles->draw_passes.write[p_pass] = p_mesh;
6533 }
6534 
6535 void RasterizerStorageGLES3::particles_restart(RID p_particles) {
6536 
6537 	Particles *particles = particles_owner.getornull(p_particles);
6538 	ERR_FAIL_COND(!particles);
6539 
6540 	particles->restart_request = true;
6541 }
6542 
6543 void RasterizerStorageGLES3::particles_request_process(RID p_particles) {
6544 
6545 	Particles *particles = particles_owner.getornull(p_particles);
6546 	ERR_FAIL_COND(!particles);
6547 
6548 	if (!particles->particle_element.in_list()) {
6549 		particle_update_list.add(&particles->particle_element);
6550 	}
6551 }
6552 
6553 AABB RasterizerStorageGLES3::particles_get_current_aabb(RID p_particles) {
6554 
6555 	const Particles *particles = particles_owner.getornull(p_particles);
6556 	ERR_FAIL_COND_V(!particles, AABB());
6557 
6558 	const float *data;
6559 	glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[0]);
6560 
6561 #if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__)
6562 	PoolVector<uint8_t> vector;
6563 	vector.resize(particles->amount * 16 * 6);
6564 	{
6565 		PoolVector<uint8_t>::Write w = vector.write();
6566 		glGetBufferSubData(GL_ARRAY_BUFFER, 0, particles->amount * 16 * 6, w.ptr());
6567 	}
6568 	PoolVector<uint8_t>::Read r = vector.read();
6569 	data = reinterpret_cast<const float *>(r.ptr());
6570 #else
6571 	data = (float *)glMapBufferRange(GL_ARRAY_BUFFER, 0, particles->amount * 16 * 6, GL_MAP_READ_BIT);
6572 #endif
6573 	AABB aabb;
6574 
6575 	Transform inv = particles->emission_transform.affine_inverse();
6576 
6577 	for (int i = 0; i < particles->amount; i++) {
6578 		int ofs = i * 24;
6579 		Vector3 pos = Vector3(data[ofs + 15], data[ofs + 19], data[ofs + 23]);
6580 		if (!particles->use_local_coords) {
6581 			pos = inv.xform(pos);
6582 		}
6583 		if (i == 0)
6584 			aabb.position = pos;
6585 		else
6586 			aabb.expand_to(pos);
6587 	}
6588 
6589 #if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__)
6590 	r.release();
6591 	vector = PoolVector<uint8_t>();
6592 #else
6593 	glUnmapBuffer(GL_ARRAY_BUFFER);
6594 #endif
6595 
6596 	glBindBuffer(GL_ARRAY_BUFFER, 0);
6597 
6598 	float longest_axis = 0;
6599 	for (int i = 0; i < particles->draw_passes.size(); i++) {
6600 		if (particles->draw_passes[i].is_valid()) {
6601 			AABB maabb = mesh_get_aabb(particles->draw_passes[i], RID());
6602 			longest_axis = MAX(maabb.get_longest_axis_size(), longest_axis);
6603 		}
6604 	}
6605 
6606 	aabb.grow_by(longest_axis);
6607 
6608 	return aabb;
6609 }
6610 
6611 AABB RasterizerStorageGLES3::particles_get_aabb(RID p_particles) const {
6612 
6613 	const Particles *particles = particles_owner.getornull(p_particles);
6614 	ERR_FAIL_COND_V(!particles, AABB());
6615 
6616 	return particles->custom_aabb;
6617 }
6618 
6619 void RasterizerStorageGLES3::particles_set_emission_transform(RID p_particles, const Transform &p_transform) {
6620 
6621 	Particles *particles = particles_owner.getornull(p_particles);
6622 	ERR_FAIL_COND(!particles);
6623 
6624 	particles->emission_transform = p_transform;
6625 }
6626 
6627 int RasterizerStorageGLES3::particles_get_draw_passes(RID p_particles) const {
6628 
6629 	const Particles *particles = particles_owner.getornull(p_particles);
6630 	ERR_FAIL_COND_V(!particles, 0);
6631 
6632 	return particles->draw_passes.size();
6633 }
6634 
6635 RID RasterizerStorageGLES3::particles_get_draw_pass_mesh(RID p_particles, int p_pass) const {
6636 
6637 	const Particles *particles = particles_owner.getornull(p_particles);
6638 	ERR_FAIL_COND_V(!particles, RID());
6639 	ERR_FAIL_INDEX_V(p_pass, particles->draw_passes.size(), RID());
6640 
6641 	return particles->draw_passes[p_pass];
6642 }
6643 
6644 void RasterizerStorageGLES3::_particles_process(Particles *p_particles, float p_delta) {
6645 
6646 	float new_phase = Math::fmod((float)p_particles->phase + (p_delta / p_particles->lifetime) * p_particles->speed_scale, (float)1.0);
6647 
6648 	if (p_particles->clear) {
6649 		p_particles->cycle_number = 0;
6650 		p_particles->random_seed = Math::rand();
6651 	} else if (new_phase < p_particles->phase) {
6652 		if (p_particles->one_shot) {
6653 			p_particles->emitting = false;
6654 			shaders.particles.set_uniform(ParticlesShaderGLES3::EMITTING, false);
6655 		}
6656 		p_particles->cycle_number++;
6657 	}
6658 
6659 	shaders.particles.set_uniform(ParticlesShaderGLES3::SYSTEM_PHASE, new_phase);
6660 	shaders.particles.set_uniform(ParticlesShaderGLES3::PREV_SYSTEM_PHASE, p_particles->phase);
6661 	p_particles->phase = new_phase;
6662 
6663 	shaders.particles.set_uniform(ParticlesShaderGLES3::DELTA, p_delta * p_particles->speed_scale);
6664 	shaders.particles.set_uniform(ParticlesShaderGLES3::CLEAR, p_particles->clear);
6665 	glUniform1ui(shaders.particles.get_uniform_location(ParticlesShaderGLES3::RANDOM_SEED), p_particles->random_seed);
6666 
6667 	if (p_particles->use_local_coords)
6668 		shaders.particles.set_uniform(ParticlesShaderGLES3::EMISSION_TRANSFORM, Transform());
6669 	else
6670 		shaders.particles.set_uniform(ParticlesShaderGLES3::EMISSION_TRANSFORM, p_particles->emission_transform);
6671 
6672 	glUniform1ui(shaders.particles.get_uniform(ParticlesShaderGLES3::CYCLE), p_particles->cycle_number);
6673 
6674 	p_particles->clear = false;
6675 
6676 	glBindVertexArray(p_particles->particle_vaos[0]);
6677 
6678 	glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, p_particles->particle_buffers[1]);
6679 
6680 	//		GLint size = 0;
6681 	//		glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
6682 
6683 	glBeginTransformFeedback(GL_POINTS);
6684 	glDrawArrays(GL_POINTS, 0, p_particles->amount);
6685 	glEndTransformFeedback();
6686 
6687 	SWAP(p_particles->particle_buffers[0], p_particles->particle_buffers[1]);
6688 	SWAP(p_particles->particle_vaos[0], p_particles->particle_vaos[1]);
6689 
6690 	glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
6691 	glBindVertexArray(0);
6692 	/* //debug particles :D
6693 	glBindBuffer(GL_ARRAY_BUFFER, p_particles->particle_buffers[0]);
6694 
6695 	float *data = (float *)glMapBufferRange(GL_ARRAY_BUFFER, 0, p_particles->amount * 16 * 6, GL_MAP_READ_BIT);
6696 	for (int i = 0; i < p_particles->amount; i++) {
6697 		int ofs = i * 24;
6698 		print_line(itos(i) + ":");
6699 		print_line("\tColor: " + Color(data[ofs + 0], data[ofs + 1], data[ofs + 2], data[ofs + 3]));
6700 		print_line("\tVelocity: " + Vector3(data[ofs + 4], data[ofs + 5], data[ofs + 6]));
6701 		print_line("\tActive: " + itos(data[ofs + 7]));
6702 		print_line("\tCustom: " + Color(data[ofs + 8], data[ofs + 9], data[ofs + 10], data[ofs + 11]));
6703 		print_line("\tXF X: " + Color(data[ofs + 12], data[ofs + 13], data[ofs + 14], data[ofs + 15]));
6704 		print_line("\tXF Y: " + Color(data[ofs + 16], data[ofs + 17], data[ofs + 18], data[ofs + 19]));
6705 		print_line("\tXF Z: " + Color(data[ofs + 20], data[ofs + 21], data[ofs + 22], data[ofs + 23]));
6706 	}
6707 
6708 	glUnmapBuffer(GL_ARRAY_BUFFER);
6709 	glBindBuffer(GL_ARRAY_BUFFER, 0);
6710 	//*/
6711 }
6712 
6713 void RasterizerStorageGLES3::update_particles() {
6714 
6715 	glEnable(GL_RASTERIZER_DISCARD);
6716 
6717 	while (particle_update_list.first()) {
6718 
6719 		//use transform feedback to process particles
6720 
6721 		Particles *particles = particle_update_list.first()->self();
6722 
6723 		if (particles->restart_request) {
6724 			particles->prev_ticks = 0;
6725 			particles->phase = 0;
6726 			particles->prev_phase = 0;
6727 			particles->clear = true;
6728 			particles->particle_valid_histories[0] = false;
6729 			particles->particle_valid_histories[1] = false;
6730 			particles->restart_request = false;
6731 		}
6732 
6733 		if (particles->inactive && !particles->emitting) {
6734 
6735 			particle_update_list.remove(particle_update_list.first());
6736 			continue;
6737 		}
6738 
6739 		if (particles->emitting) {
6740 			if (particles->inactive) {
6741 				//restart system from scratch
6742 				particles->prev_ticks = 0;
6743 				particles->phase = 0;
6744 				particles->prev_phase = 0;
6745 				particles->clear = true;
6746 				particles->particle_valid_histories[0] = false;
6747 				particles->particle_valid_histories[1] = false;
6748 			}
6749 			particles->inactive = false;
6750 			particles->inactive_time = 0;
6751 		} else {
6752 			particles->inactive_time += particles->speed_scale * frame.delta;
6753 			if (particles->inactive_time > particles->lifetime * 1.2) {
6754 				particles->inactive = true;
6755 				particle_update_list.remove(particle_update_list.first());
6756 				continue;
6757 			}
6758 		}
6759 
6760 		Material *material = material_owner.getornull(particles->process_material);
6761 		if (!material || !material->shader || material->shader->mode != VS::SHADER_PARTICLES) {
6762 
6763 			shaders.particles.set_custom_shader(0);
6764 		} else {
6765 			shaders.particles.set_custom_shader(material->shader->custom_code_id);
6766 
6767 			if (material->ubo_id) {
6768 
6769 				glBindBufferBase(GL_UNIFORM_BUFFER, 0, material->ubo_id);
6770 			}
6771 
6772 			int tc = material->textures.size();
6773 			RID *textures = material->textures.ptrw();
6774 			ShaderLanguage::ShaderNode::Uniform::Hint *texture_hints = material->shader->texture_hints.ptrw();
6775 
6776 			for (int i = 0; i < tc; i++) {
6777 
6778 				glActiveTexture(GL_TEXTURE0 + i);
6779 
6780 				GLenum target;
6781 				GLuint tex;
6782 
6783 				RasterizerStorageGLES3::Texture *t = texture_owner.getornull(textures[i]);
6784 
6785 				if (!t) {
6786 					//check hints
6787 					target = GL_TEXTURE_2D;
6788 
6789 					switch (texture_hints[i]) {
6790 						case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO:
6791 						case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: {
6792 							tex = resources.black_tex;
6793 						} break;
6794 						case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: {
6795 							tex = resources.aniso_tex;
6796 						} break;
6797 						case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: {
6798 							tex = resources.normal_tex;
6799 						} break;
6800 						default: {
6801 							tex = resources.white_tex;
6802 						} break;
6803 					}
6804 				} else {
6805 
6806 					t = t->get_ptr(); //resolve for proxies
6807 					target = t->target;
6808 					tex = t->tex_id;
6809 				}
6810 
6811 				glBindTexture(target, tex);
6812 			}
6813 		}
6814 
6815 		shaders.particles.set_conditional(ParticlesShaderGLES3::USE_FRACTIONAL_DELTA, particles->fractional_delta);
6816 
6817 		shaders.particles.bind();
6818 
6819 		shaders.particles.set_uniform(ParticlesShaderGLES3::TOTAL_PARTICLES, particles->amount);
6820 		shaders.particles.set_uniform(ParticlesShaderGLES3::TIME, frame.time[0]);
6821 		shaders.particles.set_uniform(ParticlesShaderGLES3::EXPLOSIVENESS, particles->explosiveness);
6822 		shaders.particles.set_uniform(ParticlesShaderGLES3::LIFETIME, particles->lifetime);
6823 		shaders.particles.set_uniform(ParticlesShaderGLES3::ATTRACTOR_COUNT, 0);
6824 		shaders.particles.set_uniform(ParticlesShaderGLES3::EMITTING, particles->emitting);
6825 		shaders.particles.set_uniform(ParticlesShaderGLES3::RANDOMNESS, particles->randomness);
6826 
6827 		bool zero_time_scale = Engine::get_singleton()->get_time_scale() <= 0.0;
6828 
6829 		if (particles->clear && particles->pre_process_time > 0.0) {
6830 
6831 			float frame_time;
6832 			if (particles->fixed_fps > 0)
6833 				frame_time = 1.0 / particles->fixed_fps;
6834 			else
6835 				frame_time = 1.0 / 30.0;
6836 
6837 			float todo = particles->pre_process_time;
6838 
6839 			while (todo >= 0) {
6840 				_particles_process(particles, frame_time);
6841 				todo -= frame_time;
6842 			}
6843 		}
6844 
6845 		if (particles->fixed_fps > 0) {
6846 			float frame_time;
6847 			float decr;
6848 			if (zero_time_scale) {
6849 				frame_time = 0.0;
6850 				decr = 1.0 / particles->fixed_fps;
6851 			} else {
6852 				frame_time = 1.0 / particles->fixed_fps;
6853 				decr = frame_time;
6854 			}
6855 			float delta = frame.delta;
6856 			if (delta > 0.1) { //avoid recursive stalls if fps goes below 10
6857 				delta = 0.1;
6858 			} else if (delta <= 0.0) { //unlikely but..
6859 				delta = 0.001;
6860 			}
6861 			float todo = particles->frame_remainder + delta;
6862 
6863 			while (todo >= frame_time) {
6864 				_particles_process(particles, frame_time);
6865 				todo -= decr;
6866 			}
6867 
6868 			particles->frame_remainder = todo;
6869 
6870 		} else {
6871 			if (zero_time_scale)
6872 				_particles_process(particles, 0.0);
6873 			else
6874 				_particles_process(particles, frame.delta);
6875 		}
6876 
6877 		particle_update_list.remove(particle_update_list.first());
6878 
6879 		if (particles->histories_enabled) {
6880 
6881 			SWAP(particles->particle_buffer_histories[0], particles->particle_buffer_histories[1]);
6882 			SWAP(particles->particle_vao_histories[0], particles->particle_vao_histories[1]);
6883 			SWAP(particles->particle_valid_histories[0], particles->particle_valid_histories[1]);
6884 
6885 			//copy
6886 			glBindBuffer(GL_COPY_READ_BUFFER, particles->particle_buffers[0]);
6887 			glBindBuffer(GL_COPY_WRITE_BUFFER, particles->particle_buffer_histories[0]);
6888 			glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, particles->amount * 24 * sizeof(float));
6889 
6890 			particles->particle_valid_histories[0] = true;
6891 		}
6892 
6893 		particles->instance_change_notify(true, false); //make sure shadows are updated
6894 	}
6895 
6896 	glDisable(GL_RASTERIZER_DISCARD);
6897 }
6898 
6899 bool RasterizerStorageGLES3::particles_is_inactive(RID p_particles) const {
6900 
6901 	const Particles *particles = particles_owner.getornull(p_particles);
6902 	ERR_FAIL_COND_V(!particles, false);
6903 	return !particles->emitting && particles->inactive;
6904 }
6905 
6906 ////////
6907 
6908 void RasterizerStorageGLES3::instance_add_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance) {
6909 
6910 	Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
6911 	ERR_FAIL_COND(!skeleton);
6912 
6913 	skeleton->instances.insert(p_instance);
6914 }
6915 
6916 void RasterizerStorageGLES3::instance_remove_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance) {
6917 
6918 	Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
6919 	ERR_FAIL_COND(!skeleton);
6920 
6921 	skeleton->instances.erase(p_instance);
6922 }
6923 
6924 void RasterizerStorageGLES3::instance_add_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance) {
6925 
6926 	Instantiable *inst = NULL;
6927 	switch (p_instance->base_type) {
6928 		case VS::INSTANCE_MESH: {
6929 			inst = mesh_owner.getornull(p_base);
6930 			ERR_FAIL_COND(!inst);
6931 		} break;
6932 		case VS::INSTANCE_MULTIMESH: {
6933 			inst = multimesh_owner.getornull(p_base);
6934 			ERR_FAIL_COND(!inst);
6935 		} break;
6936 		case VS::INSTANCE_IMMEDIATE: {
6937 			inst = immediate_owner.getornull(p_base);
6938 			ERR_FAIL_COND(!inst);
6939 		} break;
6940 		case VS::INSTANCE_PARTICLES: {
6941 			inst = particles_owner.getornull(p_base);
6942 			ERR_FAIL_COND(!inst);
6943 		} break;
6944 		case VS::INSTANCE_REFLECTION_PROBE: {
6945 			inst = reflection_probe_owner.getornull(p_base);
6946 			ERR_FAIL_COND(!inst);
6947 		} break;
6948 		case VS::INSTANCE_LIGHT: {
6949 			inst = light_owner.getornull(p_base);
6950 			ERR_FAIL_COND(!inst);
6951 		} break;
6952 		case VS::INSTANCE_GI_PROBE: {
6953 			inst = gi_probe_owner.getornull(p_base);
6954 			ERR_FAIL_COND(!inst);
6955 		} break;
6956 		case VS::INSTANCE_LIGHTMAP_CAPTURE: {
6957 			inst = lightmap_capture_data_owner.getornull(p_base);
6958 			ERR_FAIL_COND(!inst);
6959 		} break;
6960 		default: {
6961 			ERR_FAIL();
6962 		}
6963 	}
6964 
6965 	inst->instance_list.add(&p_instance->dependency_item);
6966 }
6967 
6968 void RasterizerStorageGLES3::instance_remove_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance) {
6969 
6970 	Instantiable *inst = NULL;
6971 
6972 	switch (p_instance->base_type) {
6973 		case VS::INSTANCE_MESH: {
6974 			inst = mesh_owner.getornull(p_base);
6975 			ERR_FAIL_COND(!inst);
6976 		} break;
6977 		case VS::INSTANCE_MULTIMESH: {
6978 			inst = multimesh_owner.getornull(p_base);
6979 			ERR_FAIL_COND(!inst);
6980 		} break;
6981 		case VS::INSTANCE_IMMEDIATE: {
6982 			inst = immediate_owner.getornull(p_base);
6983 			ERR_FAIL_COND(!inst);
6984 		} break;
6985 		case VS::INSTANCE_PARTICLES: {
6986 			inst = particles_owner.getornull(p_base);
6987 			ERR_FAIL_COND(!inst);
6988 		} break;
6989 		case VS::INSTANCE_REFLECTION_PROBE: {
6990 			inst = reflection_probe_owner.getornull(p_base);
6991 			ERR_FAIL_COND(!inst);
6992 		} break;
6993 		case VS::INSTANCE_LIGHT: {
6994 			inst = light_owner.getornull(p_base);
6995 			ERR_FAIL_COND(!inst);
6996 		} break;
6997 		case VS::INSTANCE_GI_PROBE: {
6998 			inst = gi_probe_owner.getornull(p_base);
6999 			ERR_FAIL_COND(!inst);
7000 		} break;
7001 		case VS::INSTANCE_LIGHTMAP_CAPTURE: {
7002 			inst = lightmap_capture_data_owner.getornull(p_base);
7003 			ERR_FAIL_COND(!inst);
7004 		} break;
7005 		default: {
7006 			ERR_FAIL();
7007 		}
7008 	}
7009 
7010 	inst->instance_list.remove(&p_instance->dependency_item);
7011 }
7012 
7013 /* RENDER TARGET */
7014 
7015 void RasterizerStorageGLES3::_render_target_clear(RenderTarget *rt) {
7016 
7017 	if (rt->fbo) {
7018 		glDeleteFramebuffers(1, &rt->fbo);
7019 		glDeleteTextures(1, &rt->color);
7020 		rt->fbo = 0;
7021 	}
7022 
7023 	if (rt->buffers.active) {
7024 		glDeleteFramebuffers(1, &rt->buffers.fbo);
7025 		glDeleteRenderbuffers(1, &rt->buffers.depth);
7026 		glDeleteRenderbuffers(1, &rt->buffers.diffuse);
7027 		if (rt->buffers.effects_active) {
7028 			glDeleteRenderbuffers(1, &rt->buffers.specular);
7029 			glDeleteRenderbuffers(1, &rt->buffers.normal_rough);
7030 			glDeleteRenderbuffers(1, &rt->buffers.sss);
7031 			glDeleteFramebuffers(1, &rt->buffers.effect_fbo);
7032 			glDeleteTextures(1, &rt->buffers.effect);
7033 		}
7034 
7035 		rt->buffers.effects_active = false;
7036 		rt->buffers.active = false;
7037 	}
7038 
7039 	if (rt->depth) {
7040 		glDeleteTextures(1, &rt->depth);
7041 		rt->depth = 0;
7042 	}
7043 
7044 	if (rt->effects.ssao.blur_fbo[0]) {
7045 		glDeleteFramebuffers(1, &rt->effects.ssao.blur_fbo[0]);
7046 		glDeleteTextures(1, &rt->effects.ssao.blur_red[0]);
7047 		glDeleteFramebuffers(1, &rt->effects.ssao.blur_fbo[1]);
7048 		glDeleteTextures(1, &rt->effects.ssao.blur_red[1]);
7049 		for (int i = 0; i < rt->effects.ssao.depth_mipmap_fbos.size(); i++) {
7050 			glDeleteFramebuffers(1, &rt->effects.ssao.depth_mipmap_fbos[i]);
7051 		}
7052 
7053 		rt->effects.ssao.depth_mipmap_fbos.clear();
7054 
7055 		glDeleteTextures(1, &rt->effects.ssao.linear_depth);
7056 
7057 		rt->effects.ssao.blur_fbo[0] = 0;
7058 		rt->effects.ssao.blur_fbo[1] = 0;
7059 	}
7060 
7061 	if (rt->exposure.fbo) {
7062 		glDeleteFramebuffers(1, &rt->exposure.fbo);
7063 		glDeleteTextures(1, &rt->exposure.color);
7064 		rt->exposure.fbo = 0;
7065 	}
7066 
7067 	if (rt->external.fbo != 0) {
7068 		// free this
7069 		glDeleteFramebuffers(1, &rt->external.fbo);
7070 
7071 		// clean up our texture
7072 		Texture *t = texture_owner.get(rt->external.texture);
7073 		t->alloc_height = 0;
7074 		t->alloc_width = 0;
7075 		t->width = 0;
7076 		t->height = 0;
7077 		t->active = false;
7078 		texture_owner.free(rt->external.texture);
7079 		memdelete(t);
7080 
7081 		rt->external.fbo = 0;
7082 	}
7083 
7084 	Texture *tex = texture_owner.get(rt->texture);
7085 	tex->alloc_height = 0;
7086 	tex->alloc_width = 0;
7087 	tex->width = 0;
7088 	tex->height = 0;
7089 	tex->active = false;
7090 
7091 	for (int i = 0; i < 2; i++) {
7092 		if (rt->effects.mip_maps[i].color) {
7093 			for (int j = 0; j < rt->effects.mip_maps[i].sizes.size(); j++) {
7094 				glDeleteFramebuffers(1, &rt->effects.mip_maps[i].sizes[j].fbo);
7095 			}
7096 
7097 			glDeleteTextures(1, &rt->effects.mip_maps[i].color);
7098 			rt->effects.mip_maps[i].sizes.clear();
7099 			rt->effects.mip_maps[i].levels = 0;
7100 			rt->effects.mip_maps[i].color = 0;
7101 		}
7102 	}
7103 
7104 	/*
7105 	if (rt->effects.screen_space_depth) {
7106 		glDeleteTextures(1,&rt->effects.screen_space_depth);
7107 		rt->effects.screen_space_depth=0;
7108 
7109 	}
7110 */
7111 }
7112 
7113 void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt) {
7114 
7115 	if (rt->width <= 0 || rt->height <= 0)
7116 		return;
7117 
7118 	GLuint color_internal_format;
7119 	GLuint color_format;
7120 	GLuint color_type;
7121 	Image::Format image_format;
7122 
7123 	bool hdr = rt->flags[RENDER_TARGET_HDR] && config.framebuffer_half_float_supported;
7124 	//hdr = false;
7125 
7126 	if (!hdr || rt->flags[RENDER_TARGET_NO_3D]) {
7127 
7128 		if (rt->flags[RENDER_TARGET_NO_3D_EFFECTS] && !rt->flags[RENDER_TARGET_TRANSPARENT]) {
7129 			//if this is not used, linear colorspace looks pretty bad
7130 			//this is the default mode used for mobile
7131 			color_internal_format = GL_RGB10_A2;
7132 			color_format = GL_RGBA;
7133 			color_type = GL_UNSIGNED_INT_2_10_10_10_REV;
7134 			image_format = Image::FORMAT_RGBA8;
7135 		} else {
7136 
7137 			color_internal_format = GL_RGBA8;
7138 			color_format = GL_RGBA;
7139 			color_type = GL_UNSIGNED_BYTE;
7140 			image_format = Image::FORMAT_RGBA8;
7141 		}
7142 	} else {
7143 		color_internal_format = GL_RGBA16F;
7144 		color_format = GL_RGBA;
7145 		color_type = GL_HALF_FLOAT;
7146 		image_format = Image::FORMAT_RGBAH;
7147 	}
7148 
7149 	{
7150 		/* FRONT FBO */
7151 
7152 		glActiveTexture(GL_TEXTURE0);
7153 
7154 		glGenFramebuffers(1, &rt->fbo);
7155 		glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo);
7156 
7157 		glGenTextures(1, &rt->depth);
7158 		glBindTexture(GL_TEXTURE_2D, rt->depth);
7159 		glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, rt->width, rt->height, 0,
7160 				GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
7161 
7162 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
7163 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
7164 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
7165 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
7166 
7167 		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
7168 				GL_TEXTURE_2D, rt->depth, 0);
7169 
7170 		glGenTextures(1, &rt->color);
7171 		glBindTexture(GL_TEXTURE_2D, rt->color);
7172 
7173 		glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, rt->width, rt->height, 0, color_format, color_type, NULL);
7174 
7175 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
7176 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
7177 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
7178 		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
7179 		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->color, 0);
7180 
7181 		GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
7182 		glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
7183 
7184 		if (status != GL_FRAMEBUFFER_COMPLETE) {
7185 			printf("framebuffer fail, status: %x\n", status);
7186 		}
7187 
7188 		ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
7189 
7190 		Texture *tex = texture_owner.get(rt->texture);
7191 		tex->format = image_format;
7192 		tex->gl_format_cache = color_format;
7193 		tex->gl_type_cache = color_type;
7194 		tex->gl_internal_format_cache = color_internal_format;
7195 		tex->tex_id = rt->color;
7196 		tex->width = rt->width;
7197 		tex->alloc_width = rt->width;
7198 		tex->height = rt->height;
7199 		tex->alloc_height = rt->height;
7200 		tex->active = true;
7201 
7202 		texture_set_flags(rt->texture, tex->flags);
7203 	}
7204 
7205 	/* BACK FBO */
7206 
7207 	if (!rt->flags[RENDER_TARGET_NO_3D] && (!rt->flags[RENDER_TARGET_NO_3D_EFFECTS] || rt->msaa != VS::VIEWPORT_MSAA_DISABLED)) {
7208 
7209 		rt->buffers.active = true;
7210 
7211 		static const int msaa_value[] = { 0, 2, 4, 8, 16, 4, 16 }; // MSAA_EXT_nX is a GLES2 temporary hack ignored in GLES3 for now...
7212 		int msaa = msaa_value[rt->msaa];
7213 
7214 		int max_samples = 0;
7215 		glGetIntegerv(GL_MAX_SAMPLES, &max_samples);
7216 		if (msaa > max_samples) {
7217 			WARN_PRINTS("MSAA must be <= GL_MAX_SAMPLES, falling-back to GL_MAX_SAMPLES = " + itos(max_samples));
7218 			msaa = max_samples;
7219 		}
7220 
7221 		//regular fbo
7222 		glGenFramebuffers(1, &rt->buffers.fbo);
7223 		glBindFramebuffer(GL_FRAMEBUFFER, rt->buffers.fbo);
7224 
7225 		glGenRenderbuffers(1, &rt->buffers.depth);
7226 		glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.depth);
7227 		if (msaa == 0)
7228 			glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, rt->width, rt->height);
7229 		else
7230 			glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, GL_DEPTH_COMPONENT24, rt->width, rt->height);
7231 
7232 		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->buffers.depth);
7233 
7234 		glGenRenderbuffers(1, &rt->buffers.diffuse);
7235 		glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.diffuse);
7236 
7237 		if (msaa == 0)
7238 			glRenderbufferStorage(GL_RENDERBUFFER, color_internal_format, rt->width, rt->height);
7239 		else
7240 			glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, color_internal_format, rt->width, rt->height);
7241 
7242 		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rt->buffers.diffuse);
7243 
7244 		if (!rt->flags[RENDER_TARGET_NO_3D_EFFECTS]) {
7245 
7246 			rt->buffers.effects_active = true;
7247 			glGenRenderbuffers(1, &rt->buffers.specular);
7248 			glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.specular);
7249 
7250 			if (msaa == 0)
7251 				glRenderbufferStorage(GL_RENDERBUFFER, color_internal_format, rt->width, rt->height);
7252 			else
7253 				glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, color_internal_format, rt->width, rt->height);
7254 
7255 			glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_RENDERBUFFER, rt->buffers.specular);
7256 
7257 			glGenRenderbuffers(1, &rt->buffers.normal_rough);
7258 			glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.normal_rough);
7259 
7260 			if (msaa == 0)
7261 				glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, rt->width, rt->height);
7262 			else
7263 				glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, GL_RGBA8, rt->width, rt->height);
7264 
7265 			glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_RENDERBUFFER, rt->buffers.normal_rough);
7266 
7267 			glGenRenderbuffers(1, &rt->buffers.sss);
7268 			glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.sss);
7269 
7270 			if (msaa == 0)
7271 				glRenderbufferStorage(GL_RENDERBUFFER, GL_R8, rt->width, rt->height);
7272 			else
7273 				glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, GL_R8, rt->width, rt->height);
7274 
7275 			glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_RENDERBUFFER, rt->buffers.sss);
7276 
7277 			GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
7278 			glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
7279 
7280 			if (status != GL_FRAMEBUFFER_COMPLETE) {
7281 				printf("err status: %x\n", status);
7282 				_render_target_clear(rt);
7283 				ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
7284 			}
7285 
7286 			glBindRenderbuffer(GL_RENDERBUFFER, 0);
7287 
7288 			// effect resolver
7289 
7290 			glGenFramebuffers(1, &rt->buffers.effect_fbo);
7291 			glBindFramebuffer(GL_FRAMEBUFFER, rt->buffers.effect_fbo);
7292 
7293 			glGenTextures(1, &rt->buffers.effect);
7294 			glBindTexture(GL_TEXTURE_2D, rt->buffers.effect);
7295 			glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, rt->width, rt->height, 0,
7296 					color_format, color_type, NULL);
7297 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
7298 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
7299 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
7300 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
7301 			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
7302 					GL_TEXTURE_2D, rt->buffers.effect, 0);
7303 
7304 			status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
7305 			glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
7306 
7307 			if (status != GL_FRAMEBUFFER_COMPLETE) {
7308 				printf("err status: %x\n", status);
7309 				_render_target_clear(rt);
7310 				ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
7311 			}
7312 
7313 			///////////////// ssao
7314 
7315 			//AO strength textures
7316 			for (int i = 0; i < 2; i++) {
7317 
7318 				glGenFramebuffers(1, &rt->effects.ssao.blur_fbo[i]);
7319 				glBindFramebuffer(GL_FRAMEBUFFER, rt->effects.ssao.blur_fbo[i]);
7320 				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
7321 						GL_TEXTURE_2D, rt->depth, 0);
7322 
7323 				glGenTextures(1, &rt->effects.ssao.blur_red[i]);
7324 				glBindTexture(GL_TEXTURE_2D, rt->effects.ssao.blur_red[i]);
7325 
7326 				glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, rt->width, rt->height, 0, GL_RED, GL_UNSIGNED_BYTE, NULL);
7327 				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
7328 				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
7329 				glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
7330 				glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
7331 
7332 				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->effects.ssao.blur_red[i], 0);
7333 
7334 				status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
7335 				if (status != GL_FRAMEBUFFER_COMPLETE) {
7336 					_render_target_clear(rt);
7337 					ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
7338 				}
7339 			}
7340 			//5 mip levels for depth texture, but base is read separately
7341 
7342 			glGenTextures(1, &rt->effects.ssao.linear_depth);
7343 			glBindTexture(GL_TEXTURE_2D, rt->effects.ssao.linear_depth);
7344 
7345 			int ssao_w = rt->width / 2;
7346 			int ssao_h = rt->height / 2;
7347 
7348 			for (int i = 0; i < 4; i++) { //5, but 4 mips, base is read directly to save bw
7349 
7350 				glTexImage2D(GL_TEXTURE_2D, i, GL_R16UI, ssao_w, ssao_h, 0, GL_RED_INTEGER, GL_UNSIGNED_SHORT, NULL);
7351 				ssao_w >>= 1;
7352 				ssao_h >>= 1;
7353 			}
7354 
7355 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
7356 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
7357 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
7358 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
7359 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
7360 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 3);
7361 
7362 			for (int i = 0; i < 4; i++) { //5, but 4 mips, base is read directly to save bw
7363 
7364 				GLuint fbo;
7365 				glGenFramebuffers(1, &fbo);
7366 				glBindFramebuffer(GL_FRAMEBUFFER, fbo);
7367 				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->effects.ssao.linear_depth, i);
7368 				rt->effects.ssao.depth_mipmap_fbos.push_back(fbo);
7369 			}
7370 
7371 			//////Exposure
7372 
7373 			glGenFramebuffers(1, &rt->exposure.fbo);
7374 			glBindFramebuffer(GL_FRAMEBUFFER, rt->exposure.fbo);
7375 
7376 			glGenTextures(1, &rt->exposure.color);
7377 			glBindTexture(GL_TEXTURE_2D, rt->exposure.color);
7378 			if (config.framebuffer_float_supported) {
7379 				glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 1, 1, 0, GL_RED, GL_FLOAT, NULL);
7380 			} else if (config.framebuffer_half_float_supported) {
7381 				glTexImage2D(GL_TEXTURE_2D, 0, GL_R16F, 1, 1, 0, GL_RED, GL_HALF_FLOAT, NULL);
7382 			} else {
7383 				glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, NULL);
7384 			}
7385 
7386 			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->exposure.color, 0);
7387 
7388 			status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
7389 			if (status != GL_FRAMEBUFFER_COMPLETE) {
7390 				_render_target_clear(rt);
7391 				ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
7392 			}
7393 		} else {
7394 			rt->buffers.effects_active = false;
7395 		}
7396 	} else {
7397 		rt->buffers.active = false;
7398 		rt->buffers.effects_active = true;
7399 	}
7400 
7401 	if (!rt->flags[RENDER_TARGET_NO_SAMPLING] && rt->width >= 2 && rt->height >= 2) {
7402 
7403 		for (int i = 0; i < 2; i++) {
7404 
7405 			ERR_FAIL_COND(rt->effects.mip_maps[i].sizes.size());
7406 			int w = rt->width;
7407 			int h = rt->height;
7408 
7409 			if (i > 0) {
7410 				w >>= 1;
7411 				h >>= 1;
7412 			}
7413 
7414 			glGenTextures(1, &rt->effects.mip_maps[i].color);
7415 			glBindTexture(GL_TEXTURE_2D, rt->effects.mip_maps[i].color);
7416 
7417 			int level = 0;
7418 			int fb_w = w;
7419 			int fb_h = h;
7420 
7421 			while (true) {
7422 
7423 				RenderTarget::Effects::MipMaps::Size mm;
7424 				mm.width = w;
7425 				mm.height = h;
7426 				rt->effects.mip_maps[i].sizes.push_back(mm);
7427 
7428 				w >>= 1;
7429 				h >>= 1;
7430 
7431 				if (w < 2 || h < 2)
7432 					break;
7433 
7434 				level++;
7435 			}
7436 
7437 			glTexStorage2DCustom(GL_TEXTURE_2D, level + 1, color_internal_format, fb_w, fb_h, color_format, color_type);
7438 
7439 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
7440 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, level);
7441 			glDisable(GL_SCISSOR_TEST);
7442 			glColorMask(1, 1, 1, 1);
7443 			if (!rt->buffers.active) {
7444 				glDepthMask(GL_TRUE);
7445 			}
7446 
7447 			for (int j = 0; j < rt->effects.mip_maps[i].sizes.size(); j++) {
7448 
7449 				RenderTarget::Effects::MipMaps::Size &mm = rt->effects.mip_maps[i].sizes.write[j];
7450 
7451 				glGenFramebuffers(1, &mm.fbo);
7452 				glBindFramebuffer(GL_FRAMEBUFFER, mm.fbo);
7453 				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->effects.mip_maps[i].color, j);
7454 				bool used_depth = false;
7455 				if (j == 0 && i == 0) { //use always
7456 					glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rt->depth, 0);
7457 					used_depth = true;
7458 				}
7459 
7460 				GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
7461 				if (status != GL_FRAMEBUFFER_COMPLETE) {
7462 					_render_target_clear(rt);
7463 					ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
7464 				}
7465 
7466 				float zero[4] = { 1, 0, 1, 0 };
7467 				glViewport(0, 0, rt->effects.mip_maps[i].sizes[j].width, rt->effects.mip_maps[i].sizes[j].height);
7468 				glClearBufferfv(GL_COLOR, 0, zero);
7469 				if (used_depth) {
7470 					glClearDepth(1.0);
7471 					glClear(GL_DEPTH_BUFFER_BIT);
7472 				}
7473 			}
7474 
7475 			glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
7476 			rt->effects.mip_maps[i].levels = level;
7477 
7478 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
7479 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
7480 			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
7481 			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
7482 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
7483 			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
7484 		}
7485 	}
7486 }
7487 
7488 RID RasterizerStorageGLES3::render_target_create() {
7489 
7490 	RenderTarget *rt = memnew(RenderTarget);
7491 
7492 	Texture *t = memnew(Texture);
7493 
7494 	t->type = VS::TEXTURE_TYPE_2D;
7495 	t->flags = 0;
7496 	t->width = 0;
7497 	t->height = 0;
7498 	t->alloc_height = 0;
7499 	t->alloc_width = 0;
7500 	t->format = Image::FORMAT_R8;
7501 	t->target = GL_TEXTURE_2D;
7502 	t->gl_format_cache = 0;
7503 	t->gl_internal_format_cache = 0;
7504 	t->gl_type_cache = 0;
7505 	t->data_size = 0;
7506 	t->compressed = false;
7507 	t->srgb = false;
7508 	t->total_data_size = 0;
7509 	t->ignore_mipmaps = false;
7510 	t->mipmaps = 1;
7511 	t->active = true;
7512 	t->tex_id = 0;
7513 	t->render_target = rt;
7514 
7515 	rt->texture = texture_owner.make_rid(t);
7516 
7517 	return render_target_owner.make_rid(rt);
7518 }
7519 
7520 void RasterizerStorageGLES3::render_target_set_position(RID p_render_target, int p_x, int p_y) {
7521 	//only used in GLES2
7522 }
7523 
7524 void RasterizerStorageGLES3::render_target_set_size(RID p_render_target, int p_width, int p_height) {
7525 
7526 	RenderTarget *rt = render_target_owner.getornull(p_render_target);
7527 	ERR_FAIL_COND(!rt);
7528 
7529 	if (rt->width == p_width && rt->height == p_height)
7530 		return;
7531 
7532 	_render_target_clear(rt);
7533 	rt->width = p_width;
7534 	rt->height = p_height;
7535 	_render_target_allocate(rt);
7536 }
7537 
7538 RID RasterizerStorageGLES3::render_target_get_texture(RID p_render_target) const {
7539 
7540 	RenderTarget *rt = render_target_owner.getornull(p_render_target);
7541 	ERR_FAIL_COND_V(!rt, RID());
7542 
7543 	if (rt->external.fbo == 0) {
7544 		return rt->texture;
7545 	} else {
7546 		return rt->external.texture;
7547 	}
7548 }
7549 
7550 void RasterizerStorageGLES3::render_target_set_external_texture(RID p_render_target, unsigned int p_texture_id) {
7551 	RenderTarget *rt = render_target_owner.getornull(p_render_target);
7552 	ERR_FAIL_COND(!rt);
7553 
7554 	if (p_texture_id == 0) {
7555 		if (rt->external.fbo != 0) {
7556 			// free this
7557 			glDeleteFramebuffers(1, &rt->external.fbo);
7558 
7559 			// clean up our texture
7560 			Texture *t = texture_owner.get(rt->external.texture);
7561 			t->alloc_height = 0;
7562 			t->alloc_width = 0;
7563 			t->width = 0;
7564 			t->height = 0;
7565 			t->active = false;
7566 			texture_owner.free(rt->external.texture);
7567 			memdelete(t);
7568 
7569 			rt->external.fbo = 0;
7570 		}
7571 	} else {
7572 		Texture *t;
7573 
7574 		if (rt->external.fbo == 0) {
7575 			// create our fbo
7576 			glGenFramebuffers(1, &rt->external.fbo);
7577 			glBindFramebuffer(GL_FRAMEBUFFER, rt->external.fbo);
7578 
7579 			// allocate a texture
7580 			t = memnew(Texture);
7581 
7582 			t->type = VS::TEXTURE_TYPE_2D;
7583 			t->flags = 0;
7584 			t->width = 0;
7585 			t->height = 0;
7586 			t->alloc_height = 0;
7587 			t->alloc_width = 0;
7588 			t->format = Image::FORMAT_RGBA8;
7589 			t->target = GL_TEXTURE_2D;
7590 			t->gl_format_cache = 0;
7591 			t->gl_internal_format_cache = 0;
7592 			t->gl_type_cache = 0;
7593 			t->data_size = 0;
7594 			t->compressed = false;
7595 			t->srgb = false;
7596 			t->total_data_size = 0;
7597 			t->ignore_mipmaps = false;
7598 			t->mipmaps = 1;
7599 			t->active = true;
7600 			t->tex_id = 0;
7601 			t->render_target = rt;
7602 
7603 			rt->external.texture = texture_owner.make_rid(t);
7604 		} else {
7605 			// bind our frame buffer
7606 			glBindFramebuffer(GL_FRAMEBUFFER, rt->external.fbo);
7607 
7608 			// find our texture
7609 			t = texture_owner.get(rt->external.texture);
7610 		}
7611 
7612 		// set our texture
7613 		t->tex_id = p_texture_id;
7614 
7615 		// size shouldn't be different
7616 		t->width = rt->width;
7617 		t->height = rt->height;
7618 		t->alloc_height = rt->width;
7619 		t->alloc_width = rt->height;
7620 
7621 		// is there a point to setting the internal formats? we don't know them..
7622 
7623 		// set our texture as the destination for our framebuffer
7624 		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, p_texture_id, 0);
7625 
7626 		// check status and unbind
7627 		GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
7628 		glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
7629 
7630 		if (status != GL_FRAMEBUFFER_COMPLETE) {
7631 			printf("framebuffer fail, status: %x\n", status);
7632 		}
7633 
7634 		ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
7635 	}
7636 }
7637 
7638 void RasterizerStorageGLES3::render_target_set_flag(RID p_render_target, RenderTargetFlags p_flag, bool p_value) {
7639 
7640 	RenderTarget *rt = render_target_owner.getornull(p_render_target);
7641 	ERR_FAIL_COND(!rt);
7642 
7643 	rt->flags[p_flag] = p_value;
7644 
7645 	switch (p_flag) {
7646 		case RENDER_TARGET_HDR:
7647 		case RENDER_TARGET_NO_3D:
7648 		case RENDER_TARGET_NO_SAMPLING:
7649 		case RENDER_TARGET_NO_3D_EFFECTS: {
7650 			//must reset for these formats
7651 			_render_target_clear(rt);
7652 			_render_target_allocate(rt);
7653 
7654 		} break;
7655 		default: {
7656 		}
7657 	}
7658 }
7659 bool RasterizerStorageGLES3::render_target_was_used(RID p_render_target) {
7660 
7661 	RenderTarget *rt = render_target_owner.getornull(p_render_target);
7662 	ERR_FAIL_COND_V(!rt, false);
7663 
7664 	return rt->used_in_frame;
7665 }
7666 
7667 void RasterizerStorageGLES3::render_target_clear_used(RID p_render_target) {
7668 
7669 	RenderTarget *rt = render_target_owner.getornull(p_render_target);
7670 	ERR_FAIL_COND(!rt);
7671 
7672 	rt->used_in_frame = false;
7673 }
7674 
7675 void RasterizerStorageGLES3::render_target_set_msaa(RID p_render_target, VS::ViewportMSAA p_msaa) {
7676 
7677 	RenderTarget *rt = render_target_owner.getornull(p_render_target);
7678 	ERR_FAIL_COND(!rt);
7679 
7680 	if (rt->msaa == p_msaa)
7681 		return;
7682 
7683 	_render_target_clear(rt);
7684 	rt->msaa = p_msaa;
7685 	_render_target_allocate(rt);
7686 }
7687 
7688 /* CANVAS SHADOW */
7689 
7690 RID RasterizerStorageGLES3::canvas_light_shadow_buffer_create(int p_width) {
7691 
7692 	CanvasLightShadow *cls = memnew(CanvasLightShadow);
7693 	if (p_width > config.max_texture_size)
7694 		p_width = config.max_texture_size;
7695 
7696 	cls->size = p_width;
7697 	cls->height = 16;
7698 
7699 	glActiveTexture(GL_TEXTURE0);
7700 
7701 	glGenFramebuffers(1, &cls->fbo);
7702 	glBindFramebuffer(GL_FRAMEBUFFER, cls->fbo);
7703 
7704 	glGenRenderbuffers(1, &cls->depth);
7705 	glBindRenderbuffer(GL_RENDERBUFFER, cls->depth);
7706 	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, cls->size, cls->height);
7707 	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, cls->depth);
7708 	glBindRenderbuffer(GL_RENDERBUFFER, 0);
7709 
7710 	glGenTextures(1, &cls->distance);
7711 	glBindTexture(GL_TEXTURE_2D, cls->distance);
7712 	if (config.use_rgba_2d_shadows) {
7713 		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cls->size, cls->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
7714 	} else {
7715 		glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, cls->size, cls->height, 0, GL_RED, GL_FLOAT, NULL);
7716 	}
7717 
7718 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
7719 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
7720 	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
7721 	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
7722 	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cls->distance, 0);
7723 
7724 	GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
7725 	//printf("errnum: %x\n",status);
7726 	glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
7727 
7728 	if (status != GL_FRAMEBUFFER_COMPLETE) {
7729 		memdelete(cls);
7730 		ERR_FAIL_COND_V(status != GL_FRAMEBUFFER_COMPLETE, RID());
7731 	}
7732 
7733 	return canvas_light_shadow_owner.make_rid(cls);
7734 }
7735 
7736 /* LIGHT SHADOW MAPPING */
7737 
7738 RID RasterizerStorageGLES3::canvas_light_occluder_create() {
7739 
7740 	CanvasOccluder *co = memnew(CanvasOccluder);
7741 	co->index_id = 0;
7742 	co->vertex_id = 0;
7743 	co->len = 0;
7744 	glGenVertexArrays(1, &co->array_id);
7745 
7746 	return canvas_occluder_owner.make_rid(co);
7747 }
7748 
7749 void RasterizerStorageGLES3::canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2> &p_lines) {
7750 
7751 	CanvasOccluder *co = canvas_occluder_owner.get(p_occluder);
7752 	ERR_FAIL_COND(!co);
7753 
7754 	co->lines = p_lines;
7755 
7756 	if (p_lines.size() != co->len) {
7757 
7758 		if (co->index_id)
7759 			glDeleteBuffers(1, &co->index_id);
7760 		if (co->vertex_id)
7761 			glDeleteBuffers(1, &co->vertex_id);
7762 
7763 		co->index_id = 0;
7764 		co->vertex_id = 0;
7765 		co->len = 0;
7766 	}
7767 
7768 	if (p_lines.size()) {
7769 
7770 		PoolVector<float> geometry;
7771 		PoolVector<uint16_t> indices;
7772 		int lc = p_lines.size();
7773 
7774 		geometry.resize(lc * 6);
7775 		indices.resize(lc * 3);
7776 
7777 		PoolVector<float>::Write vw = geometry.write();
7778 		PoolVector<uint16_t>::Write iw = indices.write();
7779 
7780 		PoolVector<Vector2>::Read lr = p_lines.read();
7781 
7782 		const int POLY_HEIGHT = 16384;
7783 
7784 		for (int i = 0; i < lc / 2; i++) {
7785 
7786 			vw[i * 12 + 0] = lr[i * 2 + 0].x;
7787 			vw[i * 12 + 1] = lr[i * 2 + 0].y;
7788 			vw[i * 12 + 2] = POLY_HEIGHT;
7789 
7790 			vw[i * 12 + 3] = lr[i * 2 + 1].x;
7791 			vw[i * 12 + 4] = lr[i * 2 + 1].y;
7792 			vw[i * 12 + 5] = POLY_HEIGHT;
7793 
7794 			vw[i * 12 + 6] = lr[i * 2 + 1].x;
7795 			vw[i * 12 + 7] = lr[i * 2 + 1].y;
7796 			vw[i * 12 + 8] = -POLY_HEIGHT;
7797 
7798 			vw[i * 12 + 9] = lr[i * 2 + 0].x;
7799 			vw[i * 12 + 10] = lr[i * 2 + 0].y;
7800 			vw[i * 12 + 11] = -POLY_HEIGHT;
7801 
7802 			iw[i * 6 + 0] = i * 4 + 0;
7803 			iw[i * 6 + 1] = i * 4 + 1;
7804 			iw[i * 6 + 2] = i * 4 + 2;
7805 
7806 			iw[i * 6 + 3] = i * 4 + 2;
7807 			iw[i * 6 + 4] = i * 4 + 3;
7808 			iw[i * 6 + 5] = i * 4 + 0;
7809 		}
7810 
7811 		//if same buffer len is being set, just use BufferSubData to avoid a pipeline flush
7812 
7813 		if (!co->vertex_id) {
7814 			glGenBuffers(1, &co->vertex_id);
7815 			glBindBuffer(GL_ARRAY_BUFFER, co->vertex_id);
7816 			glBufferData(GL_ARRAY_BUFFER, lc * 6 * sizeof(real_t), vw.ptr(), GL_STATIC_DRAW);
7817 		} else {
7818 
7819 			glBindBuffer(GL_ARRAY_BUFFER, co->vertex_id);
7820 			glBufferSubData(GL_ARRAY_BUFFER, 0, lc * 6 * sizeof(real_t), vw.ptr());
7821 		}
7822 
7823 		glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
7824 
7825 		if (!co->index_id) {
7826 
7827 			glGenBuffers(1, &co->index_id);
7828 			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, co->index_id);
7829 			glBufferData(GL_ELEMENT_ARRAY_BUFFER, lc * 3 * sizeof(uint16_t), iw.ptr(), GL_DYNAMIC_DRAW);
7830 		} else {
7831 
7832 			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, co->index_id);
7833 			glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, lc * 3 * sizeof(uint16_t), iw.ptr());
7834 		}
7835 
7836 		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
7837 
7838 		co->len = lc;
7839 		glBindVertexArray(co->array_id);
7840 		glBindBuffer(GL_ARRAY_BUFFER, co->vertex_id);
7841 		glEnableVertexAttribArray(VS::ARRAY_VERTEX);
7842 		glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false, 0, 0);
7843 		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, co->index_id);
7844 		glBindVertexArray(0);
7845 	}
7846 }
7847 
7848 VS::InstanceType RasterizerStorageGLES3::get_base_type(RID p_rid) const {
7849 
7850 	if (mesh_owner.owns(p_rid)) {
7851 		return VS::INSTANCE_MESH;
7852 	}
7853 
7854 	if (multimesh_owner.owns(p_rid)) {
7855 		return VS::INSTANCE_MULTIMESH;
7856 	}
7857 
7858 	if (immediate_owner.owns(p_rid)) {
7859 		return VS::INSTANCE_IMMEDIATE;
7860 	}
7861 
7862 	if (particles_owner.owns(p_rid)) {
7863 		return VS::INSTANCE_PARTICLES;
7864 	}
7865 
7866 	if (light_owner.owns(p_rid)) {
7867 		return VS::INSTANCE_LIGHT;
7868 	}
7869 
7870 	if (reflection_probe_owner.owns(p_rid)) {
7871 		return VS::INSTANCE_REFLECTION_PROBE;
7872 	}
7873 
7874 	if (gi_probe_owner.owns(p_rid)) {
7875 		return VS::INSTANCE_GI_PROBE;
7876 	}
7877 
7878 	if (lightmap_capture_data_owner.owns(p_rid)) {
7879 		return VS::INSTANCE_LIGHTMAP_CAPTURE;
7880 	}
7881 
7882 	return VS::INSTANCE_NONE;
7883 }
7884 
7885 bool RasterizerStorageGLES3::free(RID p_rid) {
7886 
7887 	if (render_target_owner.owns(p_rid)) {
7888 
7889 		RenderTarget *rt = render_target_owner.getornull(p_rid);
7890 		_render_target_clear(rt);
7891 		Texture *t = texture_owner.get(rt->texture);
7892 		texture_owner.free(rt->texture);
7893 		memdelete(t);
7894 		render_target_owner.free(p_rid);
7895 		memdelete(rt);
7896 
7897 	} else if (texture_owner.owns(p_rid)) {
7898 		// delete the texture
7899 		Texture *texture = texture_owner.get(p_rid);
7900 		ERR_FAIL_COND_V(texture->render_target, true); //can't free the render target texture, dude
7901 		info.texture_mem -= texture->total_data_size;
7902 		texture_owner.free(p_rid);
7903 		memdelete(texture);
7904 
7905 	} else if (sky_owner.owns(p_rid)) {
7906 		// delete the sky
7907 		Sky *sky = sky_owner.get(p_rid);
7908 		sky_set_texture(p_rid, RID(), 256);
7909 		sky_owner.free(p_rid);
7910 		memdelete(sky);
7911 
7912 	} else if (shader_owner.owns(p_rid)) {
7913 
7914 		// delete the texture
7915 		Shader *shader = shader_owner.get(p_rid);
7916 
7917 		if (shader->shader && shader->custom_code_id)
7918 			shader->shader->free_custom_shader(shader->custom_code_id);
7919 
7920 		if (shader->dirty_list.in_list())
7921 			_shader_dirty_list.remove(&shader->dirty_list);
7922 
7923 		while (shader->materials.first()) {
7924 
7925 			Material *mat = shader->materials.first()->self();
7926 
7927 			mat->shader = NULL;
7928 			_material_make_dirty(mat);
7929 
7930 			shader->materials.remove(shader->materials.first());
7931 		}
7932 
7933 		//material_shader.free_custom_shader(shader->custom_code_id);
7934 		shader_owner.free(p_rid);
7935 		memdelete(shader);
7936 
7937 	} else if (material_owner.owns(p_rid)) {
7938 
7939 		// delete the texture
7940 		Material *material = material_owner.get(p_rid);
7941 
7942 		if (material->shader) {
7943 			material->shader->materials.remove(&material->list);
7944 		}
7945 
7946 		if (material->ubo_id) {
7947 			glDeleteBuffers(1, &material->ubo_id);
7948 		}
7949 
7950 		//remove from owners
7951 		for (Map<Geometry *, int>::Element *E = material->geometry_owners.front(); E; E = E->next()) {
7952 
7953 			Geometry *g = E->key();
7954 			g->material = RID();
7955 		}
7956 		for (Map<RasterizerScene::InstanceBase *, int>::Element *E = material->instance_owners.front(); E; E = E->next()) {
7957 			RasterizerScene::InstanceBase *ins = E->key();
7958 			if (ins->material_override == p_rid) {
7959 				ins->material_override = RID();
7960 			}
7961 
7962 			for (int i = 0; i < ins->materials.size(); i++) {
7963 				if (ins->materials[i] == p_rid) {
7964 					ins->materials.write[i] = RID();
7965 				}
7966 			}
7967 		}
7968 
7969 		material_owner.free(p_rid);
7970 		memdelete(material);
7971 
7972 	} else if (skeleton_owner.owns(p_rid)) {
7973 
7974 		// delete the texture
7975 		Skeleton *skeleton = skeleton_owner.get(p_rid);
7976 		if (skeleton->update_list.in_list()) {
7977 			skeleton_update_list.remove(&skeleton->update_list);
7978 		}
7979 
7980 		for (Set<RasterizerScene::InstanceBase *>::Element *E = skeleton->instances.front(); E; E = E->next()) {
7981 			E->get()->skeleton = RID();
7982 		}
7983 
7984 		skeleton_allocate(p_rid, 0, false);
7985 
7986 		glDeleteTextures(1, &skeleton->texture);
7987 		skeleton_owner.free(p_rid);
7988 		memdelete(skeleton);
7989 
7990 	} else if (mesh_owner.owns(p_rid)) {
7991 
7992 		// delete the texture
7993 		Mesh *mesh = mesh_owner.get(p_rid);
7994 		mesh->instance_remove_deps();
7995 		mesh_clear(p_rid);
7996 
7997 		while (mesh->multimeshes.first()) {
7998 			MultiMesh *multimesh = mesh->multimeshes.first()->self();
7999 			multimesh->mesh = RID();
8000 			multimesh->dirty_aabb = true;
8001 			mesh->multimeshes.remove(mesh->multimeshes.first());
8002 
8003 			if (!multimesh->update_list.in_list()) {
8004 				multimesh_update_list.add(&multimesh->update_list);
8005 			}
8006 		}
8007 
8008 		mesh_owner.free(p_rid);
8009 		memdelete(mesh);
8010 
8011 	} else if (multimesh_owner.owns(p_rid)) {
8012 
8013 		// delete the texture
8014 		MultiMesh *multimesh = multimesh_owner.get(p_rid);
8015 		multimesh->instance_remove_deps();
8016 
8017 		if (multimesh->mesh.is_valid()) {
8018 			Mesh *mesh = mesh_owner.getornull(multimesh->mesh);
8019 			if (mesh) {
8020 				mesh->multimeshes.remove(&multimesh->mesh_list);
8021 			}
8022 		}
8023 
8024 		multimesh_allocate(p_rid, 0, VS::MULTIMESH_TRANSFORM_2D, VS::MULTIMESH_COLOR_NONE); //frees multimesh
8025 		update_dirty_multimeshes();
8026 
8027 		multimesh_owner.free(p_rid);
8028 		memdelete(multimesh);
8029 	} else if (immediate_owner.owns(p_rid)) {
8030 
8031 		Immediate *immediate = immediate_owner.get(p_rid);
8032 		immediate->instance_remove_deps();
8033 
8034 		immediate_owner.free(p_rid);
8035 		memdelete(immediate);
8036 	} else if (light_owner.owns(p_rid)) {
8037 
8038 		// delete the texture
8039 		Light *light = light_owner.get(p_rid);
8040 		light->instance_remove_deps();
8041 
8042 		light_owner.free(p_rid);
8043 		memdelete(light);
8044 
8045 	} else if (reflection_probe_owner.owns(p_rid)) {
8046 
8047 		// delete the texture
8048 		ReflectionProbe *reflection_probe = reflection_probe_owner.get(p_rid);
8049 		reflection_probe->instance_remove_deps();
8050 
8051 		reflection_probe_owner.free(p_rid);
8052 		memdelete(reflection_probe);
8053 
8054 	} else if (gi_probe_owner.owns(p_rid)) {
8055 
8056 		// delete the texture
8057 		GIProbe *gi_probe = gi_probe_owner.get(p_rid);
8058 		gi_probe->instance_remove_deps();
8059 
8060 		gi_probe_owner.free(p_rid);
8061 		memdelete(gi_probe);
8062 	} else if (gi_probe_data_owner.owns(p_rid)) {
8063 
8064 		// delete the texture
8065 		GIProbeData *gi_probe_data = gi_probe_data_owner.get(p_rid);
8066 
8067 		glDeleteTextures(1, &gi_probe_data->tex_id);
8068 		gi_probe_data_owner.free(p_rid);
8069 		memdelete(gi_probe_data);
8070 	} else if (lightmap_capture_data_owner.owns(p_rid)) {
8071 
8072 		// delete the texture
8073 		LightmapCapture *lightmap_capture = lightmap_capture_data_owner.get(p_rid);
8074 		lightmap_capture->instance_remove_deps();
8075 
8076 		lightmap_capture_data_owner.free(p_rid);
8077 		memdelete(lightmap_capture);
8078 
8079 	} else if (canvas_occluder_owner.owns(p_rid)) {
8080 
8081 		CanvasOccluder *co = canvas_occluder_owner.get(p_rid);
8082 		if (co->index_id)
8083 			glDeleteBuffers(1, &co->index_id);
8084 		if (co->vertex_id)
8085 			glDeleteBuffers(1, &co->vertex_id);
8086 
8087 		glDeleteVertexArrays(1, &co->array_id);
8088 
8089 		canvas_occluder_owner.free(p_rid);
8090 		memdelete(co);
8091 
8092 	} else if (canvas_light_shadow_owner.owns(p_rid)) {
8093 
8094 		CanvasLightShadow *cls = canvas_light_shadow_owner.get(p_rid);
8095 		glDeleteFramebuffers(1, &cls->fbo);
8096 		glDeleteRenderbuffers(1, &cls->depth);
8097 		glDeleteTextures(1, &cls->distance);
8098 		canvas_light_shadow_owner.free(p_rid);
8099 		memdelete(cls);
8100 	} else if (particles_owner.owns(p_rid)) {
8101 		Particles *particles = particles_owner.get(p_rid);
8102 		particles->instance_remove_deps();
8103 		particles_owner.free(p_rid);
8104 		memdelete(particles);
8105 	} else {
8106 		return false;
8107 	}
8108 
8109 	return true;
8110 }
8111 
8112 bool RasterizerStorageGLES3::has_os_feature(const String &p_feature) const {
8113 
8114 	if (p_feature == "bptc")
8115 		return config.bptc_supported;
8116 
8117 	if (p_feature == "s3tc")
8118 		return config.s3tc_supported;
8119 
8120 	if (p_feature == "etc")
8121 		return config.etc_supported;
8122 
8123 	if (p_feature == "etc2")
8124 		return config.etc2_supported;
8125 
8126 	if (p_feature == "pvrtc")
8127 		return config.pvrtc_supported;
8128 
8129 	return false;
8130 }
8131 
8132 ////////////////////////////////////////////
8133 
8134 void RasterizerStorageGLES3::set_debug_generate_wireframes(bool p_generate) {
8135 
8136 	config.generate_wireframes = p_generate;
8137 }
8138 
8139 void RasterizerStorageGLES3::render_info_begin_capture() {
8140 
8141 	info.snap = info.render;
8142 }
8143 
8144 void RasterizerStorageGLES3::render_info_end_capture() {
8145 
8146 	info.snap.object_count = info.render.object_count - info.snap.object_count;
8147 	info.snap.draw_call_count = info.render.draw_call_count - info.snap.draw_call_count;
8148 	info.snap.material_switch_count = info.render.material_switch_count - info.snap.material_switch_count;
8149 	info.snap.surface_switch_count = info.render.surface_switch_count - info.snap.surface_switch_count;
8150 	info.snap.shader_rebind_count = info.render.shader_rebind_count - info.snap.shader_rebind_count;
8151 	info.snap.vertices_count = info.render.vertices_count - info.snap.vertices_count;
8152 	info.snap._2d_item_count = info.render._2d_item_count - info.snap._2d_item_count;
8153 	info.snap._2d_draw_call_count = info.render._2d_draw_call_count - info.snap._2d_draw_call_count;
8154 }
8155 
8156 int RasterizerStorageGLES3::get_captured_render_info(VS::RenderInfo p_info) {
8157 
8158 	switch (p_info) {
8159 		case VS::INFO_OBJECTS_IN_FRAME: {
8160 
8161 			return info.snap.object_count;
8162 		} break;
8163 		case VS::INFO_VERTICES_IN_FRAME: {
8164 
8165 			return info.snap.vertices_count;
8166 		} break;
8167 		case VS::INFO_MATERIAL_CHANGES_IN_FRAME: {
8168 			return info.snap.material_switch_count;
8169 		} break;
8170 		case VS::INFO_SHADER_CHANGES_IN_FRAME: {
8171 			return info.snap.shader_rebind_count;
8172 		} break;
8173 		case VS::INFO_SURFACE_CHANGES_IN_FRAME: {
8174 			return info.snap.surface_switch_count;
8175 		} break;
8176 		case VS::INFO_DRAW_CALLS_IN_FRAME: {
8177 			return info.snap.draw_call_count;
8178 		} break;
8179 		case VS::INFO_2D_ITEMS_IN_FRAME: {
8180 			return info.snap._2d_item_count;
8181 		} break;
8182 		case VS::INFO_2D_DRAW_CALLS_IN_FRAME: {
8183 			return info.snap._2d_draw_call_count;
8184 		} break;
8185 		default: {
8186 			return get_render_info(p_info);
8187 		}
8188 	}
8189 }
8190 
8191 int RasterizerStorageGLES3::get_render_info(VS::RenderInfo p_info) {
8192 
8193 	switch (p_info) {
8194 		case VS::INFO_OBJECTS_IN_FRAME:
8195 			return info.render_final.object_count;
8196 		case VS::INFO_VERTICES_IN_FRAME:
8197 			return info.render_final.vertices_count;
8198 		case VS::INFO_MATERIAL_CHANGES_IN_FRAME:
8199 			return info.render_final.material_switch_count;
8200 		case VS::INFO_SHADER_CHANGES_IN_FRAME:
8201 			return info.render_final.shader_rebind_count;
8202 		case VS::INFO_SURFACE_CHANGES_IN_FRAME:
8203 			return info.render_final.surface_switch_count;
8204 		case VS::INFO_DRAW_CALLS_IN_FRAME:
8205 			return info.render_final.draw_call_count;
8206 		case VS::INFO_2D_ITEMS_IN_FRAME:
8207 			return info.render_final._2d_item_count;
8208 		case VS::INFO_2D_DRAW_CALLS_IN_FRAME:
8209 			return info.render_final._2d_draw_call_count;
8210 		case VS::INFO_USAGE_VIDEO_MEM_TOTAL:
8211 			return 0; //no idea
8212 		case VS::INFO_VIDEO_MEM_USED:
8213 			return info.vertex_mem + info.texture_mem;
8214 		case VS::INFO_TEXTURE_MEM_USED:
8215 			return info.texture_mem;
8216 		case VS::INFO_VERTEX_MEM_USED:
8217 			return info.vertex_mem;
8218 		default:
8219 			return 0; //no idea either
8220 	}
8221 }
8222 
8223 String RasterizerStorageGLES3::get_video_adapter_name() const {
8224 
8225 	return (const char *)glGetString(GL_RENDERER);
8226 }
8227 
8228 String RasterizerStorageGLES3::get_video_adapter_vendor() const {
8229 
8230 	return (const char *)glGetString(GL_VENDOR);
8231 }
8232 
8233 void RasterizerStorageGLES3::initialize() {
8234 
8235 	RasterizerStorageGLES3::system_fbo = 0;
8236 
8237 	//// extensions config
8238 	///
8239 
8240 	{
8241 
8242 		int max_extensions = 0;
8243 		glGetIntegerv(GL_NUM_EXTENSIONS, &max_extensions);
8244 		for (int i = 0; i < max_extensions; i++) {
8245 			const GLubyte *s = glGetStringi(GL_EXTENSIONS, i);
8246 			if (!s)
8247 				break;
8248 			config.extensions.insert((const char *)s);
8249 		}
8250 	}
8251 
8252 	config.shrink_textures_x2 = false;
8253 	config.use_fast_texture_filter = int(ProjectSettings::get_singleton()->get("rendering/quality/filters/use_nearest_mipmap_filter"));
8254 	config.use_anisotropic_filter = config.extensions.has("rendering/quality/filters/anisotropic_filter_level");
8255 
8256 	config.etc_supported = config.extensions.has("GL_OES_compressed_ETC1_RGB8_texture");
8257 	config.latc_supported = config.extensions.has("GL_EXT_texture_compression_latc");
8258 	config.bptc_supported = config.extensions.has("GL_ARB_texture_compression_bptc");
8259 #ifdef GLES_OVER_GL
8260 	config.etc2_supported = false;
8261 	config.s3tc_supported = true;
8262 	config.rgtc_supported = true; //RGTC - core since OpenGL version 3.0
8263 	config.texture_float_linear_supported = true;
8264 	config.framebuffer_float_supported = true;
8265 	config.framebuffer_half_float_supported = true;
8266 
8267 #else
8268 	config.etc2_supported = true;
8269 	config.s3tc_supported = config.extensions.has("GL_EXT_texture_compression_dxt1") || config.extensions.has("GL_EXT_texture_compression_s3tc") || config.extensions.has("WEBGL_compressed_texture_s3tc");
8270 	config.rgtc_supported = config.extensions.has("GL_EXT_texture_compression_rgtc") || config.extensions.has("GL_ARB_texture_compression_rgtc") || config.extensions.has("EXT_texture_compression_rgtc");
8271 	config.texture_float_linear_supported = config.extensions.has("GL_OES_texture_float_linear");
8272 	config.framebuffer_float_supported = config.extensions.has("GL_EXT_color_buffer_float");
8273 	config.framebuffer_half_float_supported = config.extensions.has("GL_EXT_color_buffer_half_float") || config.framebuffer_float_supported;
8274 
8275 #endif
8276 
8277 	config.pvrtc_supported = config.extensions.has("GL_IMG_texture_compression_pvrtc");
8278 	config.srgb_decode_supported = config.extensions.has("GL_EXT_texture_sRGB_decode");
8279 
8280 	config.anisotropic_level = 1.0;
8281 	config.use_anisotropic_filter = config.extensions.has("GL_EXT_texture_filter_anisotropic");
8282 	if (config.use_anisotropic_filter) {
8283 		glGetFloatv(_GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &config.anisotropic_level);
8284 		config.anisotropic_level = MIN(int(ProjectSettings::get_singleton()->get("rendering/quality/filters/anisotropic_filter_level")), config.anisotropic_level);
8285 	}
8286 
8287 	frame.clear_request = false;
8288 
8289 	shaders.copy.init();
8290 
8291 	{
8292 		//default textures
8293 
8294 		glGenTextures(1, &resources.white_tex);
8295 		unsigned char whitetexdata[8 * 8 * 3];
8296 		for (int i = 0; i < 8 * 8 * 3; i++) {
8297 			whitetexdata[i] = 255;
8298 		}
8299 
8300 		glActiveTexture(GL_TEXTURE0);
8301 		glBindTexture(GL_TEXTURE_2D, resources.white_tex);
8302 		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, whitetexdata);
8303 		glGenerateMipmap(GL_TEXTURE_2D);
8304 		glBindTexture(GL_TEXTURE_2D, 0);
8305 
8306 		glGenTextures(1, &resources.black_tex);
8307 		unsigned char blacktexdata[8 * 8 * 3];
8308 		for (int i = 0; i < 8 * 8 * 3; i++) {
8309 			blacktexdata[i] = 0;
8310 		}
8311 
8312 		glActiveTexture(GL_TEXTURE0);
8313 		glBindTexture(GL_TEXTURE_2D, resources.black_tex);
8314 		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, blacktexdata);
8315 		glGenerateMipmap(GL_TEXTURE_2D);
8316 		glBindTexture(GL_TEXTURE_2D, 0);
8317 
8318 		glGenTextures(1, &resources.normal_tex);
8319 		unsigned char normaltexdata[8 * 8 * 3];
8320 		for (int i = 0; i < 8 * 8 * 3; i += 3) {
8321 			normaltexdata[i + 0] = 128;
8322 			normaltexdata[i + 1] = 128;
8323 			normaltexdata[i + 2] = 255;
8324 		}
8325 
8326 		glActiveTexture(GL_TEXTURE0);
8327 		glBindTexture(GL_TEXTURE_2D, resources.normal_tex);
8328 		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, normaltexdata);
8329 		glGenerateMipmap(GL_TEXTURE_2D);
8330 		glBindTexture(GL_TEXTURE_2D, 0);
8331 
8332 		glGenTextures(1, &resources.aniso_tex);
8333 		unsigned char anisotexdata[8 * 8 * 3];
8334 		for (int i = 0; i < 8 * 8 * 3; i += 3) {
8335 			anisotexdata[i + 0] = 255;
8336 			anisotexdata[i + 1] = 128;
8337 			anisotexdata[i + 2] = 0;
8338 		}
8339 
8340 		glActiveTexture(GL_TEXTURE0);
8341 		glBindTexture(GL_TEXTURE_2D, resources.aniso_tex);
8342 		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, anisotexdata);
8343 		glGenerateMipmap(GL_TEXTURE_2D);
8344 		glBindTexture(GL_TEXTURE_2D, 0);
8345 
8346 		glGenTextures(1, &resources.white_tex_3d);
8347 
8348 		glActiveTexture(GL_TEXTURE0);
8349 		glBindTexture(GL_TEXTURE_3D, resources.white_tex_3d);
8350 		glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB, 2, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, whitetexdata);
8351 
8352 		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0);
8353 		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, 0);
8354 
8355 		glGenTextures(1, &resources.white_tex_array);
8356 		glActiveTexture(GL_TEXTURE0);
8357 		glBindTexture(GL_TEXTURE_2D_ARRAY, resources.white_tex_array);
8358 		glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGB, 8, 8, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
8359 		glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, 8, 8, 1, GL_RGB, GL_UNSIGNED_BYTE, whitetexdata);
8360 		glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
8361 		glBindTexture(GL_TEXTURE_2D, 0);
8362 	}
8363 
8364 	glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &config.max_texture_image_units);
8365 	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &config.max_texture_size);
8366 
8367 	config.use_rgba_2d_shadows = !config.framebuffer_float_supported;
8368 
8369 	//generic quadie for copying
8370 
8371 	{
8372 		//quad buffers
8373 
8374 		glGenBuffers(1, &resources.quadie);
8375 		glBindBuffer(GL_ARRAY_BUFFER, resources.quadie);
8376 		{
8377 			const float qv[16] = {
8378 				-1,
8379 				-1,
8380 				0,
8381 				0,
8382 				-1,
8383 				1,
8384 				0,
8385 				1,
8386 				1,
8387 				1,
8388 				1,
8389 				1,
8390 				1,
8391 				-1,
8392 				1,
8393 				0,
8394 			};
8395 
8396 			glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16, qv, GL_STATIC_DRAW);
8397 		}
8398 
8399 		glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
8400 
8401 		glGenVertexArrays(1, &resources.quadie_array);
8402 		glBindVertexArray(resources.quadie_array);
8403 		glBindBuffer(GL_ARRAY_BUFFER, resources.quadie);
8404 		glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, 0);
8405 		glEnableVertexAttribArray(0);
8406 		glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, CAST_INT_TO_UCHAR_PTR(8));
8407 		glEnableVertexAttribArray(4);
8408 		glBindVertexArray(0);
8409 		glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
8410 	}
8411 
8412 	//generic quadie for copying without touching sky
8413 
8414 	{
8415 		//transform feedback buffers
8416 		uint32_t xf_feedback_size = GLOBAL_DEF_RST("rendering/limits/buffers/blend_shape_max_buffer_size_kb", 4096);
8417 		ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/blend_shape_max_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/blend_shape_max_buffer_size_kb", PROPERTY_HINT_RANGE, "0,8192,1,or_greater"));
8418 
8419 		for (int i = 0; i < 2; i++) {
8420 
8421 			glGenBuffers(1, &resources.transform_feedback_buffers[i]);
8422 			glBindBuffer(GL_ARRAY_BUFFER, resources.transform_feedback_buffers[i]);
8423 			glBufferData(GL_ARRAY_BUFFER, xf_feedback_size * 1024, NULL, GL_STREAM_DRAW);
8424 		}
8425 
8426 		shaders.blend_shapes.init();
8427 
8428 		glGenVertexArrays(1, &resources.transform_feedback_array);
8429 	}
8430 
8431 	shaders.cubemap_filter.init();
8432 	bool ggx_hq = GLOBAL_GET("rendering/quality/reflections/high_quality_ggx");
8433 	shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY, !ggx_hq);
8434 	shaders.particles.init();
8435 
8436 #ifdef GLES_OVER_GL
8437 	glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS);
8438 #endif
8439 
8440 	frame.count = 0;
8441 	frame.delta = 0;
8442 	frame.current_rt = NULL;
8443 	config.keep_original_textures = false;
8444 	config.generate_wireframes = false;
8445 	config.use_texture_array_environment = GLOBAL_GET("rendering/quality/reflections/texture_array_reflections");
8446 
8447 	config.force_vertex_shading = GLOBAL_GET("rendering/quality/shading/force_vertex_shading");
8448 
8449 	String renderer = (const char *)glGetString(GL_RENDERER);
8450 
8451 	config.use_depth_prepass = bool(GLOBAL_GET("rendering/quality/depth_prepass/enable"));
8452 	if (config.use_depth_prepass) {
8453 
8454 		String vendors = GLOBAL_GET("rendering/quality/depth_prepass/disable_for_vendors");
8455 		Vector<String> vendor_match = vendors.split(",");
8456 		for (int i = 0; i < vendor_match.size(); i++) {
8457 			String v = vendor_match[i].strip_edges();
8458 			if (v == String())
8459 				continue;
8460 
8461 			if (renderer.findn(v) != -1) {
8462 				config.use_depth_prepass = false;
8463 			}
8464 		}
8465 	}
8466 }
8467 
8468 void RasterizerStorageGLES3::finalize() {
8469 
8470 	glDeleteTextures(1, &resources.white_tex);
8471 	glDeleteTextures(1, &resources.black_tex);
8472 	glDeleteTextures(1, &resources.normal_tex);
8473 }
8474 
8475 void RasterizerStorageGLES3::update_dirty_resources() {
8476 
8477 	update_dirty_multimeshes();
8478 	update_dirty_skeletons();
8479 	update_dirty_shaders();
8480 	update_dirty_materials();
8481 	update_particles();
8482 }
8483 
8484 RasterizerStorageGLES3::RasterizerStorageGLES3() {
8485 }
8486