1/**************************************************************************/
2/* material_storage.cpp */
3/**************************************************************************/
4/* This file is part of: */
5/* GODOT ENGINE */
6/* https://godotengine.org */
7/**************************************************************************/
8/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
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#ifdef GLES3_ENABLED
32
33#include "core/config/project_settings.h"
34
35#include "config.h"
36#include "material_storage.h"
37#include "particles_storage.h"
38#include "texture_storage.h"
39
40#include "drivers/gles3/rasterizer_canvas_gles3.h"
41#include "drivers/gles3/rasterizer_gles3.h"
42#include "servers/rendering/storage/variant_converters.h"
43
44using namespace GLES3;
45
46///////////////////////////////////////////////////////////////////////////
47// UBI helper functions
48
49static void _fill_std140_variant_ubo_value(ShaderLanguage::DataType type, int p_array_size, const Variant &value, uint8_t *data) {
50 switch (type) {
51 case ShaderLanguage::TYPE_BOOL: {
52 uint32_t *gui = (uint32_t *)data;
53
54 if (p_array_size > 0) {
55 PackedInt32Array ba = value;
56 for (int i = 0; i < ba.size(); i++) {
57 ba.set(i, ba[i] ? 1 : 0);
58 }
59 write_array_std140<int32_t>(ba, gui, p_array_size, 4);
60 } else {
61 bool v = value;
62 gui[0] = v ? 1 : 0;
63 }
64 } break;
65 case ShaderLanguage::TYPE_BVEC2: {
66 uint32_t *gui = (uint32_t *)data;
67
68 if (p_array_size > 0) {
69 PackedInt32Array ba = convert_array_std140<Vector2i, int32_t>(value);
70 for (int i = 0; i < ba.size(); i++) {
71 ba.set(i, ba[i] ? 1 : 0);
72 }
73 write_array_std140<Vector2i>(ba, gui, p_array_size, 4);
74 } else {
75 uint32_t v = value;
76 gui[0] = v & 1 ? 1 : 0;
77 gui[1] = v & 2 ? 1 : 0;
78 }
79 } break;
80 case ShaderLanguage::TYPE_BVEC3: {
81 uint32_t *gui = (uint32_t *)data;
82
83 if (p_array_size > 0) {
84 PackedInt32Array ba = convert_array_std140<Vector3i, int32_t>(value);
85 for (int i = 0; i < ba.size(); i++) {
86 ba.set(i, ba[i] ? 1 : 0);
87 }
88 write_array_std140<Vector3i>(ba, gui, p_array_size, 4);
89 } else {
90 uint32_t v = value;
91 gui[0] = (v & 1) ? 1 : 0;
92 gui[1] = (v & 2) ? 1 : 0;
93 gui[2] = (v & 4) ? 1 : 0;
94 }
95 } break;
96 case ShaderLanguage::TYPE_BVEC4: {
97 uint32_t *gui = (uint32_t *)data;
98
99 if (p_array_size > 0) {
100 PackedInt32Array ba = convert_array_std140<Vector4i, int32_t>(value);
101 for (int i = 0; i < ba.size(); i++) {
102 ba.set(i, ba[i] ? 1 : 0);
103 }
104 write_array_std140<Vector4i>(ba, gui, p_array_size, 4);
105 } else {
106 uint32_t v = value;
107 gui[0] = (v & 1) ? 1 : 0;
108 gui[1] = (v & 2) ? 1 : 0;
109 gui[2] = (v & 4) ? 1 : 0;
110 gui[3] = (v & 8) ? 1 : 0;
111 }
112 } break;
113 case ShaderLanguage::TYPE_INT: {
114 int32_t *gui = (int32_t *)data;
115
116 if (p_array_size > 0) {
117 const PackedInt32Array &iv = value;
118 write_array_std140<int32_t>(iv, gui, p_array_size, 4);
119 } else {
120 int v = value;
121 gui[0] = v;
122 }
123 } break;
124 case ShaderLanguage::TYPE_IVEC2: {
125 int32_t *gui = (int32_t *)data;
126
127 if (p_array_size > 0) {
128 const PackedInt32Array &iv = convert_array_std140<Vector2i, int32_t>(value);
129 write_array_std140<Vector2i>(iv, gui, p_array_size, 4);
130 } else {
131 Vector2i v = convert_to_vector<Vector2i>(value);
132 gui[0] = v.x;
133 gui[1] = v.y;
134 }
135 } break;
136 case ShaderLanguage::TYPE_IVEC3: {
137 int32_t *gui = (int32_t *)data;
138
139 if (p_array_size > 0) {
140 const PackedInt32Array &iv = convert_array_std140<Vector3i, int32_t>(value);
141 write_array_std140<Vector3i>(iv, gui, p_array_size, 4);
142 } else {
143 Vector3i v = convert_to_vector<Vector3i>(value);
144 gui[0] = v.x;
145 gui[1] = v.y;
146 gui[2] = v.z;
147 }
148 } break;
149 case ShaderLanguage::TYPE_IVEC4: {
150 int32_t *gui = (int32_t *)data;
151
152 if (p_array_size > 0) {
153 const PackedInt32Array &iv = convert_array_std140<Vector4i, int32_t>(value);
154 write_array_std140<Vector4i>(iv, gui, p_array_size, 4);
155 } else {
156 Vector4i v = convert_to_vector<Vector4i>(value);
157 gui[0] = v.x;
158 gui[1] = v.y;
159 gui[2] = v.z;
160 gui[3] = v.w;
161 }
162 } break;
163 case ShaderLanguage::TYPE_UINT: {
164 uint32_t *gui = (uint32_t *)data;
165
166 if (p_array_size > 0) {
167 const PackedInt32Array &iv = value;
168 write_array_std140<uint32_t>(iv, gui, p_array_size, 4);
169 } else {
170 int v = value;
171 gui[0] = v;
172 }
173 } break;
174 case ShaderLanguage::TYPE_UVEC2: {
175 uint32_t *gui = (uint32_t *)data;
176
177 if (p_array_size > 0) {
178 const PackedInt32Array &iv = convert_array_std140<Vector2i, int32_t>(value);
179 write_array_std140<Vector2i>(iv, gui, p_array_size, 4);
180 } else {
181 Vector2i v = convert_to_vector<Vector2i>(value);
182 gui[0] = v.x;
183 gui[1] = v.y;
184 }
185 } break;
186 case ShaderLanguage::TYPE_UVEC3: {
187 uint32_t *gui = (uint32_t *)data;
188
189 if (p_array_size > 0) {
190 const PackedInt32Array &iv = convert_array_std140<Vector3i, int32_t>(value);
191 write_array_std140<Vector3i>(iv, gui, p_array_size, 4);
192 } else {
193 Vector3i v = convert_to_vector<Vector3i>(value);
194 gui[0] = v.x;
195 gui[1] = v.y;
196 gui[2] = v.z;
197 }
198 } break;
199 case ShaderLanguage::TYPE_UVEC4: {
200 uint32_t *gui = (uint32_t *)data;
201
202 if (p_array_size > 0) {
203 const PackedInt32Array &iv = convert_array_std140<Vector4i, int32_t>(value);
204 write_array_std140<Vector4i>(iv, gui, p_array_size, 4);
205 } else {
206 Vector4i v = convert_to_vector<Vector4i>(value);
207 gui[0] = v.x;
208 gui[1] = v.y;
209 gui[2] = v.z;
210 gui[3] = v.w;
211 }
212 } break;
213 case ShaderLanguage::TYPE_FLOAT: {
214 float *gui = (float *)data;
215
216 if (p_array_size > 0) {
217 const PackedFloat32Array &a = value;
218 write_array_std140<float>(a, gui, p_array_size, 4);
219 } else {
220 float v = value;
221 gui[0] = v;
222 }
223 } break;
224 case ShaderLanguage::TYPE_VEC2: {
225 float *gui = (float *)data;
226
227 if (p_array_size > 0) {
228 const PackedFloat32Array &a = convert_array_std140<Vector2, float>(value);
229 write_array_std140<Vector2>(a, gui, p_array_size, 4);
230 } else {
231 Vector2 v = convert_to_vector<Vector2>(value);
232 gui[0] = v.x;
233 gui[1] = v.y;
234 }
235 } break;
236 case ShaderLanguage::TYPE_VEC3: {
237 float *gui = (float *)data;
238
239 if (p_array_size > 0) {
240 const PackedFloat32Array &a = convert_array_std140<Vector3, float>(value);
241 write_array_std140<Vector3>(a, gui, p_array_size, 4);
242 } else {
243 Vector3 v = convert_to_vector<Vector3>(value);
244 gui[0] = v.x;
245 gui[1] = v.y;
246 gui[2] = v.z;
247 }
248 } break;
249 case ShaderLanguage::TYPE_VEC4: {
250 float *gui = (float *)data;
251
252 if (p_array_size > 0) {
253 const PackedFloat32Array &a = convert_array_std140<Vector4, float>(value);
254 write_array_std140<Vector4>(a, gui, p_array_size, 4);
255 } else {
256 Vector4 v = convert_to_vector<Vector4>(value);
257 gui[0] = v.x;
258 gui[1] = v.y;
259 gui[2] = v.z;
260 gui[3] = v.w;
261 }
262 } break;
263 case ShaderLanguage::TYPE_MAT2: {
264 float *gui = (float *)data;
265
266 if (p_array_size > 0) {
267 const PackedFloat32Array &a = value;
268 int s = a.size();
269
270 for (int i = 0, j = 0; i < p_array_size * 4; i += 4, j += 8) {
271 if (i + 3 < s) {
272 gui[j] = a[i];
273 gui[j + 1] = a[i + 1];
274
275 gui[j + 4] = a[i + 2];
276 gui[j + 5] = a[i + 3];
277 } else {
278 gui[j] = 1;
279 gui[j + 1] = 0;
280
281 gui[j + 4] = 0;
282 gui[j + 5] = 1;
283 }
284 gui[j + 2] = 0; // ignored
285 gui[j + 3] = 0; // ignored
286 gui[j + 6] = 0; // ignored
287 gui[j + 7] = 0; // ignored
288 }
289 } else {
290 Transform2D v = value;
291
292 //in std140 members of mat2 are treated as vec4s
293 gui[0] = v.columns[0][0];
294 gui[1] = v.columns[0][1];
295 gui[2] = 0; // ignored
296 gui[3] = 0; // ignored
297
298 gui[4] = v.columns[1][0];
299 gui[5] = v.columns[1][1];
300 gui[6] = 0; // ignored
301 gui[7] = 0; // ignored
302 }
303 } break;
304 case ShaderLanguage::TYPE_MAT3: {
305 float *gui = (float *)data;
306
307 if (p_array_size > 0) {
308 const PackedFloat32Array &a = convert_array_std140<Basis, float>(value);
309 const Basis default_basis;
310 const int s = a.size();
311
312 for (int i = 0, j = 0; i < p_array_size * 9; i += 9, j += 12) {
313 if (i + 8 < s) {
314 gui[j] = a[i];
315 gui[j + 1] = a[i + 1];
316 gui[j + 2] = a[i + 2];
317 gui[j + 3] = 0; // Ignored.
318
319 gui[j + 4] = a[i + 3];
320 gui[j + 5] = a[i + 4];
321 gui[j + 6] = a[i + 5];
322 gui[j + 7] = 0; // Ignored.
323
324 gui[j + 8] = a[i + 6];
325 gui[j + 9] = a[i + 7];
326 gui[j + 10] = a[i + 8];
327 gui[j + 11] = 0; // Ignored.
328 } else {
329 convert_item_std140(default_basis, gui + j);
330 }
331 }
332 } else {
333 convert_item_std140<Basis>(value, gui);
334 }
335 } break;
336 case ShaderLanguage::TYPE_MAT4: {
337 float *gui = (float *)data;
338
339 if (p_array_size > 0) {
340 const PackedFloat32Array &a = convert_array_std140<Projection, float>(value);
341 write_array_std140<Projection>(a, gui, p_array_size, 16);
342 } else {
343 convert_item_std140<Projection>(value, gui);
344 }
345 } break;
346 default: {
347 }
348 }
349}
350
351_FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type, const Vector<ShaderLanguage::ConstantNode::Value> &value, uint8_t *data) {
352 switch (type) {
353 case ShaderLanguage::TYPE_BOOL: {
354 uint32_t *gui = (uint32_t *)data;
355 gui[0] = value[0].boolean ? 1 : 0;
356 } break;
357 case ShaderLanguage::TYPE_BVEC2: {
358 uint32_t *gui = (uint32_t *)data;
359 gui[0] = value[0].boolean ? 1 : 0;
360 gui[1] = value[1].boolean ? 1 : 0;
361
362 } break;
363 case ShaderLanguage::TYPE_BVEC3: {
364 uint32_t *gui = (uint32_t *)data;
365 gui[0] = value[0].boolean ? 1 : 0;
366 gui[1] = value[1].boolean ? 1 : 0;
367 gui[2] = value[2].boolean ? 1 : 0;
368
369 } break;
370 case ShaderLanguage::TYPE_BVEC4: {
371 uint32_t *gui = (uint32_t *)data;
372 gui[0] = value[0].boolean ? 1 : 0;
373 gui[1] = value[1].boolean ? 1 : 0;
374 gui[2] = value[2].boolean ? 1 : 0;
375 gui[3] = value[3].boolean ? 1 : 0;
376
377 } break;
378 case ShaderLanguage::TYPE_INT: {
379 int32_t *gui = (int32_t *)data;
380 gui[0] = value[0].sint;
381
382 } break;
383 case ShaderLanguage::TYPE_IVEC2: {
384 int32_t *gui = (int32_t *)data;
385
386 for (int i = 0; i < 2; i++) {
387 gui[i] = value[i].sint;
388 }
389
390 } break;
391 case ShaderLanguage::TYPE_IVEC3: {
392 int32_t *gui = (int32_t *)data;
393
394 for (int i = 0; i < 3; i++) {
395 gui[i] = value[i].sint;
396 }
397
398 } break;
399 case ShaderLanguage::TYPE_IVEC4: {
400 int32_t *gui = (int32_t *)data;
401
402 for (int i = 0; i < 4; i++) {
403 gui[i] = value[i].sint;
404 }
405
406 } break;
407 case ShaderLanguage::TYPE_UINT: {
408 uint32_t *gui = (uint32_t *)data;
409 gui[0] = value[0].uint;
410
411 } break;
412 case ShaderLanguage::TYPE_UVEC2: {
413 int32_t *gui = (int32_t *)data;
414
415 for (int i = 0; i < 2; i++) {
416 gui[i] = value[i].uint;
417 }
418 } break;
419 case ShaderLanguage::TYPE_UVEC3: {
420 int32_t *gui = (int32_t *)data;
421
422 for (int i = 0; i < 3; i++) {
423 gui[i] = value[i].uint;
424 }
425
426 } break;
427 case ShaderLanguage::TYPE_UVEC4: {
428 int32_t *gui = (int32_t *)data;
429
430 for (int i = 0; i < 4; i++) {
431 gui[i] = value[i].uint;
432 }
433 } break;
434 case ShaderLanguage::TYPE_FLOAT: {
435 float *gui = (float *)data;
436 gui[0] = value[0].real;
437
438 } break;
439 case ShaderLanguage::TYPE_VEC2: {
440 float *gui = (float *)data;
441
442 for (int i = 0; i < 2; i++) {
443 gui[i] = value[i].real;
444 }
445
446 } break;
447 case ShaderLanguage::TYPE_VEC3: {
448 float *gui = (float *)data;
449
450 for (int i = 0; i < 3; i++) {
451 gui[i] = value[i].real;
452 }
453
454 } break;
455 case ShaderLanguage::TYPE_VEC4: {
456 float *gui = (float *)data;
457
458 for (int i = 0; i < 4; i++) {
459 gui[i] = value[i].real;
460 }
461 } break;
462 case ShaderLanguage::TYPE_MAT2: {
463 float *gui = (float *)data;
464
465 //in std140 members of mat2 are treated as vec4s
466 gui[0] = value[0].real;
467 gui[1] = value[1].real;
468 gui[2] = 0;
469 gui[3] = 0;
470 gui[4] = value[2].real;
471 gui[5] = value[3].real;
472 gui[6] = 0;
473 gui[7] = 0;
474 } break;
475 case ShaderLanguage::TYPE_MAT3: {
476 float *gui = (float *)data;
477
478 gui[0] = value[0].real;
479 gui[1] = value[1].real;
480 gui[2] = value[2].real;
481 gui[3] = 0;
482 gui[4] = value[3].real;
483 gui[5] = value[4].real;
484 gui[6] = value[5].real;
485 gui[7] = 0;
486 gui[8] = value[6].real;
487 gui[9] = value[7].real;
488 gui[10] = value[8].real;
489 gui[11] = 0;
490 } break;
491 case ShaderLanguage::TYPE_MAT4: {
492 float *gui = (float *)data;
493
494 for (int i = 0; i < 16; i++) {
495 gui[i] = value[i].real;
496 }
497 } break;
498 default: {
499 }
500 }
501}
502
503_FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type, int p_array_size, uint8_t *data) {
504 if (p_array_size <= 0) {
505 p_array_size = 1;
506 }
507
508 switch (type) {
509 case ShaderLanguage::TYPE_BOOL:
510 case ShaderLanguage::TYPE_INT:
511 case ShaderLanguage::TYPE_UINT:
512 case ShaderLanguage::TYPE_FLOAT: {
513 memset(data, 0, 4 * p_array_size);
514 } break;
515 case ShaderLanguage::TYPE_BVEC2:
516 case ShaderLanguage::TYPE_IVEC2:
517 case ShaderLanguage::TYPE_UVEC2:
518 case ShaderLanguage::TYPE_VEC2: {
519 memset(data, 0, 8 * p_array_size);
520 } break;
521 case ShaderLanguage::TYPE_BVEC3:
522 case ShaderLanguage::TYPE_IVEC3:
523 case ShaderLanguage::TYPE_UVEC3:
524 case ShaderLanguage::TYPE_VEC3: {
525 memset(data, 0, 12 * p_array_size);
526 } break;
527 case ShaderLanguage::TYPE_BVEC4:
528 case ShaderLanguage::TYPE_IVEC4:
529 case ShaderLanguage::TYPE_UVEC4:
530 case ShaderLanguage::TYPE_VEC4: {
531 memset(data, 0, 16 * p_array_size);
532 } break;
533 case ShaderLanguage::TYPE_MAT2: {
534 memset(data, 0, 32 * p_array_size);
535 } break;
536 case ShaderLanguage::TYPE_MAT3: {
537 memset(data, 0, 48 * p_array_size);
538 } break;
539 case ShaderLanguage::TYPE_MAT4: {
540 memset(data, 0, 64 * p_array_size);
541 } break;
542
543 default: {
544 }
545 }
546}
547
548///////////////////////////////////////////////////////////////////////////
549// ShaderData
550
551void ShaderData::set_path_hint(const String &p_hint) {
552 path = p_hint;
553}
554
555void ShaderData::set_default_texture_parameter(const StringName &p_name, RID p_texture, int p_index) {
556 if (!p_texture.is_valid()) {
557 if (default_texture_params.has(p_name) && default_texture_params[p_name].has(p_index)) {
558 default_texture_params[p_name].erase(p_index);
559
560 if (default_texture_params[p_name].is_empty()) {
561 default_texture_params.erase(p_name);
562 }
563 }
564 } else {
565 if (!default_texture_params.has(p_name)) {
566 default_texture_params[p_name] = HashMap<int, RID>();
567 }
568 default_texture_params[p_name][p_index] = p_texture;
569 }
570}
571
572Variant ShaderData::get_default_parameter(const StringName &p_parameter) const {
573 if (uniforms.has(p_parameter)) {
574 ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter];
575 Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value;
576 return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.array_size, uniform.hint);
577 }
578 return Variant();
579}
580
581void ShaderData::get_shader_uniform_list(List<PropertyInfo> *p_param_list) const {
582 SortArray<Pair<StringName, int>, ShaderLanguage::UniformOrderComparator> sorter;
583 LocalVector<Pair<StringName, int>> filtered_uniforms;
584
585 for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : uniforms) {
586 if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL) {
587 continue;
588 }
589 if (E.value.texture_order >= 0) {
590 filtered_uniforms.push_back(Pair<StringName, int>(E.key, E.value.texture_order + 100000));
591 } else {
592 filtered_uniforms.push_back(Pair<StringName, int>(E.key, E.value.order));
593 }
594 }
595 int uniform_count = filtered_uniforms.size();
596 sorter.sort(filtered_uniforms.ptr(), uniform_count);
597
598 String last_group;
599 for (int i = 0; i < uniform_count; i++) {
600 const StringName &uniform_name = filtered_uniforms[i].first;
601 const ShaderLanguage::ShaderNode::Uniform &uniform = uniforms[uniform_name];
602
603 String group = uniform.group;
604 if (!uniform.subgroup.is_empty()) {
605 group += "::" + uniform.subgroup;
606 }
607
608 if (group != last_group) {
609 PropertyInfo pi;
610 pi.usage = PROPERTY_USAGE_GROUP;
611 pi.name = group;
612 p_param_list->push_back(pi);
613
614 last_group = group;
615 }
616
617 PropertyInfo pi = ShaderLanguage::uniform_to_property_info(uniform);
618 pi.name = uniform_name;
619 p_param_list->push_back(pi);
620 }
621}
622
623void ShaderData::get_instance_param_list(List<RendererMaterialStorage::InstanceShaderParam> *p_param_list) const {
624 for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : uniforms) {
625 if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
626 continue;
627 }
628
629 RendererMaterialStorage::InstanceShaderParam p;
630 p.info = ShaderLanguage::uniform_to_property_info(E.value);
631 p.info.name = E.key; //supply name
632 p.index = E.value.instance_index;
633 p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.array_size, E.value.hint);
634 p_param_list->push_back(p);
635 }
636}
637
638bool ShaderData::is_parameter_texture(const StringName &p_param) const {
639 if (!uniforms.has(p_param)) {
640 return false;
641 }
642
643 return uniforms[p_param].texture_order >= 0;
644}
645
646///////////////////////////////////////////////////////////////////////////
647// MaterialData
648
649// Look up table to translate ShaderLanguage::DataType to GL_TEXTURE_*
650static const GLenum target_from_type[ShaderLanguage::TYPE_MAX] = {
651 GL_TEXTURE_2D, // TYPE_VOID,
652 GL_TEXTURE_2D, // TYPE_BOOL,
653 GL_TEXTURE_2D, // TYPE_BVEC2,
654 GL_TEXTURE_2D, // TYPE_BVEC3,
655 GL_TEXTURE_2D, // TYPE_BVEC4,
656 GL_TEXTURE_2D, // TYPE_INT,
657 GL_TEXTURE_2D, // TYPE_IVEC2,
658 GL_TEXTURE_2D, // TYPE_IVEC3,
659 GL_TEXTURE_2D, // TYPE_IVEC4,
660 GL_TEXTURE_2D, // TYPE_UINT,
661 GL_TEXTURE_2D, // TYPE_UVEC2,
662 GL_TEXTURE_2D, // TYPE_UVEC3,
663 GL_TEXTURE_2D, // TYPE_UVEC4,
664 GL_TEXTURE_2D, // TYPE_FLOAT,
665 GL_TEXTURE_2D, // TYPE_VEC2,
666 GL_TEXTURE_2D, // TYPE_VEC3,
667 GL_TEXTURE_2D, // TYPE_VEC4,
668 GL_TEXTURE_2D, // TYPE_MAT2,
669 GL_TEXTURE_2D, // TYPE_MAT3,
670 GL_TEXTURE_2D, // TYPE_MAT4,
671 GL_TEXTURE_2D, // TYPE_SAMPLER2D,
672 GL_TEXTURE_2D, // TYPE_ISAMPLER2D,
673 GL_TEXTURE_2D, // TYPE_USAMPLER2D,
674 GL_TEXTURE_2D_ARRAY, // TYPE_SAMPLER2DARRAY,
675 GL_TEXTURE_2D_ARRAY, // TYPE_ISAMPLER2DARRAY,
676 GL_TEXTURE_2D_ARRAY, // TYPE_USAMPLER2DARRAY,
677 GL_TEXTURE_3D, // TYPE_SAMPLER3D,
678 GL_TEXTURE_3D, // TYPE_ISAMPLER3D,
679 GL_TEXTURE_3D, // TYPE_USAMPLER3D,
680 GL_TEXTURE_CUBE_MAP, // TYPE_SAMPLERCUBE,
681 GL_TEXTURE_CUBE_MAP, // TYPE_SAMPLERCUBEARRAY,
682 GL_TEXTURE_2D, // TYPE_STRUCT
683};
684
685static const RS::CanvasItemTextureRepeat repeat_from_uniform[ShaderLanguage::REPEAT_DEFAULT + 1] = {
686 RS::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED, // ShaderLanguage::TextureRepeat::REPEAT_DISABLE,
687 RS::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED, // ShaderLanguage::TextureRepeat::REPEAT_ENABLE,
688 RS::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED, // ShaderLanguage::TextureRepeat::REPEAT_DEFAULT,
689};
690
691static const RS::CanvasItemTextureRepeat repeat_from_uniform_canvas[ShaderLanguage::REPEAT_DEFAULT + 1] = {
692 RS::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED, // ShaderLanguage::TextureRepeat::REPEAT_DISABLE,
693 RS::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED, // ShaderLanguage::TextureRepeat::REPEAT_ENABLE,
694 RS::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED, // ShaderLanguage::TextureRepeat::REPEAT_DEFAULT,
695};
696
697static const RS::CanvasItemTextureFilter filter_from_uniform[ShaderLanguage::FILTER_DEFAULT + 1] = {
698 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, // ShaderLanguage::TextureFilter::FILTER_NEAREST,
699 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, // ShaderLanguage::TextureFilter::FILTER_LINEAR,
700 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, // ShaderLanguage::TextureFilter::FILTER_NEAREST_MIPMAP,
701 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, // ShaderLanguage::TextureFilter::FILTER_LINEAR_MIPMAP,
702 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, // ShaderLanguage::TextureFilter::FILTER_NEAREST_MIPMAP_ANISOTROPIC,
703 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, // ShaderLanguage::TextureFilter::FILTER_LINEAR_MIPMAP_ANISOTROPIC,
704 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, // ShaderLanguage::TextureFilter::FILTER_DEFAULT,
705};
706
707static const RS::CanvasItemTextureFilter filter_from_uniform_canvas[ShaderLanguage::FILTER_DEFAULT + 1] = {
708 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, // ShaderLanguage::TextureFilter::FILTER_NEAREST,
709 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, // ShaderLanguage::TextureFilter::FILTER_LINEAR,
710 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, // ShaderLanguage::TextureFilter::FILTER_NEAREST_MIPMAP,
711 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, // ShaderLanguage::TextureFilter::FILTER_LINEAR_MIPMAP,
712 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, // ShaderLanguage::TextureFilter::FILTER_NEAREST_MIPMAP_ANISOTROPIC,
713 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, // ShaderLanguage::TextureFilter::FILTER_LINEAR_MIPMAP_ANISOTROPIC,
714 RS::CanvasItemTextureFilter::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, // ShaderLanguage::TextureFilter::FILTER_DEFAULT,
715};
716
717void MaterialData::update_uniform_buffer(const HashMap<StringName, ShaderLanguage::ShaderNode::Uniform> &p_uniforms, const uint32_t *p_uniform_offsets, const HashMap<StringName, Variant> &p_parameters, uint8_t *p_buffer, uint32_t p_buffer_size) {
718 MaterialStorage *material_storage = MaterialStorage::get_singleton();
719 bool uses_global_buffer = false;
720
721 for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : p_uniforms) {
722 if (E.value.order < 0) {
723 continue; // texture, does not go here
724 }
725
726 if (E.value.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
727 continue; //instance uniforms don't appear in the buffer
728 }
729
730 if (E.value.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL) {
731 //this is a global variable, get the index to it
732 GlobalShaderUniforms::Variable *gv = material_storage->global_shader_uniforms.variables.getptr(E.key);
733 uint32_t index = 0;
734 if (gv) {
735 index = gv->buffer_index;
736 } else {
737 WARN_PRINT("Shader uses global parameter '" + E.key + "', but it was removed at some point. Material will not display correctly.");
738 }
739
740 uint32_t offset = p_uniform_offsets[E.value.order];
741 uint32_t *intptr = (uint32_t *)&p_buffer[offset];
742 *intptr = index;
743 uses_global_buffer = true;
744 continue;
745 }
746
747 //regular uniform
748 uint32_t offset = p_uniform_offsets[E.value.order];
749#ifdef DEBUG_ENABLED
750 uint32_t size = 0U;
751 // The following code enforces a 16-byte alignment of uniform arrays.
752 if (E.value.array_size > 0) {
753 size = ShaderLanguage::get_datatype_size(E.value.type) * E.value.array_size;
754 int m = (16 * E.value.array_size);
755 if ((size % m) != 0U) {
756 size += m - (size % m);
757 }
758 } else {
759 size = ShaderLanguage::get_datatype_size(E.value.type);
760 }
761 ERR_CONTINUE(offset + size > p_buffer_size);
762#endif
763 uint8_t *data = &p_buffer[offset];
764 HashMap<StringName, Variant>::ConstIterator V = p_parameters.find(E.key);
765
766 if (V) {
767 //user provided
768 _fill_std140_variant_ubo_value(E.value.type, E.value.array_size, V->value, data);
769
770 } else if (E.value.default_value.size()) {
771 //default value
772 _fill_std140_ubo_value(E.value.type, E.value.default_value, data);
773 //value=E.value.default_value;
774 } else {
775 //zero because it was not provided
776 if ((E.value.type == ShaderLanguage::TYPE_VEC3 || E.value.type == ShaderLanguage::TYPE_VEC4) && E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SOURCE_COLOR) {
777 //colors must be set as black, with alpha as 1.0
778 _fill_std140_variant_ubo_value(E.value.type, E.value.array_size, Color(0, 0, 0, 1), data);
779 } else {
780 //else just zero it out
781 _fill_std140_ubo_empty(E.value.type, E.value.array_size, data);
782 }
783 }
784 }
785
786 if (uses_global_buffer != (global_buffer_E != nullptr)) {
787 if (uses_global_buffer) {
788 global_buffer_E = material_storage->global_shader_uniforms.materials_using_buffer.push_back(self);
789 } else {
790 material_storage->global_shader_uniforms.materials_using_buffer.erase(global_buffer_E);
791 global_buffer_E = nullptr;
792 }
793 }
794}
795
796MaterialData::~MaterialData() {
797 MaterialStorage *material_storage = MaterialStorage::get_singleton();
798
799 if (global_buffer_E) {
800 //unregister global buffers
801 material_storage->global_shader_uniforms.materials_using_buffer.erase(global_buffer_E);
802 }
803
804 if (global_texture_E) {
805 //unregister global textures
806
807 for (const KeyValue<StringName, uint64_t> &E : used_global_textures) {
808 GlobalShaderUniforms::Variable *v = material_storage->global_shader_uniforms.variables.getptr(E.key);
809 if (v) {
810 v->texture_materials.erase(self);
811 }
812 }
813 //unregister material from those using global textures
814 material_storage->global_shader_uniforms.materials_using_texture.erase(global_texture_E);
815 }
816
817 if (uniform_buffer) {
818 glDeleteBuffers(1, &uniform_buffer);
819 uniform_buffer = 0;
820 }
821}
822
823void MaterialData::update_textures(const HashMap<StringName, Variant> &p_parameters, const HashMap<StringName, HashMap<int, RID>> &p_default_textures, const Vector<ShaderCompiler::GeneratedCode::Texture> &p_texture_uniforms, RID *p_textures, bool p_is_3d_shader_type) {
824 TextureStorage *texture_storage = TextureStorage::get_singleton();
825 MaterialStorage *material_storage = MaterialStorage::get_singleton();
826
827#ifdef TOOLS_ENABLED
828 Texture *roughness_detect_texture = nullptr;
829 RS::TextureDetectRoughnessChannel roughness_channel = RS::TEXTURE_DETECT_ROUGHNESS_R;
830 Texture *normal_detect_texture = nullptr;
831#endif
832
833 bool uses_global_textures = false;
834 global_textures_pass++;
835
836 for (int i = 0, k = 0; i < p_texture_uniforms.size(); i++) {
837 const StringName &uniform_name = p_texture_uniforms[i].name;
838 int uniform_array_size = p_texture_uniforms[i].array_size;
839
840 Vector<RID> textures;
841
842 if (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||
843 p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||
844 p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {
845 continue;
846 }
847
848 if (p_texture_uniforms[i].global) {
849 uses_global_textures = true;
850
851 GlobalShaderUniforms::Variable *v = material_storage->global_shader_uniforms.variables.getptr(uniform_name);
852 if (v) {
853 if (v->buffer_index >= 0) {
854 WARN_PRINT("Shader uses global parameter texture '" + String(uniform_name) + "', but it changed type and is no longer a texture!.");
855
856 } else {
857 HashMap<StringName, uint64_t>::Iterator E = used_global_textures.find(uniform_name);
858 if (!E) {
859 E = used_global_textures.insert(uniform_name, global_textures_pass);
860 v->texture_materials.insert(self);
861 } else {
862 E->value = global_textures_pass;
863 }
864
865 textures.push_back(v->override.get_type() != Variant::NIL ? v->override : v->value);
866 }
867
868 } else {
869 WARN_PRINT("Shader uses global parameter texture '" + String(uniform_name) + "', but it was removed at some point. Material will not display correctly.");
870 }
871 } else {
872 HashMap<StringName, Variant>::ConstIterator V = p_parameters.find(uniform_name);
873 if (V) {
874 if (V->value.is_array()) {
875 Array array = (Array)V->value;
876 if (uniform_array_size > 0) {
877 for (int j = 0; j < array.size(); j++) {
878 textures.push_back(array[j]);
879 }
880 } else {
881 if (array.size() > 0) {
882 textures.push_back(array[0]);
883 }
884 }
885 } else {
886 textures.push_back(V->value);
887 }
888 }
889
890 if (uniform_array_size > 0) {
891 if (textures.size() < uniform_array_size) {
892 HashMap<StringName, HashMap<int, RID>>::ConstIterator W = p_default_textures.find(uniform_name);
893 for (int j = textures.size(); j < uniform_array_size; j++) {
894 if (W && W->value.has(j)) {
895 textures.push_back(W->value[j]);
896 } else {
897 textures.push_back(RID());
898 }
899 }
900 }
901 } else if (textures.is_empty()) {
902 HashMap<StringName, HashMap<int, RID>>::ConstIterator W = p_default_textures.find(uniform_name);
903 if (W && W->value.has(0)) {
904 textures.push_back(W->value[0]);
905 }
906 }
907 }
908
909 RID gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_WHITE);
910
911 if (textures.is_empty()) {
912 //check default usage
913 switch (p_texture_uniforms[i].type) {
914 case ShaderLanguage::TYPE_ISAMPLER2D:
915 case ShaderLanguage::TYPE_USAMPLER2D:
916 case ShaderLanguage::TYPE_SAMPLER2D: {
917 switch (p_texture_uniforms[i].hint) {
918 case ShaderLanguage::ShaderNode::Uniform::HINT_DEFAULT_BLACK: {
919 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_BLACK);
920 } break;
921 case ShaderLanguage::ShaderNode::Uniform::HINT_DEFAULT_TRANSPARENT: {
922 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_TRANSPARENT);
923 } break;
924 case ShaderLanguage::ShaderNode::Uniform::HINT_ANISOTROPY: {
925 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_ANISO);
926 } break;
927 case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: {
928 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_NORMAL);
929 } break;
930 case ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL: {
931 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_NORMAL);
932 } break;
933 default: {
934 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_WHITE);
935 } break;
936 }
937 } break;
938
939 case ShaderLanguage::TYPE_SAMPLERCUBE: {
940 switch (p_texture_uniforms[i].hint) {
941 case ShaderLanguage::ShaderNode::Uniform::HINT_DEFAULT_BLACK: {
942 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_CUBEMAP_BLACK);
943 } break;
944 default: {
945 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_CUBEMAP_WHITE);
946 } break;
947 }
948 } break;
949 case ShaderLanguage::TYPE_SAMPLERCUBEARRAY: {
950 ERR_PRINT_ONCE("Type: SamplerCubeArray not supported in GL Compatibility rendering backend, please use another type.");
951 } break;
952
953 case ShaderLanguage::TYPE_ISAMPLER3D:
954 case ShaderLanguage::TYPE_USAMPLER3D:
955 case ShaderLanguage::TYPE_SAMPLER3D: {
956 switch (p_texture_uniforms[i].hint) {
957 case ShaderLanguage::ShaderNode::Uniform::HINT_DEFAULT_BLACK: {
958 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_3D_BLACK);
959 } break;
960 default: {
961 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_3D_WHITE);
962 } break;
963 }
964 } break;
965
966 case ShaderLanguage::TYPE_ISAMPLER2DARRAY:
967 case ShaderLanguage::TYPE_USAMPLER2DARRAY:
968 case ShaderLanguage::TYPE_SAMPLER2DARRAY: {
969 gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_2D_ARRAY_WHITE);
970 } break;
971
972 default: {
973 }
974 }
975#ifdef TOOLS_ENABLED
976 if (roughness_detect_texture && normal_detect_texture && !normal_detect_texture->path.is_empty()) {
977 roughness_detect_texture->detect_roughness_callback(roughness_detect_texture->detect_roughness_callback_ud, normal_detect_texture->path, roughness_channel);
978 }
979#endif
980 if (uniform_array_size > 0) {
981 for (int j = 0; j < uniform_array_size; j++) {
982 p_textures[k++] = gl_texture;
983 }
984 } else {
985 p_textures[k++] = gl_texture;
986 }
987 } else {
988 for (int j = 0; j < textures.size(); j++) {
989 Texture *tex = TextureStorage::get_singleton()->get_texture(textures[j]);
990
991 if (tex) {
992 gl_texture = textures[j];
993#ifdef TOOLS_ENABLED
994 if (tex->detect_3d_callback && p_is_3d_shader_type) {
995 tex->detect_3d_callback(tex->detect_3d_callback_ud);
996 }
997 if (tex->detect_normal_callback && (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL || p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL)) {
998 if (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL) {
999 normal_detect_texture = tex;
1000 }
1001 tex->detect_normal_callback(tex->detect_normal_callback_ud);
1002 }
1003 if (tex->detect_roughness_callback && (p_texture_uniforms[i].hint >= ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_R || p_texture_uniforms[i].hint <= ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_GRAY)) {
1004 //find the normal texture
1005 roughness_detect_texture = tex;
1006 roughness_channel = RS::TextureDetectRoughnessChannel(p_texture_uniforms[i].hint - ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_R);
1007 }
1008#endif
1009 }
1010#ifdef TOOLS_ENABLED
1011 if (roughness_detect_texture && normal_detect_texture && !normal_detect_texture->path.is_empty()) {
1012 roughness_detect_texture->detect_roughness_callback(roughness_detect_texture->detect_roughness_callback_ud, normal_detect_texture->path, roughness_channel);
1013 }
1014#endif
1015 p_textures[k++] = gl_texture;
1016 }
1017 }
1018 }
1019 {
1020 //for textures no longer used, unregister them
1021 List<StringName> to_delete;
1022 for (KeyValue<StringName, uint64_t> &E : used_global_textures) {
1023 if (E.value != global_textures_pass) {
1024 to_delete.push_back(E.key);
1025
1026 GlobalShaderUniforms::Variable *v = material_storage->global_shader_uniforms.variables.getptr(E.key);
1027 if (v) {
1028 v->texture_materials.erase(self);
1029 }
1030 }
1031 }
1032
1033 while (to_delete.front()) {
1034 used_global_textures.erase(to_delete.front()->get());
1035 to_delete.pop_front();
1036 }
1037 //handle registering/unregistering global textures
1038 if (uses_global_textures != (global_texture_E != nullptr)) {
1039 if (uses_global_textures) {
1040 global_texture_E = material_storage->global_shader_uniforms.materials_using_texture.push_back(self);
1041 } else {
1042 material_storage->global_shader_uniforms.materials_using_texture.erase(global_texture_E);
1043 global_texture_E = nullptr;
1044 }
1045 }
1046 }
1047}
1048
1049void MaterialData::update_parameters_internal(const HashMap<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty, const HashMap<StringName, ShaderLanguage::ShaderNode::Uniform> &p_uniforms, const uint32_t *p_uniform_offsets, const Vector<ShaderCompiler::GeneratedCode::Texture> &p_texture_uniforms, const HashMap<StringName, HashMap<int, RID>> &p_default_texture_params, uint32_t p_ubo_size, bool p_is_3d_shader_type) {
1050 if ((uint32_t)ubo_data.size() != p_ubo_size) {
1051 p_uniform_dirty = true;
1052 if (!uniform_buffer) {
1053 glGenBuffers(1, &uniform_buffer);
1054 }
1055
1056 ubo_data.resize(p_ubo_size);
1057 if (ubo_data.size()) {
1058 memset(ubo_data.ptrw(), 0, ubo_data.size()); //clear
1059 }
1060 }
1061
1062 //check whether buffer changed
1063 if (p_uniform_dirty && ubo_data.size()) {
1064 update_uniform_buffer(p_uniforms, p_uniform_offsets, p_parameters, ubo_data.ptrw(), ubo_data.size());
1065 glBindBuffer(GL_UNIFORM_BUFFER, uniform_buffer);
1066 glBufferData(GL_UNIFORM_BUFFER, ubo_data.size(), ubo_data.ptrw(), GL_DYNAMIC_DRAW);
1067 glBindBuffer(GL_UNIFORM_BUFFER, 0);
1068 }
1069
1070 uint32_t tex_uniform_count = 0U;
1071 for (int i = 0; i < p_texture_uniforms.size(); i++) {
1072 tex_uniform_count += uint32_t(p_texture_uniforms[i].array_size > 0 ? p_texture_uniforms[i].array_size : 1);
1073 }
1074
1075 if ((uint32_t)texture_cache.size() != tex_uniform_count || p_textures_dirty) {
1076 texture_cache.resize(tex_uniform_count);
1077 p_textures_dirty = true;
1078 }
1079
1080 if (p_textures_dirty && tex_uniform_count) {
1081 update_textures(p_parameters, p_default_texture_params, p_texture_uniforms, texture_cache.ptrw(), p_is_3d_shader_type);
1082 }
1083}
1084
1085///////////////////////////////////////////////////////////////////////////
1086// Material Storage
1087
1088MaterialStorage *MaterialStorage::singleton = nullptr;
1089
1090MaterialStorage *MaterialStorage::get_singleton() {
1091 return singleton;
1092}
1093
1094MaterialStorage::MaterialStorage() {
1095 singleton = this;
1096
1097 shader_data_request_func[RS::SHADER_SPATIAL] = _create_scene_shader_func;
1098 shader_data_request_func[RS::SHADER_CANVAS_ITEM] = _create_canvas_shader_func;
1099 shader_data_request_func[RS::SHADER_PARTICLES] = _create_particles_shader_func;
1100 shader_data_request_func[RS::SHADER_SKY] = _create_sky_shader_func;
1101 shader_data_request_func[RS::SHADER_FOG] = nullptr;
1102
1103 material_data_request_func[RS::SHADER_SPATIAL] = _create_scene_material_func;
1104 material_data_request_func[RS::SHADER_CANVAS_ITEM] = _create_canvas_material_func;
1105 material_data_request_func[RS::SHADER_PARTICLES] = _create_particles_material_func;
1106 material_data_request_func[RS::SHADER_SKY] = _create_sky_material_func;
1107 material_data_request_func[RS::SHADER_FOG] = nullptr;
1108
1109 static_assert(sizeof(GlobalShaderUniforms::Value) == 16);
1110
1111 global_shader_uniforms.buffer_size = MAX(4096, (int)GLOBAL_GET("rendering/limits/global_shader_variables/buffer_size"));
1112 if (global_shader_uniforms.buffer_size > uint32_t(Config::get_singleton()->max_uniform_buffer_size)) {
1113 global_shader_uniforms.buffer_size = uint32_t(Config::get_singleton()->max_uniform_buffer_size);
1114 WARN_PRINT("Project setting \"rendering/limits/global_shader_variables/buffer_size\" exceeds maximum uniform buffer size of: " + itos(Config::get_singleton()->max_uniform_buffer_size));
1115 }
1116
1117 global_shader_uniforms.buffer_values = memnew_arr(GlobalShaderUniforms::Value, global_shader_uniforms.buffer_size);
1118 memset(global_shader_uniforms.buffer_values, 0, sizeof(GlobalShaderUniforms::Value) * global_shader_uniforms.buffer_size);
1119 global_shader_uniforms.buffer_usage = memnew_arr(GlobalShaderUniforms::ValueUsage, global_shader_uniforms.buffer_size);
1120 global_shader_uniforms.buffer_dirty_regions = memnew_arr(bool, global_shader_uniforms.buffer_size / GlobalShaderUniforms::BUFFER_DIRTY_REGION_SIZE);
1121 memset(global_shader_uniforms.buffer_dirty_regions, 0, sizeof(bool) * global_shader_uniforms.buffer_size / GlobalShaderUniforms::BUFFER_DIRTY_REGION_SIZE);
1122 glGenBuffers(1, &global_shader_uniforms.buffer);
1123 glBindBuffer(GL_UNIFORM_BUFFER, global_shader_uniforms.buffer);
1124 glBufferData(GL_UNIFORM_BUFFER, sizeof(GlobalShaderUniforms::Value) * global_shader_uniforms.buffer_size, nullptr, GL_DYNAMIC_DRAW);
1125 glBindBuffer(GL_UNIFORM_BUFFER, 0);
1126
1127 {
1128 // Setup CanvasItem compiler
1129 ShaderCompiler::DefaultIdentifierActions actions;
1130
1131 actions.renames["VERTEX"] = "vertex";
1132 actions.renames["LIGHT_VERTEX"] = "light_vertex";
1133 actions.renames["SHADOW_VERTEX"] = "shadow_vertex";
1134 actions.renames["UV"] = "uv";
1135 actions.renames["POINT_SIZE"] = "point_size";
1136
1137 actions.renames["MODEL_MATRIX"] = "model_matrix";
1138 actions.renames["CANVAS_MATRIX"] = "canvas_transform";
1139 actions.renames["SCREEN_MATRIX"] = "screen_transform";
1140 actions.renames["TIME"] = "time";
1141 actions.renames["PI"] = _MKSTR(Math_PI);
1142 actions.renames["TAU"] = _MKSTR(Math_TAU);
1143 actions.renames["E"] = _MKSTR(Math_E);
1144 actions.renames["AT_LIGHT_PASS"] = "false";
1145 actions.renames["INSTANCE_CUSTOM"] = "instance_custom";
1146
1147 actions.renames["COLOR"] = "color";
1148 actions.renames["NORMAL"] = "normal";
1149 actions.renames["NORMAL_MAP"] = "normal_map";
1150 actions.renames["NORMAL_MAP_DEPTH"] = "normal_map_depth";
1151 actions.renames["TEXTURE"] = "color_texture";
1152 actions.renames["TEXTURE_PIXEL_SIZE"] = "color_texture_pixel_size";
1153 actions.renames["NORMAL_TEXTURE"] = "normal_texture";
1154 actions.renames["SPECULAR_SHININESS_TEXTURE"] = "specular_texture";
1155 actions.renames["SPECULAR_SHININESS"] = "specular_shininess";
1156 actions.renames["SCREEN_UV"] = "screen_uv";
1157 actions.renames["SCREEN_PIXEL_SIZE"] = "screen_pixel_size";
1158 actions.renames["FRAGCOORD"] = "gl_FragCoord";
1159 actions.renames["POINT_COORD"] = "gl_PointCoord";
1160 actions.renames["INSTANCE_ID"] = "gl_InstanceIndex";
1161 actions.renames["VERTEX_ID"] = "gl_VertexIndex";
1162
1163 actions.renames["LIGHT_POSITION"] = "light_position";
1164 actions.renames["LIGHT_DIRECTION"] = "light_direction";
1165 actions.renames["LIGHT_IS_DIRECTIONAL"] = "is_directional";
1166 actions.renames["LIGHT_COLOR"] = "light_color";
1167 actions.renames["LIGHT_ENERGY"] = "light_energy";
1168 actions.renames["LIGHT"] = "light";
1169 actions.renames["SHADOW_MODULATE"] = "shadow_modulate";
1170
1171 actions.renames["texture_sdf"] = "texture_sdf";
1172 actions.renames["texture_sdf_normal"] = "texture_sdf_normal";
1173 actions.renames["sdf_to_screen_uv"] = "sdf_to_screen_uv";
1174 actions.renames["screen_uv_to_sdf"] = "screen_uv_to_sdf";
1175
1176 actions.usage_defines["COLOR"] = "#define COLOR_USED\n";
1177 actions.usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";
1178 actions.usage_defines["SCREEN_PIXEL_SIZE"] = "@SCREEN_UV";
1179 actions.usage_defines["NORMAL"] = "#define NORMAL_USED\n";
1180 actions.usage_defines["NORMAL_MAP"] = "#define NORMAL_MAP_USED\n";
1181 actions.usage_defines["LIGHT"] = "#define LIGHT_SHADER_CODE_USED\n";
1182 actions.usage_defines["SPECULAR_SHININESS"] = "#define SPECULAR_SHININESS_USED\n";
1183
1184 actions.render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n";
1185 actions.render_mode_defines["unshaded"] = "#define MODE_UNSHADED\n";
1186 actions.render_mode_defines["light_only"] = "#define MODE_LIGHT_ONLY\n";
1187
1188 actions.global_buffer_array_variable = "global_shader_uniforms";
1189
1190 shaders.compiler_canvas.initialize(actions);
1191 }
1192
1193 {
1194 // Setup Scene compiler
1195
1196 //shader compiler
1197 ShaderCompiler::DefaultIdentifierActions actions;
1198
1199 actions.renames["MODEL_MATRIX"] = "model_matrix";
1200 actions.renames["MODEL_NORMAL_MATRIX"] = "model_normal_matrix";
1201 actions.renames["VIEW_MATRIX"] = "scene_data.view_matrix";
1202 actions.renames["INV_VIEW_MATRIX"] = "scene_data.inv_view_matrix";
1203 actions.renames["PROJECTION_MATRIX"] = "projection_matrix";
1204 actions.renames["INV_PROJECTION_MATRIX"] = "inv_projection_matrix";
1205 actions.renames["MODELVIEW_MATRIX"] = "modelview";
1206 actions.renames["MODELVIEW_NORMAL_MATRIX"] = "modelview_normal";
1207
1208 actions.renames["VERTEX"] = "vertex";
1209 actions.renames["NORMAL"] = "normal";
1210 actions.renames["TANGENT"] = "tangent";
1211 actions.renames["BINORMAL"] = "binormal";
1212 actions.renames["POSITION"] = "position";
1213 actions.renames["UV"] = "uv_interp";
1214 actions.renames["UV2"] = "uv2_interp";
1215 actions.renames["COLOR"] = "color_interp";
1216 actions.renames["POINT_SIZE"] = "point_size";
1217 actions.renames["INSTANCE_ID"] = "gl_InstanceID";
1218 actions.renames["VERTEX_ID"] = "gl_VertexID";
1219
1220 actions.renames["ALPHA_SCISSOR_THRESHOLD"] = "alpha_scissor_threshold";
1221 actions.renames["ALPHA_HASH_SCALE"] = "alpha_hash_scale";
1222 actions.renames["ALPHA_ANTIALIASING_EDGE"] = "alpha_antialiasing_edge";
1223 actions.renames["ALPHA_TEXTURE_COORDINATE"] = "alpha_texture_coordinate";
1224
1225 //builtins
1226
1227 actions.renames["TIME"] = "scene_data.time";
1228 actions.renames["EXPOSURE"] = "(1.0 / scene_data.emissive_exposure_normalization)";
1229 actions.renames["PI"] = _MKSTR(Math_PI);
1230 actions.renames["TAU"] = _MKSTR(Math_TAU);
1231 actions.renames["E"] = _MKSTR(Math_E);
1232 actions.renames["VIEWPORT_SIZE"] = "scene_data.viewport_size";
1233
1234 actions.renames["FRAGCOORD"] = "gl_FragCoord";
1235 actions.renames["FRONT_FACING"] = "gl_FrontFacing";
1236 actions.renames["NORMAL_MAP"] = "normal_map";
1237 actions.renames["NORMAL_MAP_DEPTH"] = "normal_map_depth";
1238 actions.renames["ALBEDO"] = "albedo";
1239 actions.renames["ALPHA"] = "alpha";
1240 actions.renames["METALLIC"] = "metallic";
1241 actions.renames["SPECULAR"] = "specular";
1242 actions.renames["ROUGHNESS"] = "roughness";
1243 actions.renames["RIM"] = "rim";
1244 actions.renames["RIM_TINT"] = "rim_tint";
1245 actions.renames["CLEARCOAT"] = "clearcoat";
1246 actions.renames["CLEARCOAT_ROUGHNESS"] = "clearcoat_roughness";
1247 actions.renames["ANISOTROPY"] = "anisotropy";
1248 actions.renames["ANISOTROPY_FLOW"] = "anisotropy_flow";
1249 actions.renames["SSS_STRENGTH"] = "sss_strength";
1250 actions.renames["SSS_TRANSMITTANCE_COLOR"] = "transmittance_color";
1251 actions.renames["SSS_TRANSMITTANCE_DEPTH"] = "transmittance_depth";
1252 actions.renames["SSS_TRANSMITTANCE_BOOST"] = "transmittance_boost";
1253 actions.renames["BACKLIGHT"] = "backlight";
1254 actions.renames["AO"] = "ao";
1255 actions.renames["AO_LIGHT_AFFECT"] = "ao_light_affect";
1256 actions.renames["EMISSION"] = "emission";
1257 actions.renames["POINT_COORD"] = "gl_PointCoord";
1258 actions.renames["INSTANCE_CUSTOM"] = "instance_custom";
1259 actions.renames["SCREEN_UV"] = "screen_uv";
1260 actions.renames["DEPTH"] = "gl_FragDepth";
1261 actions.renames["FOG"] = "fog";
1262 actions.renames["RADIANCE"] = "custom_radiance";
1263 actions.renames["IRRADIANCE"] = "custom_irradiance";
1264 actions.renames["BONE_INDICES"] = "bone_attrib";
1265 actions.renames["BONE_WEIGHTS"] = "weight_attrib";
1266 actions.renames["CUSTOM0"] = "custom0_attrib";
1267 actions.renames["CUSTOM1"] = "custom1_attrib";
1268 actions.renames["CUSTOM2"] = "custom2_attrib";
1269 actions.renames["CUSTOM3"] = "custom3_attrib";
1270 actions.renames["OUTPUT_IS_SRGB"] = "SHADER_IS_SRGB";
1271
1272 actions.renames["NODE_POSITION_WORLD"] = "model_matrix[3].xyz";
1273 actions.renames["CAMERA_POSITION_WORLD"] = "scene_data.inv_view_matrix[3].xyz";
1274 actions.renames["CAMERA_DIRECTION_WORLD"] = "scene_data.view_matrix[3].xyz";
1275 actions.renames["CAMERA_VISIBLE_LAYERS"] = "scene_data.camera_visible_layers";
1276 actions.renames["NODE_POSITION_VIEW"] = "(scene_data.view_matrix * model_matrix)[3].xyz";
1277
1278 actions.renames["VIEW_INDEX"] = "ViewIndex";
1279 actions.renames["VIEW_MONO_LEFT"] = "uint(0)";
1280 actions.renames["VIEW_RIGHT"] = "uint(1)";
1281 actions.renames["EYE_OFFSET"] = "eye_offset";
1282
1283 //for light
1284 actions.renames["VIEW"] = "view";
1285 actions.renames["SPECULAR_AMOUNT"] = "specular_amount";
1286 actions.renames["LIGHT_COLOR"] = "light_color";
1287 actions.renames["LIGHT_IS_DIRECTIONAL"] = "is_directional";
1288 actions.renames["LIGHT"] = "light";
1289 actions.renames["ATTENUATION"] = "attenuation";
1290 actions.renames["DIFFUSE_LIGHT"] = "diffuse_light";
1291 actions.renames["SPECULAR_LIGHT"] = "specular_light";
1292
1293 actions.usage_defines["NORMAL"] = "#define NORMAL_USED\n";
1294 actions.usage_defines["TANGENT"] = "#define TANGENT_USED\n";
1295 actions.usage_defines["BINORMAL"] = "@TANGENT";
1296 actions.usage_defines["RIM"] = "#define LIGHT_RIM_USED\n";
1297 actions.usage_defines["RIM_TINT"] = "@RIM";
1298 actions.usage_defines["CLEARCOAT"] = "#define LIGHT_CLEARCOAT_USED\n";
1299 actions.usage_defines["CLEARCOAT_ROUGHNESS"] = "@CLEARCOAT";
1300 actions.usage_defines["ANISOTROPY"] = "#define LIGHT_ANISOTROPY_USED\n";
1301 actions.usage_defines["ANISOTROPY_FLOW"] = "@ANISOTROPY";
1302 actions.usage_defines["AO"] = "#define AO_USED\n";
1303 actions.usage_defines["AO_LIGHT_AFFECT"] = "#define AO_USED\n";
1304 actions.usage_defines["UV"] = "#define UV_USED\n";
1305 actions.usage_defines["UV2"] = "#define UV2_USED\n";
1306 actions.usage_defines["BONE_INDICES"] = "#define BONES_USED\n";
1307 actions.usage_defines["BONE_WEIGHTS"] = "#define WEIGHTS_USED\n";
1308 actions.usage_defines["CUSTOM0"] = "#define CUSTOM0_USED\n";
1309 actions.usage_defines["CUSTOM1"] = "#define CUSTOM1_USED\n";
1310 actions.usage_defines["CUSTOM2"] = "#define CUSTOM2_USED\n";
1311 actions.usage_defines["CUSTOM3"] = "#define CUSTOM3_USED\n";
1312 actions.usage_defines["NORMAL_MAP"] = "#define NORMAL_MAP_USED\n";
1313 actions.usage_defines["NORMAL_MAP_DEPTH"] = "@NORMAL_MAP";
1314 actions.usage_defines["COLOR"] = "#define COLOR_USED\n";
1315 actions.usage_defines["INSTANCE_CUSTOM"] = "#define ENABLE_INSTANCE_CUSTOM\n";
1316 actions.usage_defines["POSITION"] = "#define OVERRIDE_POSITION\n";
1317
1318 actions.usage_defines["ALPHA_SCISSOR_THRESHOLD"] = "#define ALPHA_SCISSOR_USED\n";
1319 actions.usage_defines["ALPHA_HASH_SCALE"] = "#define ALPHA_HASH_USED\n";
1320 actions.usage_defines["ALPHA_ANTIALIASING_EDGE"] = "#define ALPHA_ANTIALIASING_EDGE_USED\n";
1321 actions.usage_defines["ALPHA_TEXTURE_COORDINATE"] = "@ALPHA_ANTIALIASING_EDGE";
1322
1323 actions.usage_defines["SSS_STRENGTH"] = "#define ENABLE_SSS\n";
1324 actions.usage_defines["SSS_TRANSMITTANCE_DEPTH"] = "#define ENABLE_TRANSMITTANCE\n";
1325 actions.usage_defines["BACKLIGHT"] = "#define LIGHT_BACKLIGHT_USED\n";
1326 actions.usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";
1327
1328 actions.usage_defines["DIFFUSE_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n";
1329 actions.usage_defines["SPECULAR_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n";
1330
1331 actions.usage_defines["FOG"] = "#define CUSTOM_FOG_USED\n";
1332 actions.usage_defines["RADIANCE"] = "#define CUSTOM_RADIANCE_USED\n";
1333 actions.usage_defines["IRRADIANCE"] = "#define CUSTOM_IRRADIANCE_USED\n";
1334
1335 actions.render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n";
1336 actions.render_mode_defines["world_vertex_coords"] = "#define VERTEX_WORLD_COORDS_USED\n";
1337 actions.render_mode_defines["ensure_correct_normals"] = "#define ENSURE_CORRECT_NORMALS\n";
1338 actions.render_mode_defines["cull_front"] = "#define DO_SIDE_CHECK\n";
1339 actions.render_mode_defines["cull_disabled"] = "#define DO_SIDE_CHECK\n";
1340 actions.render_mode_defines["particle_trails"] = "#define USE_PARTICLE_TRAILS\n";
1341 actions.render_mode_defines["depth_prepass_alpha"] = "#define USE_OPAQUE_PREPASS\n";
1342
1343 bool force_lambert = GLOBAL_GET("rendering/shading/overrides/force_lambert_over_burley");
1344
1345 if (!force_lambert) {
1346 actions.render_mode_defines["diffuse_burley"] = "#define DIFFUSE_BURLEY\n";
1347 }
1348
1349 actions.render_mode_defines["diffuse_lambert_wrap"] = "#define DIFFUSE_LAMBERT_WRAP\n";
1350 actions.render_mode_defines["diffuse_toon"] = "#define DIFFUSE_TOON\n";
1351
1352 actions.render_mode_defines["sss_mode_skin"] = "#define SSS_MODE_SKIN\n";
1353
1354 actions.render_mode_defines["specular_schlick_ggx"] = "#define SPECULAR_SCHLICK_GGX\n";
1355 actions.render_mode_defines["specular_toon"] = "#define SPECULAR_TOON\n";
1356 actions.render_mode_defines["specular_disabled"] = "#define SPECULAR_DISABLED\n";
1357 actions.render_mode_defines["shadows_disabled"] = "#define SHADOWS_DISABLED\n";
1358 actions.render_mode_defines["ambient_light_disabled"] = "#define AMBIENT_LIGHT_DISABLED\n";
1359 actions.render_mode_defines["shadow_to_opacity"] = "#define USE_SHADOW_TO_OPACITY\n";
1360 actions.render_mode_defines["unshaded"] = "#define MODE_UNSHADED\n";
1361 actions.render_mode_defines["fog_disabled"] = "#define FOG_DISABLED\n";
1362
1363 actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
1364 actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
1365
1366 actions.check_multiview_samplers = RasterizerGLES3::get_singleton()->is_xr_enabled();
1367 actions.global_buffer_array_variable = "global_shader_uniforms";
1368
1369 shaders.compiler_scene.initialize(actions);
1370 }
1371
1372 {
1373 // Setup Particles compiler
1374
1375 ShaderCompiler::DefaultIdentifierActions actions;
1376
1377 actions.renames["COLOR"] = "out_color";
1378 actions.renames["VELOCITY"] = "out_velocity_flags.xyz";
1379 //actions.renames["MASS"] = "mass"; ?
1380 actions.renames["ACTIVE"] = "particle_active";
1381 actions.renames["RESTART"] = "restart";
1382 actions.renames["CUSTOM"] = "out_custom";
1383 for (int i = 0; i < PARTICLES_MAX_USERDATAS; i++) {
1384 String udname = "USERDATA" + itos(i + 1);
1385 actions.renames[udname] = "out_userdata" + itos(i + 1);
1386 actions.usage_defines[udname] = "#define USERDATA" + itos(i + 1) + "_USED\n";
1387 }
1388 actions.renames["TRANSFORM"] = "xform";
1389 actions.renames["TIME"] = "time";
1390 actions.renames["PI"] = _MKSTR(Math_PI);
1391 actions.renames["TAU"] = _MKSTR(Math_TAU);
1392 actions.renames["E"] = _MKSTR(Math_E);
1393 actions.renames["LIFETIME"] = "lifetime";
1394 actions.renames["DELTA"] = "local_delta";
1395 actions.renames["NUMBER"] = "particle_number";
1396 actions.renames["INDEX"] = "index";
1397 //actions.renames["GRAVITY"] = "current_gravity";
1398 actions.renames["EMISSION_TRANSFORM"] = "emission_transform";
1399 actions.renames["RANDOM_SEED"] = "random_seed";
1400 actions.renames["RESTART_POSITION"] = "restart_position";
1401 actions.renames["RESTART_ROT_SCALE"] = "restart_rotation_scale";
1402 actions.renames["RESTART_VELOCITY"] = "restart_velocity";
1403 actions.renames["RESTART_COLOR"] = "restart_color";
1404 actions.renames["RESTART_CUSTOM"] = "restart_custom";
1405 actions.renames["COLLIDED"] = "collided";
1406 actions.renames["COLLISION_NORMAL"] = "collision_normal";
1407 actions.renames["COLLISION_DEPTH"] = "collision_depth";
1408 actions.renames["ATTRACTOR_FORCE"] = "attractor_force";
1409
1410 // These are unsupported, but may be used by users. To avoid compile time overhead, we add the stub only when used.
1411 actions.renames["FLAG_EMIT_POSITION"] = "uint(1)";
1412 actions.renames["FLAG_EMIT_ROT_SCALE"] = "uint(2)";
1413 actions.renames["FLAG_EMIT_VELOCITY"] = "uint(4)";
1414 actions.renames["FLAG_EMIT_COLOR"] = "uint(8)";
1415 actions.renames["FLAG_EMIT_CUSTOM"] = "uint(16)";
1416 actions.renames["emit_subparticle"] = "emit_subparticle";
1417 actions.usage_defines["emit_subparticle"] = "\nbool emit_subparticle(mat4 p_xform, vec3 p_velocity, vec4 p_color, vec4 p_custom, uint p_flags) {\n\treturn false;\n}\n";
1418
1419 actions.render_mode_defines["disable_force"] = "#define DISABLE_FORCE\n";
1420 actions.render_mode_defines["disable_velocity"] = "#define DISABLE_VELOCITY\n";
1421 actions.render_mode_defines["keep_data"] = "#define ENABLE_KEEP_DATA\n";
1422 actions.render_mode_defines["collision_use_scale"] = "#define USE_COLLISION_SCALE\n";
1423
1424 actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
1425 actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
1426
1427 actions.global_buffer_array_variable = "global_shader_uniforms";
1428
1429 shaders.compiler_particles.initialize(actions);
1430 }
1431
1432 {
1433 // Setup Sky compiler
1434 ShaderCompiler::DefaultIdentifierActions actions;
1435
1436 actions.renames["COLOR"] = "color";
1437 actions.renames["ALPHA"] = "alpha";
1438 actions.renames["EYEDIR"] = "cube_normal";
1439 actions.renames["POSITION"] = "position";
1440 actions.renames["SKY_COORDS"] = "panorama_coords";
1441 actions.renames["SCREEN_UV"] = "uv";
1442 actions.renames["TIME"] = "time";
1443 actions.renames["FRAGCOORD"] = "gl_FragCoord";
1444 actions.renames["PI"] = _MKSTR(Math_PI);
1445 actions.renames["TAU"] = _MKSTR(Math_TAU);
1446 actions.renames["E"] = _MKSTR(Math_E);
1447 actions.renames["HALF_RES_COLOR"] = "half_res_color";
1448 actions.renames["QUARTER_RES_COLOR"] = "quarter_res_color";
1449 actions.renames["RADIANCE"] = "radiance";
1450 actions.renames["FOG"] = "custom_fog";
1451 actions.renames["LIGHT0_ENABLED"] = "directional_lights.data[0].enabled";
1452 actions.renames["LIGHT0_DIRECTION"] = "directional_lights.data[0].direction_energy.xyz";
1453 actions.renames["LIGHT0_ENERGY"] = "directional_lights.data[0].direction_energy.w";
1454 actions.renames["LIGHT0_COLOR"] = "directional_lights.data[0].color_size.xyz";
1455 actions.renames["LIGHT0_SIZE"] = "directional_lights.data[0].color_size.w";
1456 actions.renames["LIGHT1_ENABLED"] = "directional_lights.data[1].enabled";
1457 actions.renames["LIGHT1_DIRECTION"] = "directional_lights.data[1].direction_energy.xyz";
1458 actions.renames["LIGHT1_ENERGY"] = "directional_lights.data[1].direction_energy.w";
1459 actions.renames["LIGHT1_COLOR"] = "directional_lights.data[1].color_size.xyz";
1460 actions.renames["LIGHT1_SIZE"] = "directional_lights.data[1].color_size.w";
1461 actions.renames["LIGHT2_ENABLED"] = "directional_lights.data[2].enabled";
1462 actions.renames["LIGHT2_DIRECTION"] = "directional_lights.data[2].direction_energy.xyz";
1463 actions.renames["LIGHT2_ENERGY"] = "directional_lights.data[2].direction_energy.w";
1464 actions.renames["LIGHT2_COLOR"] = "directional_lights.data[2].color_size.xyz";
1465 actions.renames["LIGHT2_SIZE"] = "directional_lights.data[2].color_size.w";
1466 actions.renames["LIGHT3_ENABLED"] = "directional_lights.data[3].enabled";
1467 actions.renames["LIGHT3_DIRECTION"] = "directional_lights.data[3].direction_energy.xyz";
1468 actions.renames["LIGHT3_ENERGY"] = "directional_lights.data[3].direction_energy.w";
1469 actions.renames["LIGHT3_COLOR"] = "directional_lights.data[3].color_size.xyz";
1470 actions.renames["LIGHT3_SIZE"] = "directional_lights.data[3].color_size.w";
1471 actions.renames["AT_CUBEMAP_PASS"] = "AT_CUBEMAP_PASS";
1472 actions.renames["AT_HALF_RES_PASS"] = "AT_HALF_RES_PASS";
1473 actions.renames["AT_QUARTER_RES_PASS"] = "AT_QUARTER_RES_PASS";
1474 actions.usage_defines["HALF_RES_COLOR"] = "\n#define USES_HALF_RES_COLOR\n";
1475 actions.usage_defines["QUARTER_RES_COLOR"] = "\n#define USES_QUARTER_RES_COLOR\n";
1476 actions.render_mode_defines["disable_fog"] = "#define DISABLE_FOG\n";
1477 actions.render_mode_defines["use_debanding"] = "#define USE_DEBANDING\n";
1478
1479 actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
1480 actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
1481
1482 actions.global_buffer_array_variable = "global_shader_uniforms";
1483
1484 shaders.compiler_sky.initialize(actions);
1485 }
1486}
1487
1488MaterialStorage::~MaterialStorage() {
1489 //shaders.copy.version_free(shaders.copy_version);
1490
1491 memdelete_arr(global_shader_uniforms.buffer_values);
1492 memdelete_arr(global_shader_uniforms.buffer_usage);
1493 memdelete_arr(global_shader_uniforms.buffer_dirty_regions);
1494 glDeleteBuffers(1, &global_shader_uniforms.buffer);
1495
1496 singleton = nullptr;
1497}
1498
1499/* GLOBAL SHADER UNIFORM API */
1500
1501int32_t MaterialStorage::_global_shader_uniform_allocate(uint32_t p_elements) {
1502 int32_t idx = 0;
1503 while (idx + p_elements <= global_shader_uniforms.buffer_size) {
1504 if (global_shader_uniforms.buffer_usage[idx].elements == 0) {
1505 bool valid = true;
1506 for (uint32_t i = 1; i < p_elements; i++) {
1507 if (global_shader_uniforms.buffer_usage[idx + i].elements > 0) {
1508 valid = false;
1509 idx += i + global_shader_uniforms.buffer_usage[idx + i].elements;
1510 break;
1511 }
1512 }
1513
1514 if (!valid) {
1515 continue; //if not valid, idx is in new position
1516 }
1517
1518 return idx;
1519 } else {
1520 idx += global_shader_uniforms.buffer_usage[idx].elements;
1521 }
1522 }
1523
1524 return -1;
1525}
1526
1527void MaterialStorage::_global_shader_uniform_store_in_buffer(int32_t p_index, RS::GlobalShaderParameterType p_type, const Variant &p_value) {
1528 switch (p_type) {
1529 case RS::GLOBAL_VAR_TYPE_BOOL: {
1530 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1531 bool b = p_value;
1532 bv.x = b ? 1.0 : 0.0;
1533 bv.y = 0.0;
1534 bv.z = 0.0;
1535 bv.w = 0.0;
1536
1537 } break;
1538 case RS::GLOBAL_VAR_TYPE_BVEC2: {
1539 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1540 uint32_t bvec = p_value;
1541 bv.x = (bvec & 1) ? 1.0 : 0.0;
1542 bv.y = (bvec & 2) ? 1.0 : 0.0;
1543 bv.z = 0.0;
1544 bv.w = 0.0;
1545 } break;
1546 case RS::GLOBAL_VAR_TYPE_BVEC3: {
1547 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1548 uint32_t bvec = p_value;
1549 bv.x = (bvec & 1) ? 1.0 : 0.0;
1550 bv.y = (bvec & 2) ? 1.0 : 0.0;
1551 bv.z = (bvec & 4) ? 1.0 : 0.0;
1552 bv.w = 0.0;
1553 } break;
1554 case RS::GLOBAL_VAR_TYPE_BVEC4: {
1555 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1556 uint32_t bvec = p_value;
1557 bv.x = (bvec & 1) ? 1.0 : 0.0;
1558 bv.y = (bvec & 2) ? 1.0 : 0.0;
1559 bv.z = (bvec & 4) ? 1.0 : 0.0;
1560 bv.w = (bvec & 8) ? 1.0 : 0.0;
1561 } break;
1562 case RS::GLOBAL_VAR_TYPE_INT: {
1563 GlobalShaderUniforms::ValueInt &bv = *(GlobalShaderUniforms::ValueInt *)&global_shader_uniforms.buffer_values[p_index];
1564 int32_t v = p_value;
1565 bv.x = v;
1566 bv.y = 0;
1567 bv.z = 0;
1568 bv.w = 0;
1569 } break;
1570 case RS::GLOBAL_VAR_TYPE_IVEC2: {
1571 GlobalShaderUniforms::ValueInt &bv = *(GlobalShaderUniforms::ValueInt *)&global_shader_uniforms.buffer_values[p_index];
1572 Vector2i v = convert_to_vector<Vector2i>(p_value);
1573 bv.x = v.x;
1574 bv.y = v.y;
1575 bv.z = 0;
1576 bv.w = 0;
1577 } break;
1578 case RS::GLOBAL_VAR_TYPE_IVEC3: {
1579 GlobalShaderUniforms::ValueInt &bv = *(GlobalShaderUniforms::ValueInt *)&global_shader_uniforms.buffer_values[p_index];
1580 Vector3i v = convert_to_vector<Vector3i>(p_value);
1581 bv.x = v.x;
1582 bv.y = v.y;
1583 bv.z = v.z;
1584 bv.w = 0;
1585 } break;
1586 case RS::GLOBAL_VAR_TYPE_IVEC4: {
1587 GlobalShaderUniforms::ValueInt &bv = *(GlobalShaderUniforms::ValueInt *)&global_shader_uniforms.buffer_values[p_index];
1588 Vector4i v = convert_to_vector<Vector4i>(p_value);
1589 bv.x = v.x;
1590 bv.y = v.y;
1591 bv.z = v.z;
1592 bv.w = v.w;
1593 } break;
1594 case RS::GLOBAL_VAR_TYPE_RECT2I: {
1595 GlobalShaderUniforms::ValueInt &bv = *(GlobalShaderUniforms::ValueInt *)&global_shader_uniforms.buffer_values[p_index];
1596 Rect2i v = p_value;
1597 bv.x = v.position.x;
1598 bv.y = v.position.y;
1599 bv.z = v.size.x;
1600 bv.w = v.size.y;
1601 } break;
1602 case RS::GLOBAL_VAR_TYPE_UINT: {
1603 GlobalShaderUniforms::ValueUInt &bv = *(GlobalShaderUniforms::ValueUInt *)&global_shader_uniforms.buffer_values[p_index];
1604 uint32_t v = p_value;
1605 bv.x = v;
1606 bv.y = 0;
1607 bv.z = 0;
1608 bv.w = 0;
1609 } break;
1610 case RS::GLOBAL_VAR_TYPE_UVEC2: {
1611 GlobalShaderUniforms::ValueUInt &bv = *(GlobalShaderUniforms::ValueUInt *)&global_shader_uniforms.buffer_values[p_index];
1612 Vector2i v = convert_to_vector<Vector2i>(p_value);
1613 bv.x = v.x;
1614 bv.y = v.y;
1615 bv.z = 0;
1616 bv.w = 0;
1617 } break;
1618 case RS::GLOBAL_VAR_TYPE_UVEC3: {
1619 GlobalShaderUniforms::ValueUInt &bv = *(GlobalShaderUniforms::ValueUInt *)&global_shader_uniforms.buffer_values[p_index];
1620 Vector3i v = convert_to_vector<Vector3i>(p_value);
1621 bv.x = v.x;
1622 bv.y = v.y;
1623 bv.z = v.z;
1624 bv.w = 0;
1625 } break;
1626 case RS::GLOBAL_VAR_TYPE_UVEC4: {
1627 GlobalShaderUniforms::ValueUInt &bv = *(GlobalShaderUniforms::ValueUInt *)&global_shader_uniforms.buffer_values[p_index];
1628 Vector4i v = convert_to_vector<Vector4i>(p_value);
1629 bv.x = v.x;
1630 bv.y = v.y;
1631 bv.z = v.z;
1632 bv.w = v.w;
1633 } break;
1634 case RS::GLOBAL_VAR_TYPE_FLOAT: {
1635 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1636 float v = p_value;
1637 bv.x = v;
1638 bv.y = 0;
1639 bv.z = 0;
1640 bv.w = 0;
1641 } break;
1642 case RS::GLOBAL_VAR_TYPE_VEC2: {
1643 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1644 Vector2 v = convert_to_vector<Vector2>(p_value);
1645 bv.x = v.x;
1646 bv.y = v.y;
1647 bv.z = 0;
1648 bv.w = 0;
1649 } break;
1650 case RS::GLOBAL_VAR_TYPE_VEC3: {
1651 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1652 Vector3 v = convert_to_vector<Vector3>(p_value);
1653 bv.x = v.x;
1654 bv.y = v.y;
1655 bv.z = v.z;
1656 bv.w = 0;
1657 } break;
1658 case RS::GLOBAL_VAR_TYPE_VEC4: {
1659 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1660 Vector4 v = convert_to_vector<Vector4>(p_value);
1661 bv.x = v.x;
1662 bv.y = v.y;
1663 bv.z = v.z;
1664 bv.w = v.w;
1665 } break;
1666 case RS::GLOBAL_VAR_TYPE_COLOR: {
1667 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1668 Color v = p_value;
1669 bv.x = v.r;
1670 bv.y = v.g;
1671 bv.z = v.b;
1672 bv.w = v.a;
1673
1674 GlobalShaderUniforms::Value &bv_linear = global_shader_uniforms.buffer_values[p_index + 1];
1675 //v = v.srgb_to_linear();
1676 bv_linear.x = v.r;
1677 bv_linear.y = v.g;
1678 bv_linear.z = v.b;
1679 bv_linear.w = v.a;
1680
1681 } break;
1682 case RS::GLOBAL_VAR_TYPE_RECT2: {
1683 GlobalShaderUniforms::Value &bv = global_shader_uniforms.buffer_values[p_index];
1684 Rect2 v = p_value;
1685 bv.x = v.position.x;
1686 bv.y = v.position.y;
1687 bv.z = v.size.x;
1688 bv.w = v.size.y;
1689 } break;
1690 case RS::GLOBAL_VAR_TYPE_MAT2: {
1691 GlobalShaderUniforms::Value *bv = &global_shader_uniforms.buffer_values[p_index];
1692 Vector<float> m2 = p_value;
1693 if (m2.size() < 4) {
1694 m2.resize(4);
1695 }
1696 bv[0].x = m2[0];
1697 bv[0].y = m2[1];
1698 bv[0].z = 0;
1699 bv[0].w = 0;
1700
1701 bv[1].x = m2[2];
1702 bv[1].y = m2[3];
1703 bv[1].z = 0;
1704 bv[1].w = 0;
1705
1706 } break;
1707 case RS::GLOBAL_VAR_TYPE_MAT3: {
1708 GlobalShaderUniforms::Value *bv = &global_shader_uniforms.buffer_values[p_index];
1709 Basis v = p_value;
1710 convert_item_std140<Basis>(v, &bv->x);
1711
1712 } break;
1713 case RS::GLOBAL_VAR_TYPE_MAT4: {
1714 GlobalShaderUniforms::Value *bv = &global_shader_uniforms.buffer_values[p_index];
1715 Projection m = p_value;
1716 convert_item_std140<Projection>(m, &bv->x);
1717
1718 } break;
1719 case RS::GLOBAL_VAR_TYPE_TRANSFORM_2D: {
1720 GlobalShaderUniforms::Value *bv = &global_shader_uniforms.buffer_values[p_index];
1721 Transform2D v = p_value;
1722 convert_item_std140<Transform2D>(v, &bv->x);
1723
1724 } break;
1725 case RS::GLOBAL_VAR_TYPE_TRANSFORM: {
1726 GlobalShaderUniforms::Value *bv = &global_shader_uniforms.buffer_values[p_index];
1727 Transform3D v = p_value;
1728 convert_item_std140<Transform3D>(v, &bv->x);
1729
1730 } break;
1731 default: {
1732 ERR_FAIL();
1733 }
1734 }
1735}
1736
1737void MaterialStorage::_global_shader_uniform_mark_buffer_dirty(int32_t p_index, int32_t p_elements) {
1738 int32_t prev_chunk = -1;
1739
1740 for (int32_t i = 0; i < p_elements; i++) {
1741 int32_t chunk = (p_index + i) / GlobalShaderUniforms::BUFFER_DIRTY_REGION_SIZE;
1742 if (chunk != prev_chunk) {
1743 if (!global_shader_uniforms.buffer_dirty_regions[chunk]) {
1744 global_shader_uniforms.buffer_dirty_regions[chunk] = true;
1745 global_shader_uniforms.buffer_dirty_region_count++;
1746 }
1747 }
1748
1749 prev_chunk = chunk;
1750 }
1751}
1752
1753void MaterialStorage::global_shader_parameter_add(const StringName &p_name, RS::GlobalShaderParameterType p_type, const Variant &p_value) {
1754 ERR_FAIL_COND(global_shader_uniforms.variables.has(p_name));
1755 GlobalShaderUniforms::Variable gv;
1756 gv.type = p_type;
1757 gv.value = p_value;
1758 gv.buffer_index = -1;
1759
1760 if (p_type >= RS::GLOBAL_VAR_TYPE_SAMPLER2D) {
1761 //is texture
1762 global_shader_uniforms.must_update_texture_materials = true; //normally there are none
1763 } else {
1764 gv.buffer_elements = 1;
1765 if (p_type == RS::GLOBAL_VAR_TYPE_COLOR || p_type == RS::GLOBAL_VAR_TYPE_MAT2) {
1766 //color needs to elements to store srgb and linear
1767 gv.buffer_elements = 2;
1768 }
1769 if (p_type == RS::GLOBAL_VAR_TYPE_MAT3 || p_type == RS::GLOBAL_VAR_TYPE_TRANSFORM_2D) {
1770 //color needs to elements to store srgb and linear
1771 gv.buffer_elements = 3;
1772 }
1773 if (p_type == RS::GLOBAL_VAR_TYPE_MAT4 || p_type == RS::GLOBAL_VAR_TYPE_TRANSFORM) {
1774 //color needs to elements to store srgb and linear
1775 gv.buffer_elements = 4;
1776 }
1777
1778 //is vector, allocate in buffer and update index
1779 gv.buffer_index = _global_shader_uniform_allocate(gv.buffer_elements);
1780 ERR_FAIL_COND_MSG(gv.buffer_index < 0, vformat("Failed allocating global variable '%s' out of buffer memory. Consider increasing it in the Project Settings.", String(p_name)));
1781 global_shader_uniforms.buffer_usage[gv.buffer_index].elements = gv.buffer_elements;
1782 _global_shader_uniform_store_in_buffer(gv.buffer_index, gv.type, gv.value);
1783 _global_shader_uniform_mark_buffer_dirty(gv.buffer_index, gv.buffer_elements);
1784
1785 global_shader_uniforms.must_update_buffer_materials = true; //normally there are none
1786 }
1787
1788 global_shader_uniforms.variables[p_name] = gv;
1789}
1790
1791void MaterialStorage::global_shader_parameter_remove(const StringName &p_name) {
1792 if (!global_shader_uniforms.variables.has(p_name)) {
1793 return;
1794 }
1795 GlobalShaderUniforms::Variable &gv = global_shader_uniforms.variables[p_name];
1796
1797 if (gv.buffer_index >= 0) {
1798 global_shader_uniforms.buffer_usage[gv.buffer_index].elements = 0;
1799 global_shader_uniforms.must_update_buffer_materials = true;
1800 } else {
1801 global_shader_uniforms.must_update_texture_materials = true;
1802 }
1803
1804 global_shader_uniforms.variables.erase(p_name);
1805}
1806
1807Vector<StringName> MaterialStorage::global_shader_parameter_get_list() const {
1808 if (!Engine::get_singleton()->is_editor_hint()) {
1809 ERR_FAIL_V_MSG(Vector<StringName>(), "This function should never be used outside the editor, it can severely damage performance.");
1810 }
1811
1812 Vector<StringName> names;
1813 for (const KeyValue<StringName, GlobalShaderUniforms::Variable> &E : global_shader_uniforms.variables) {
1814 names.push_back(E.key);
1815 }
1816 names.sort_custom<StringName::AlphCompare>();
1817 return names;
1818}
1819
1820void MaterialStorage::global_shader_parameter_set(const StringName &p_name, const Variant &p_value) {
1821 ERR_FAIL_COND(!global_shader_uniforms.variables.has(p_name));
1822 GlobalShaderUniforms::Variable &gv = global_shader_uniforms.variables[p_name];
1823 gv.value = p_value;
1824 if (gv.override.get_type() == Variant::NIL) {
1825 if (gv.buffer_index >= 0) {
1826 //buffer
1827 _global_shader_uniform_store_in_buffer(gv.buffer_index, gv.type, gv.value);
1828 _global_shader_uniform_mark_buffer_dirty(gv.buffer_index, gv.buffer_elements);
1829 } else {
1830 //texture
1831 MaterialStorage *material_storage = MaterialStorage::get_singleton();
1832 for (const RID &E : gv.texture_materials) {
1833 Material *material = material_storage->get_material(E);
1834 ERR_CONTINUE(!material);
1835 material_storage->_material_queue_update(material, false, true);
1836 }
1837 }
1838 }
1839}
1840
1841void MaterialStorage::global_shader_parameter_set_override(const StringName &p_name, const Variant &p_value) {
1842 if (!global_shader_uniforms.variables.has(p_name)) {
1843 return; //variable may not exist
1844 }
1845
1846 ERR_FAIL_COND(p_value.get_type() == Variant::OBJECT);
1847
1848 GlobalShaderUniforms::Variable &gv = global_shader_uniforms.variables[p_name];
1849
1850 gv.override = p_value;
1851
1852 if (gv.buffer_index >= 0) {
1853 //buffer
1854 if (gv.override.get_type() == Variant::NIL) {
1855 _global_shader_uniform_store_in_buffer(gv.buffer_index, gv.type, gv.value);
1856 } else {
1857 _global_shader_uniform_store_in_buffer(gv.buffer_index, gv.type, gv.override);
1858 }
1859
1860 _global_shader_uniform_mark_buffer_dirty(gv.buffer_index, gv.buffer_elements);
1861 } else {
1862 //texture
1863 MaterialStorage *material_storage = MaterialStorage::get_singleton();
1864 for (const RID &E : gv.texture_materials) {
1865 Material *material = material_storage->get_material(E);
1866 ERR_CONTINUE(!material);
1867 material_storage->_material_queue_update(material, false, true);
1868 }
1869 }
1870}
1871
1872Variant MaterialStorage::global_shader_parameter_get(const StringName &p_name) const {
1873 if (!Engine::get_singleton()->is_editor_hint()) {
1874 ERR_FAIL_V_MSG(Variant(), "This function should never be used outside the editor, it can severely damage performance.");
1875 }
1876
1877 if (!global_shader_uniforms.variables.has(p_name)) {
1878 return Variant();
1879 }
1880
1881 return global_shader_uniforms.variables[p_name].value;
1882}
1883
1884RS::GlobalShaderParameterType MaterialStorage::global_shader_parameter_get_type_internal(const StringName &p_name) const {
1885 if (!global_shader_uniforms.variables.has(p_name)) {
1886 return RS::GLOBAL_VAR_TYPE_MAX;
1887 }
1888
1889 return global_shader_uniforms.variables[p_name].type;
1890}
1891
1892RS::GlobalShaderParameterType MaterialStorage::global_shader_parameter_get_type(const StringName &p_name) const {
1893 if (!Engine::get_singleton()->is_editor_hint()) {
1894 ERR_FAIL_V_MSG(RS::GLOBAL_VAR_TYPE_MAX, "This function should never be used outside the editor, it can severely damage performance.");
1895 }
1896
1897 return global_shader_parameter_get_type_internal(p_name);
1898}
1899
1900void MaterialStorage::global_shader_parameters_load_settings(bool p_load_textures) {
1901 List<PropertyInfo> settings;
1902 ProjectSettings::get_singleton()->get_property_list(&settings);
1903
1904 for (const PropertyInfo &E : settings) {
1905 if (E.name.begins_with("shader_globals/")) {
1906 StringName name = E.name.get_slice("/", 1);
1907 Dictionary d = GLOBAL_GET(E.name);
1908
1909 ERR_CONTINUE(!d.has("type"));
1910 ERR_CONTINUE(!d.has("value"));
1911
1912 String type = d["type"];
1913
1914 static const char *global_var_type_names[RS::GLOBAL_VAR_TYPE_MAX] = {
1915 "bool",
1916 "bvec2",
1917 "bvec3",
1918 "bvec4",
1919 "int",
1920 "ivec2",
1921 "ivec3",
1922 "ivec4",
1923 "rect2i",
1924 "uint",
1925 "uvec2",
1926 "uvec3",
1927 "uvec4",
1928 "float",
1929 "vec2",
1930 "vec3",
1931 "vec4",
1932 "color",
1933 "rect2",
1934 "mat2",
1935 "mat3",
1936 "mat4",
1937 "transform_2d",
1938 "transform",
1939 "sampler2D",
1940 "sampler2DArray",
1941 "sampler3D",
1942 "samplerCube",
1943 };
1944
1945 RS::GlobalShaderParameterType gvtype = RS::GLOBAL_VAR_TYPE_MAX;
1946
1947 for (int i = 0; i < RS::GLOBAL_VAR_TYPE_MAX; i++) {
1948 if (global_var_type_names[i] == type) {
1949 gvtype = RS::GlobalShaderParameterType(i);
1950 break;
1951 }
1952 }
1953
1954 ERR_CONTINUE(gvtype == RS::GLOBAL_VAR_TYPE_MAX); //type invalid
1955
1956 Variant value = d["value"];
1957
1958 if (gvtype >= RS::GLOBAL_VAR_TYPE_SAMPLER2D) {
1959 //textire
1960 if (!p_load_textures) {
1961 continue;
1962 }
1963
1964 String path = value;
1965 if (path.is_empty()) {
1966 value = RID();
1967 } else {
1968 Ref<Resource> resource = ResourceLoader::load(path);
1969 value = resource;
1970 }
1971 }
1972
1973 if (global_shader_uniforms.variables.has(name)) {
1974 //has it, update it
1975 global_shader_parameter_set(name, value);
1976 } else {
1977 global_shader_parameter_add(name, gvtype, value);
1978 }
1979 }
1980 }
1981}
1982
1983void MaterialStorage::global_shader_parameters_clear() {
1984 global_shader_uniforms.variables.clear();
1985}
1986
1987GLuint MaterialStorage::global_shader_parameters_get_uniform_buffer() const {
1988 return global_shader_uniforms.buffer;
1989}
1990
1991int32_t MaterialStorage::global_shader_parameters_instance_allocate(RID p_instance) {
1992 ERR_FAIL_COND_V(global_shader_uniforms.instance_buffer_pos.has(p_instance), -1);
1993 int32_t pos = _global_shader_uniform_allocate(ShaderLanguage::MAX_INSTANCE_UNIFORM_INDICES);
1994 global_shader_uniforms.instance_buffer_pos[p_instance] = pos; //save anyway
1995 ERR_FAIL_COND_V_MSG(pos < 0, -1, "Too many instances using shader instance variables. Increase buffer size in Project Settings.");
1996 global_shader_uniforms.buffer_usage[pos].elements = ShaderLanguage::MAX_INSTANCE_UNIFORM_INDICES;
1997 return pos;
1998}
1999
2000void MaterialStorage::global_shader_parameters_instance_free(RID p_instance) {
2001 ERR_FAIL_COND(!global_shader_uniforms.instance_buffer_pos.has(p_instance));
2002 int32_t pos = global_shader_uniforms.instance_buffer_pos[p_instance];
2003 if (pos >= 0) {
2004 global_shader_uniforms.buffer_usage[pos].elements = 0;
2005 }
2006 global_shader_uniforms.instance_buffer_pos.erase(p_instance);
2007}
2008
2009void MaterialStorage::global_shader_parameters_instance_update(RID p_instance, int p_index, const Variant &p_value, int p_flags_count) {
2010 if (!global_shader_uniforms.instance_buffer_pos.has(p_instance)) {
2011 return; //just not allocated, ignore
2012 }
2013 int32_t pos = global_shader_uniforms.instance_buffer_pos[p_instance];
2014
2015 if (pos < 0) {
2016 return; //again, not allocated, ignore
2017 }
2018 ERR_FAIL_INDEX(p_index, ShaderLanguage::MAX_INSTANCE_UNIFORM_INDICES);
2019
2020 Variant::Type value_type = p_value.get_type();
2021 ERR_FAIL_COND_MSG(p_value.get_type() > Variant::COLOR, "Unsupported variant type for instance parameter: " + Variant::get_type_name(value_type)); //anything greater not supported
2022
2023 ShaderLanguage::DataType datatype_from_value[Variant::COLOR + 1] = {
2024 ShaderLanguage::TYPE_MAX, //nil
2025 ShaderLanguage::TYPE_BOOL, //bool
2026 ShaderLanguage::TYPE_INT, //int
2027 ShaderLanguage::TYPE_FLOAT, //float
2028 ShaderLanguage::TYPE_MAX, //string
2029 ShaderLanguage::TYPE_VEC2, //vec2
2030 ShaderLanguage::TYPE_IVEC2, //vec2i
2031 ShaderLanguage::TYPE_VEC4, //rect2
2032 ShaderLanguage::TYPE_IVEC4, //rect2i
2033 ShaderLanguage::TYPE_VEC3, // vec3
2034 ShaderLanguage::TYPE_IVEC3, //vec3i
2035 ShaderLanguage::TYPE_MAX, //xform2d not supported here
2036 ShaderLanguage::TYPE_VEC4, //vec4
2037 ShaderLanguage::TYPE_IVEC4, //vec4i
2038 ShaderLanguage::TYPE_VEC4, //plane
2039 ShaderLanguage::TYPE_VEC4, //quat
2040 ShaderLanguage::TYPE_MAX, //aabb not supported here
2041 ShaderLanguage::TYPE_MAX, //basis not supported here
2042 ShaderLanguage::TYPE_MAX, //xform not supported here
2043 ShaderLanguage::TYPE_MAX, //projection not supported here
2044 ShaderLanguage::TYPE_VEC4 //color
2045 };
2046
2047 ShaderLanguage::DataType datatype = ShaderLanguage::TYPE_MAX;
2048 if (value_type == Variant::INT && p_flags_count > 0) {
2049 switch (p_flags_count) {
2050 case 1:
2051 datatype = ShaderLanguage::TYPE_BVEC2;
2052 break;
2053 case 2:
2054 datatype = ShaderLanguage::TYPE_BVEC3;
2055 break;
2056 case 3:
2057 datatype = ShaderLanguage::TYPE_BVEC4;
2058 break;
2059 }
2060 } else {
2061 datatype = datatype_from_value[value_type];
2062 }
2063
2064 ERR_FAIL_COND_MSG(datatype == ShaderLanguage::TYPE_MAX, "Unsupported variant type for instance parameter: " + Variant::get_type_name(value_type)); //anything greater not supported
2065
2066 pos += p_index;
2067
2068 _fill_std140_variant_ubo_value(datatype, 0, p_value, (uint8_t *)&global_shader_uniforms.buffer_values[pos]);
2069 _global_shader_uniform_mark_buffer_dirty(pos, 1);
2070}
2071
2072void MaterialStorage::_update_global_shader_uniforms() {
2073 MaterialStorage *material_storage = MaterialStorage::get_singleton();
2074 if (global_shader_uniforms.buffer_dirty_region_count > 0) {
2075 uint32_t total_regions = global_shader_uniforms.buffer_size / GlobalShaderUniforms::BUFFER_DIRTY_REGION_SIZE;
2076 if (total_regions / global_shader_uniforms.buffer_dirty_region_count <= 4) {
2077 // 25% of regions dirty, just update all buffer
2078 glBindBuffer(GL_UNIFORM_BUFFER, global_shader_uniforms.buffer);
2079 glBufferData(GL_UNIFORM_BUFFER, sizeof(GlobalShaderUniforms::Value) * global_shader_uniforms.buffer_size, global_shader_uniforms.buffer_values, GL_DYNAMIC_DRAW);
2080 glBindBuffer(GL_UNIFORM_BUFFER, 0);
2081 memset(global_shader_uniforms.buffer_dirty_regions, 0, sizeof(bool) * total_regions);
2082 } else {
2083 uint32_t region_byte_size = sizeof(GlobalShaderUniforms::Value) * GlobalShaderUniforms::BUFFER_DIRTY_REGION_SIZE;
2084 glBindBuffer(GL_UNIFORM_BUFFER, global_shader_uniforms.buffer);
2085 for (uint32_t i = 0; i < total_regions; i++) {
2086 if (global_shader_uniforms.buffer_dirty_regions[i]) {
2087 glBufferSubData(GL_UNIFORM_BUFFER, i * region_byte_size, region_byte_size, &global_shader_uniforms.buffer_values[i * GlobalShaderUniforms::BUFFER_DIRTY_REGION_SIZE]);
2088 global_shader_uniforms.buffer_dirty_regions[i] = false;
2089 }
2090 }
2091 glBindBuffer(GL_UNIFORM_BUFFER, 0);
2092 }
2093
2094 global_shader_uniforms.buffer_dirty_region_count = 0;
2095 }
2096
2097 if (global_shader_uniforms.must_update_buffer_materials) {
2098 // only happens in the case of a buffer variable added or removed,
2099 // so not often.
2100 for (const RID &E : global_shader_uniforms.materials_using_buffer) {
2101 Material *material = material_storage->get_material(E);
2102 ERR_CONTINUE(!material); //wtf
2103
2104 material_storage->_material_queue_update(material, true, false);
2105 }
2106
2107 global_shader_uniforms.must_update_buffer_materials = false;
2108 }
2109
2110 if (global_shader_uniforms.must_update_texture_materials) {
2111 // only happens in the case of a buffer variable added or removed,
2112 // so not often.
2113 for (const RID &E : global_shader_uniforms.materials_using_texture) {
2114 Material *material = material_storage->get_material(E);
2115 ERR_CONTINUE(!material); //wtf
2116
2117 material_storage->_material_queue_update(material, false, true);
2118 }
2119
2120 global_shader_uniforms.must_update_texture_materials = false;
2121 }
2122}
2123
2124/* SHADER API */
2125
2126RID MaterialStorage::shader_allocate() {
2127 return shader_owner.allocate_rid();
2128}
2129
2130void MaterialStorage::shader_initialize(RID p_rid) {
2131 Shader shader;
2132 shader.data = nullptr;
2133 shader.mode = RS::SHADER_MAX;
2134
2135 shader_owner.initialize_rid(p_rid, shader);
2136}
2137
2138void MaterialStorage::shader_free(RID p_rid) {
2139 GLES3::Shader *shader = shader_owner.get_or_null(p_rid);
2140 ERR_FAIL_NULL(shader);
2141
2142 //make material unreference this
2143 while (shader->owners.size()) {
2144 material_set_shader((*shader->owners.begin())->self, RID());
2145 }
2146
2147 //clear data if exists
2148 if (shader->data) {
2149 memdelete(shader->data);
2150 }
2151 shader_owner.free(p_rid);
2152}
2153
2154void MaterialStorage::shader_set_code(RID p_shader, const String &p_code) {
2155 GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
2156 ERR_FAIL_NULL(shader);
2157
2158 shader->code = p_code;
2159
2160 String mode_string = ShaderLanguage::get_shader_type(p_code);
2161
2162 RS::ShaderMode new_mode;
2163 if (mode_string == "canvas_item") {
2164 new_mode = RS::SHADER_CANVAS_ITEM;
2165 } else if (mode_string == "particles") {
2166 new_mode = RS::SHADER_PARTICLES;
2167 } else if (mode_string == "spatial") {
2168 new_mode = RS::SHADER_SPATIAL;
2169 } else if (mode_string == "sky") {
2170 new_mode = RS::SHADER_SKY;
2171 //} else if (mode_string == "fog") {
2172 // new_mode = RS::SHADER_FOG;
2173 } else {
2174 new_mode = RS::SHADER_MAX;
2175 ERR_PRINT("shader type " + mode_string + " not supported in OpenGL renderer");
2176 }
2177
2178 if (new_mode != shader->mode) {
2179 if (shader->data) {
2180 memdelete(shader->data);
2181 shader->data = nullptr;
2182 }
2183
2184 for (Material *E : shader->owners) {
2185 Material *material = E;
2186 material->shader_mode = new_mode;
2187 if (material->data) {
2188 memdelete(material->data);
2189 material->data = nullptr;
2190 }
2191 }
2192
2193 shader->mode = new_mode;
2194
2195 if (new_mode < RS::SHADER_MAX && shader_data_request_func[new_mode]) {
2196 shader->data = shader_data_request_func[new_mode]();
2197 } else {
2198 shader->mode = RS::SHADER_MAX; //invalid
2199 }
2200
2201 for (Material *E : shader->owners) {
2202 Material *material = E;
2203 if (shader->data) {
2204 material->data = material_data_request_func[new_mode](shader->data);
2205 material->data->self = material->self;
2206 material->data->set_next_pass(material->next_pass);
2207 material->data->set_render_priority(material->priority);
2208 }
2209 material->shader_mode = new_mode;
2210 }
2211
2212 if (shader->data) {
2213 for (const KeyValue<StringName, HashMap<int, RID>> &E : shader->default_texture_parameter) {
2214 for (const KeyValue<int, RID> &E2 : E.value) {
2215 shader->data->set_default_texture_parameter(E.key, E2.value, E2.key);
2216 }
2217 }
2218 }
2219 }
2220
2221 if (shader->data) {
2222 shader->data->set_code(p_code);
2223 }
2224
2225 for (Material *E : shader->owners) {
2226 Material *material = E;
2227 material->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_MATERIAL);
2228 _material_queue_update(material, true, true);
2229 }
2230}
2231
2232void MaterialStorage::shader_set_path_hint(RID p_shader, const String &p_path) {
2233 GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
2234 ERR_FAIL_NULL(shader);
2235
2236 shader->path_hint = p_path;
2237 if (shader->data) {
2238 shader->data->set_path_hint(p_path);
2239 }
2240}
2241
2242String MaterialStorage::shader_get_code(RID p_shader) const {
2243 const GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
2244 ERR_FAIL_NULL_V(shader, String());
2245 return shader->code;
2246}
2247
2248void MaterialStorage::get_shader_parameter_list(RID p_shader, List<PropertyInfo> *p_param_list) const {
2249 GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
2250 ERR_FAIL_NULL(shader);
2251 if (shader->data) {
2252 return shader->data->get_shader_uniform_list(p_param_list);
2253 }
2254}
2255
2256void MaterialStorage::shader_set_default_texture_parameter(RID p_shader, const StringName &p_name, RID p_texture, int p_index) {
2257 GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
2258 ERR_FAIL_NULL(shader);
2259
2260 if (p_texture.is_valid() && TextureStorage::get_singleton()->owns_texture(p_texture)) {
2261 if (!shader->default_texture_parameter.has(p_name)) {
2262 shader->default_texture_parameter[p_name] = HashMap<int, RID>();
2263 }
2264 shader->default_texture_parameter[p_name][p_index] = p_texture;
2265 } else {
2266 if (shader->default_texture_parameter.has(p_name) && shader->default_texture_parameter[p_name].has(p_index)) {
2267 shader->default_texture_parameter[p_name].erase(p_index);
2268
2269 if (shader->default_texture_parameter[p_name].is_empty()) {
2270 shader->default_texture_parameter.erase(p_name);
2271 }
2272 }
2273 }
2274 if (shader->data) {
2275 shader->data->set_default_texture_parameter(p_name, p_texture, p_index);
2276 }
2277 for (Material *E : shader->owners) {
2278 Material *material = E;
2279 _material_queue_update(material, false, true);
2280 }
2281}
2282
2283RID MaterialStorage::shader_get_default_texture_parameter(RID p_shader, const StringName &p_name, int p_index) const {
2284 const GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
2285 ERR_FAIL_NULL_V(shader, RID());
2286 if (shader->default_texture_parameter.has(p_name) && shader->default_texture_parameter[p_name].has(p_index)) {
2287 return shader->default_texture_parameter[p_name][p_index];
2288 }
2289
2290 return RID();
2291}
2292
2293Variant MaterialStorage::shader_get_parameter_default(RID p_shader, const StringName &p_param) const {
2294 Shader *shader = shader_owner.get_or_null(p_shader);
2295 ERR_FAIL_NULL_V(shader, Variant());
2296 if (shader->data) {
2297 return shader->data->get_default_parameter(p_param);
2298 }
2299 return Variant();
2300}
2301
2302RS::ShaderNativeSourceCode MaterialStorage::shader_get_native_source_code(RID p_shader) const {
2303 Shader *shader = shader_owner.get_or_null(p_shader);
2304 ERR_FAIL_NULL_V(shader, RS::ShaderNativeSourceCode());
2305 if (shader->data) {
2306 return shader->data->get_native_source_code();
2307 }
2308 return RS::ShaderNativeSourceCode();
2309}
2310
2311/* MATERIAL API */
2312
2313void MaterialStorage::_material_queue_update(GLES3::Material *material, bool p_uniform, bool p_texture) {
2314 material->uniform_dirty = material->uniform_dirty || p_uniform;
2315 material->texture_dirty = material->texture_dirty || p_texture;
2316
2317 if (material->update_element.in_list()) {
2318 return;
2319 }
2320
2321 material_update_list.add(&material->update_element);
2322}
2323
2324void MaterialStorage::_update_queued_materials() {
2325 while (material_update_list.first()) {
2326 Material *material = material_update_list.first()->self();
2327
2328 if (material->data) {
2329 material->data->update_parameters(material->params, material->uniform_dirty, material->texture_dirty);
2330 }
2331 material->texture_dirty = false;
2332 material->uniform_dirty = false;
2333
2334 material_update_list.remove(&material->update_element);
2335 }
2336}
2337
2338RID MaterialStorage::material_allocate() {
2339 return material_owner.allocate_rid();
2340}
2341
2342void MaterialStorage::material_initialize(RID p_rid) {
2343 material_owner.initialize_rid(p_rid);
2344 Material *material = material_owner.get_or_null(p_rid);
2345 material->self = p_rid;
2346}
2347
2348void MaterialStorage::material_free(RID p_rid) {
2349 Material *material = material_owner.get_or_null(p_rid);
2350 ERR_FAIL_NULL(material);
2351
2352 // Need to clear texture arrays to prevent spin locking of their RID's.
2353 // This happens when the app is being closed.
2354 for (KeyValue<StringName, Variant> &E : material->params) {
2355 if (E.value.get_type() == Variant::ARRAY) {
2356 Array(E.value).clear();
2357 }
2358 }
2359
2360 material_set_shader(p_rid, RID()); //clean up shader
2361 material->dependency.deleted_notify(p_rid);
2362
2363 material_owner.free(p_rid);
2364}
2365
2366void MaterialStorage::material_set_shader(RID p_material, RID p_shader) {
2367 GLES3::Material *material = material_owner.get_or_null(p_material);
2368 ERR_FAIL_NULL(material);
2369
2370 if (material->data) {
2371 memdelete(material->data);
2372 material->data = nullptr;
2373 }
2374
2375 if (material->shader) {
2376 material->shader->owners.erase(material);
2377 material->shader = nullptr;
2378 material->shader_mode = RS::SHADER_MAX;
2379 }
2380
2381 if (p_shader.is_null()) {
2382 material->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_MATERIAL);
2383 material->shader_id = 0;
2384 return;
2385 }
2386
2387 Shader *shader = get_shader(p_shader);
2388 ERR_FAIL_NULL(shader);
2389 material->shader = shader;
2390 material->shader_mode = shader->mode;
2391 material->shader_id = p_shader.get_local_index();
2392 shader->owners.insert(material);
2393
2394 if (shader->mode == RS::SHADER_MAX) {
2395 return;
2396 }
2397
2398 ERR_FAIL_COND(shader->data == nullptr);
2399
2400 material->data = material_data_request_func[shader->mode](shader->data);
2401 material->data->self = p_material;
2402 material->data->set_next_pass(material->next_pass);
2403 material->data->set_render_priority(material->priority);
2404 //updating happens later
2405 material->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_MATERIAL);
2406 _material_queue_update(material, true, true);
2407}
2408
2409void MaterialStorage::material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) {
2410 GLES3::Material *material = material_owner.get_or_null(p_material);
2411 ERR_FAIL_NULL(material);
2412
2413 if (p_value.get_type() == Variant::NIL) {
2414 material->params.erase(p_param);
2415 } else {
2416 ERR_FAIL_COND(p_value.get_type() == Variant::OBJECT); //object not allowed
2417 material->params[p_param] = p_value;
2418 }
2419
2420 if (material->shader && material->shader->data) { //shader is valid
2421 bool is_texture = material->shader->data->is_parameter_texture(p_param);
2422 _material_queue_update(material, !is_texture, is_texture);
2423 } else {
2424 _material_queue_update(material, true, true);
2425 }
2426}
2427
2428Variant MaterialStorage::material_get_param(RID p_material, const StringName &p_param) const {
2429 const GLES3::Material *material = material_owner.get_or_null(p_material);
2430 ERR_FAIL_NULL_V(material, Variant());
2431 if (material->params.has(p_param)) {
2432 return material->params[p_param];
2433 } else {
2434 return Variant();
2435 }
2436}
2437
2438void MaterialStorage::material_set_next_pass(RID p_material, RID p_next_material) {
2439 GLES3::Material *material = material_owner.get_or_null(p_material);
2440 ERR_FAIL_NULL(material);
2441
2442 if (material->next_pass == p_next_material) {
2443 return;
2444 }
2445
2446 material->next_pass = p_next_material;
2447 if (material->data) {
2448 material->data->set_next_pass(p_next_material);
2449 }
2450
2451 material->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_MATERIAL);
2452}
2453
2454void MaterialStorage::material_set_render_priority(RID p_material, int priority) {
2455 ERR_FAIL_COND(priority < RS::MATERIAL_RENDER_PRIORITY_MIN);
2456 ERR_FAIL_COND(priority > RS::MATERIAL_RENDER_PRIORITY_MAX);
2457
2458 GLES3::Material *material = material_owner.get_or_null(p_material);
2459 ERR_FAIL_NULL(material);
2460 material->priority = priority;
2461 if (material->data) {
2462 material->data->set_render_priority(priority);
2463 }
2464 material->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_MATERIAL);
2465}
2466
2467bool MaterialStorage::material_is_animated(RID p_material) {
2468 GLES3::Material *material = material_owner.get_or_null(p_material);
2469 ERR_FAIL_NULL_V(material, false);
2470 if (material->shader && material->shader->data) {
2471 if (material->shader->data->is_animated()) {
2472 return true;
2473 } else if (material->next_pass.is_valid()) {
2474 return material_is_animated(material->next_pass);
2475 }
2476 }
2477 return false; //by default nothing is animated
2478}
2479
2480bool MaterialStorage::material_casts_shadows(RID p_material) {
2481 GLES3::Material *material = material_owner.get_or_null(p_material);
2482 ERR_FAIL_NULL_V(material, true);
2483 if (material->shader && material->shader->data) {
2484 if (material->shader->data->casts_shadows()) {
2485 return true;
2486 } else if (material->next_pass.is_valid()) {
2487 return material_casts_shadows(material->next_pass);
2488 }
2489 }
2490 return true; //by default everything casts shadows
2491}
2492
2493void MaterialStorage::material_get_instance_shader_parameters(RID p_material, List<InstanceShaderParam> *r_parameters) {
2494 GLES3::Material *material = material_owner.get_or_null(p_material);
2495 ERR_FAIL_NULL(material);
2496 if (material->shader && material->shader->data) {
2497 material->shader->data->get_instance_param_list(r_parameters);
2498
2499 if (material->next_pass.is_valid()) {
2500 material_get_instance_shader_parameters(material->next_pass, r_parameters);
2501 }
2502 }
2503}
2504
2505void MaterialStorage::material_update_dependency(RID p_material, DependencyTracker *p_instance) {
2506 Material *material = material_owner.get_or_null(p_material);
2507 ERR_FAIL_NULL(material);
2508 p_instance->update_dependency(&material->dependency);
2509 if (material->next_pass.is_valid()) {
2510 material_update_dependency(material->next_pass, p_instance);
2511 }
2512}
2513
2514LocalVector<ShaderGLES3::TextureUniformData> get_texture_uniform_data(const Vector<ShaderCompiler::GeneratedCode::Texture> &texture_uniforms) {
2515 LocalVector<ShaderGLES3::TextureUniformData> texture_uniform_data;
2516 for (int i = 0; i < texture_uniforms.size(); i++) {
2517 int num_textures = texture_uniforms[i].array_size;
2518 if (num_textures == 0) {
2519 num_textures = 1;
2520 }
2521 texture_uniform_data.push_back({ texture_uniforms[i].name, num_textures });
2522 }
2523 return texture_uniform_data;
2524}
2525
2526/* Canvas Shader Data */
2527
2528void CanvasShaderData::set_code(const String &p_code) {
2529 // compile the shader
2530
2531 code = p_code;
2532 valid = false;
2533 ubo_size = 0;
2534 uniforms.clear();
2535 uses_screen_texture = false;
2536 uses_screen_texture_mipmaps = false;
2537 uses_sdf = false;
2538 uses_time = false;
2539
2540 if (code.is_empty()) {
2541 return; //just invalid, but no error
2542 }
2543
2544 ShaderCompiler::GeneratedCode gen_code;
2545
2546 int blend_modei = BLEND_MODE_MIX;
2547
2548 ShaderCompiler::IdentifierActions actions;
2549 actions.entry_point_stages["vertex"] = ShaderCompiler::STAGE_VERTEX;
2550 actions.entry_point_stages["fragment"] = ShaderCompiler::STAGE_FRAGMENT;
2551 actions.entry_point_stages["light"] = ShaderCompiler::STAGE_FRAGMENT;
2552
2553 actions.render_mode_values["blend_add"] = Pair<int *, int>(&blend_modei, BLEND_MODE_ADD);
2554 actions.render_mode_values["blend_mix"] = Pair<int *, int>(&blend_modei, BLEND_MODE_MIX);
2555 actions.render_mode_values["blend_sub"] = Pair<int *, int>(&blend_modei, BLEND_MODE_SUB);
2556 actions.render_mode_values["blend_mul"] = Pair<int *, int>(&blend_modei, BLEND_MODE_MUL);
2557 actions.render_mode_values["blend_premul_alpha"] = Pair<int *, int>(&blend_modei, BLEND_MODE_PMALPHA);
2558 actions.render_mode_values["blend_disabled"] = Pair<int *, int>(&blend_modei, BLEND_MODE_DISABLED);
2559
2560 actions.usage_flag_pointers["texture_sdf"] = &uses_sdf;
2561 actions.usage_flag_pointers["TIME"] = &uses_time;
2562
2563 actions.uniforms = &uniforms;
2564 Error err = MaterialStorage::get_singleton()->shaders.compiler_canvas.compile(RS::SHADER_CANVAS_ITEM, code, &actions, path, gen_code);
2565 ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed.");
2566
2567 if (version.is_null()) {
2568 version = MaterialStorage::get_singleton()->shaders.canvas_shader.version_create();
2569 }
2570
2571 blend_mode = BlendMode(blend_modei);
2572 uses_screen_texture_mipmaps = gen_code.uses_screen_texture_mipmaps;
2573 uses_screen_texture = gen_code.uses_screen_texture;
2574
2575#if 0
2576 print_line("**compiling shader:");
2577 print_line("**defines:\n");
2578 for (int i = 0; i < gen_code.defines.size(); i++) {
2579 print_line(gen_code.defines[i]);
2580 }
2581
2582 HashMap<String, String>::Iterator el = gen_code.code.begin();
2583 while (el) {
2584 print_line("\n**code " + el->key + ":\n" + el->value);
2585 ++el;
2586 }
2587
2588 print_line("\n**uniforms:\n" + gen_code.uniforms);
2589 print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);
2590 print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);
2591#endif
2592
2593 LocalVector<ShaderGLES3::TextureUniformData> texture_uniform_data = get_texture_uniform_data(gen_code.texture_uniforms);
2594
2595 MaterialStorage::get_singleton()->shaders.canvas_shader.version_set_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines, texture_uniform_data);
2596 ERR_FAIL_COND(!MaterialStorage::get_singleton()->shaders.canvas_shader.version_is_valid(version));
2597
2598 ubo_size = gen_code.uniform_total_size;
2599 ubo_offsets = gen_code.uniform_offsets;
2600 texture_uniforms = gen_code.texture_uniforms;
2601
2602 valid = true;
2603}
2604
2605bool CanvasShaderData::is_animated() const {
2606 return false;
2607}
2608
2609bool CanvasShaderData::casts_shadows() const {
2610 return false;
2611}
2612
2613RS::ShaderNativeSourceCode CanvasShaderData::get_native_source_code() const {
2614 return MaterialStorage::get_singleton()->shaders.canvas_shader.version_get_native_source_code(version);
2615}
2616
2617CanvasShaderData::CanvasShaderData() {
2618 valid = false;
2619 uses_screen_texture = false;
2620 uses_sdf = false;
2621}
2622
2623CanvasShaderData::~CanvasShaderData() {
2624 if (version.is_valid()) {
2625 MaterialStorage::get_singleton()->shaders.canvas_shader.version_free(version);
2626 }
2627}
2628
2629GLES3::ShaderData *GLES3::_create_canvas_shader_func() {
2630 CanvasShaderData *shader_data = memnew(CanvasShaderData);
2631 return shader_data;
2632}
2633
2634void CanvasMaterialData::update_parameters(const HashMap<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
2635 update_parameters_internal(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, false);
2636}
2637
2638static void bind_uniforms_generic(const Vector<RID> &p_textures, const Vector<ShaderCompiler::GeneratedCode::Texture> &p_texture_uniforms, int texture_offset = 0, const RS::CanvasItemTextureFilter *filter_mapping = filter_from_uniform, const RS::CanvasItemTextureRepeat *repeat_mapping = repeat_from_uniform) {
2639 const RID *textures = p_textures.ptr();
2640 const ShaderCompiler::GeneratedCode::Texture *texture_uniforms = p_texture_uniforms.ptr();
2641 int texture_uniform_index = 0;
2642 int texture_uniform_count = 0;
2643 for (int ti = 0; ti < p_textures.size(); ti++) {
2644 ERR_FAIL_COND_MSG(texture_uniform_index >= p_texture_uniforms.size(), "texture_uniform_index out of bounds");
2645 GLES3::Texture *texture = TextureStorage::get_singleton()->get_texture(textures[ti]);
2646 const ShaderCompiler::GeneratedCode::Texture &texture_uniform = texture_uniforms[texture_uniform_index];
2647 if (texture) {
2648 glActiveTexture(GL_TEXTURE0 + texture_offset + ti);
2649 glBindTexture(target_from_type[texture_uniform.type], texture->tex_id);
2650 if (texture->render_target) {
2651 texture->render_target->used_in_frame = true;
2652 }
2653
2654 texture->gl_set_filter(filter_mapping[int(texture_uniform.filter)]);
2655 texture->gl_set_repeat(repeat_mapping[int(texture_uniform.repeat)]);
2656 }
2657 texture_uniform_count++;
2658 if (texture_uniform_count >= texture_uniform.array_size) {
2659 texture_uniform_index++;
2660 texture_uniform_count = 0;
2661 }
2662 }
2663}
2664
2665void CanvasMaterialData::bind_uniforms() {
2666 // Bind Material Uniforms
2667 glBindBufferBase(GL_UNIFORM_BUFFER, RasterizerCanvasGLES3::MATERIAL_UNIFORM_LOCATION, uniform_buffer);
2668
2669 bind_uniforms_generic(texture_cache, shader_data->texture_uniforms, 1, filter_from_uniform_canvas, repeat_from_uniform_canvas); // Start at GL_TEXTURE1 because texture slot 0 is used by the base texture
2670}
2671
2672CanvasMaterialData::~CanvasMaterialData() {
2673}
2674
2675GLES3::MaterialData *GLES3::_create_canvas_material_func(ShaderData *p_shader) {
2676 CanvasMaterialData *material_data = memnew(CanvasMaterialData);
2677 material_data->shader_data = static_cast<CanvasShaderData *>(p_shader);
2678 //update will happen later anyway so do nothing.
2679 return material_data;
2680}
2681
2682////////////////////////////////////////////////////////////////////////////////
2683// SKY SHADER
2684
2685void SkyShaderData::set_code(const String &p_code) {
2686 //compile
2687
2688 code = p_code;
2689 valid = false;
2690 ubo_size = 0;
2691 uniforms.clear();
2692
2693 if (code.is_empty()) {
2694 return; //just invalid, but no error
2695 }
2696
2697 ShaderCompiler::GeneratedCode gen_code;
2698 ShaderCompiler::IdentifierActions actions;
2699 actions.entry_point_stages["sky"] = ShaderCompiler::STAGE_FRAGMENT;
2700
2701 uses_time = false;
2702 uses_half_res = false;
2703 uses_quarter_res = false;
2704 uses_position = false;
2705 uses_light = false;
2706
2707 actions.render_mode_flags["use_half_res_pass"] = &uses_half_res;
2708 actions.render_mode_flags["use_quarter_res_pass"] = &uses_quarter_res;
2709
2710 actions.usage_flag_pointers["TIME"] = &uses_time;
2711 actions.usage_flag_pointers["POSITION"] = &uses_position;
2712 actions.usage_flag_pointers["LIGHT0_ENABLED"] = &uses_light;
2713 actions.usage_flag_pointers["LIGHT0_ENERGY"] = &uses_light;
2714 actions.usage_flag_pointers["LIGHT0_DIRECTION"] = &uses_light;
2715 actions.usage_flag_pointers["LIGHT0_COLOR"] = &uses_light;
2716 actions.usage_flag_pointers["LIGHT0_SIZE"] = &uses_light;
2717 actions.usage_flag_pointers["LIGHT1_ENABLED"] = &uses_light;
2718 actions.usage_flag_pointers["LIGHT1_ENERGY"] = &uses_light;
2719 actions.usage_flag_pointers["LIGHT1_DIRECTION"] = &uses_light;
2720 actions.usage_flag_pointers["LIGHT1_COLOR"] = &uses_light;
2721 actions.usage_flag_pointers["LIGHT1_SIZE"] = &uses_light;
2722 actions.usage_flag_pointers["LIGHT2_ENABLED"] = &uses_light;
2723 actions.usage_flag_pointers["LIGHT2_ENERGY"] = &uses_light;
2724 actions.usage_flag_pointers["LIGHT2_DIRECTION"] = &uses_light;
2725 actions.usage_flag_pointers["LIGHT2_COLOR"] = &uses_light;
2726 actions.usage_flag_pointers["LIGHT2_SIZE"] = &uses_light;
2727 actions.usage_flag_pointers["LIGHT3_ENABLED"] = &uses_light;
2728 actions.usage_flag_pointers["LIGHT3_ENERGY"] = &uses_light;
2729 actions.usage_flag_pointers["LIGHT3_DIRECTION"] = &uses_light;
2730 actions.usage_flag_pointers["LIGHT3_COLOR"] = &uses_light;
2731 actions.usage_flag_pointers["LIGHT3_SIZE"] = &uses_light;
2732
2733 actions.uniforms = &uniforms;
2734
2735 Error err = MaterialStorage::get_singleton()->shaders.compiler_sky.compile(RS::SHADER_SKY, code, &actions, path, gen_code);
2736 ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed.");
2737
2738 if (version.is_null()) {
2739 version = MaterialStorage::get_singleton()->shaders.sky_shader.version_create();
2740 }
2741
2742#if 0
2743 print_line("**compiling shader:");
2744 print_line("**defines:\n");
2745 for (int i = 0; i < gen_code.defines.size(); i++) {
2746 print_line(gen_code.defines[i]);
2747 }
2748
2749 HashMap<String, String>::Iterator el = gen_code.code.begin();
2750 while (el) {
2751 print_line("\n**code " + el->key + ":\n" + el->value);
2752 ++el;
2753 }
2754
2755 print_line("\n**uniforms:\n" + gen_code.uniforms);
2756 print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);
2757 print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);
2758#endif
2759
2760 LocalVector<ShaderGLES3::TextureUniformData> texture_uniform_data = get_texture_uniform_data(gen_code.texture_uniforms);
2761
2762 MaterialStorage::get_singleton()->shaders.sky_shader.version_set_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines, texture_uniform_data);
2763 ERR_FAIL_COND(!MaterialStorage::get_singleton()->shaders.sky_shader.version_is_valid(version));
2764
2765 ubo_size = gen_code.uniform_total_size;
2766 ubo_offsets = gen_code.uniform_offsets;
2767 texture_uniforms = gen_code.texture_uniforms;
2768
2769 valid = true;
2770}
2771
2772bool SkyShaderData::is_animated() const {
2773 return false;
2774}
2775
2776bool SkyShaderData::casts_shadows() const {
2777 return false;
2778}
2779
2780RS::ShaderNativeSourceCode SkyShaderData::get_native_source_code() const {
2781 return MaterialStorage::get_singleton()->shaders.sky_shader.version_get_native_source_code(version);
2782}
2783
2784SkyShaderData::SkyShaderData() {
2785 valid = false;
2786}
2787
2788SkyShaderData::~SkyShaderData() {
2789 if (version.is_valid()) {
2790 MaterialStorage::get_singleton()->shaders.sky_shader.version_free(version);
2791 }
2792}
2793
2794GLES3::ShaderData *GLES3::_create_sky_shader_func() {
2795 SkyShaderData *shader_data = memnew(SkyShaderData);
2796 return shader_data;
2797}
2798
2799////////////////////////////////////////////////////////////////////////////////
2800// Sky material
2801
2802void SkyMaterialData::update_parameters(const HashMap<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
2803 uniform_set_updated = true;
2804 update_parameters_internal(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, true);
2805}
2806
2807SkyMaterialData::~SkyMaterialData() {
2808}
2809GLES3::MaterialData *GLES3::_create_sky_material_func(ShaderData *p_shader) {
2810 SkyMaterialData *material_data = memnew(SkyMaterialData);
2811 material_data->shader_data = static_cast<SkyShaderData *>(p_shader);
2812 //update will happen later anyway so do nothing.
2813 return material_data;
2814}
2815
2816void SkyMaterialData::bind_uniforms() {
2817 // Bind Material Uniforms
2818 glBindBufferBase(GL_UNIFORM_BUFFER, SKY_MATERIAL_UNIFORM_LOCATION, uniform_buffer);
2819
2820 bind_uniforms_generic(texture_cache, shader_data->texture_uniforms);
2821}
2822
2823////////////////////////////////////////////////////////////////////////////////
2824// Scene SHADER
2825
2826void SceneShaderData::set_code(const String &p_code) {
2827 //compile
2828
2829 code = p_code;
2830 valid = false;
2831 ubo_size = 0;
2832 uniforms.clear();
2833
2834 if (code.is_empty()) {
2835 return; //just invalid, but no error
2836 }
2837
2838 ShaderCompiler::GeneratedCode gen_code;
2839
2840 int blend_modei = BLEND_MODE_MIX;
2841 int depth_testi = DEPTH_TEST_ENABLED;
2842 int alpha_antialiasing_modei = ALPHA_ANTIALIASING_OFF;
2843 int cull_modei = CULL_BACK;
2844 int depth_drawi = DEPTH_DRAW_OPAQUE;
2845
2846 uses_point_size = false;
2847 uses_alpha = false;
2848 uses_alpha_clip = false;
2849 uses_blend_alpha = false;
2850 uses_depth_prepass_alpha = false;
2851 uses_discard = false;
2852 uses_roughness = false;
2853 uses_normal = false;
2854 wireframe = false;
2855
2856 unshaded = false;
2857 uses_vertex = false;
2858 uses_position = false;
2859 uses_sss = false;
2860 uses_transmittance = false;
2861 uses_screen_texture = false;
2862 uses_depth_texture = false;
2863 uses_normal_texture = false;
2864 uses_time = false;
2865 writes_modelview_or_projection = false;
2866 uses_world_coordinates = false;
2867 uses_particle_trails = false;
2868
2869 ShaderCompiler::IdentifierActions actions;
2870 actions.entry_point_stages["vertex"] = ShaderCompiler::STAGE_VERTEX;
2871 actions.entry_point_stages["fragment"] = ShaderCompiler::STAGE_FRAGMENT;
2872 actions.entry_point_stages["light"] = ShaderCompiler::STAGE_FRAGMENT;
2873
2874 actions.render_mode_values["blend_add"] = Pair<int *, int>(&blend_modei, BLEND_MODE_ADD);
2875 actions.render_mode_values["blend_mix"] = Pair<int *, int>(&blend_modei, BLEND_MODE_MIX);
2876 actions.render_mode_values["blend_sub"] = Pair<int *, int>(&blend_modei, BLEND_MODE_SUB);
2877 actions.render_mode_values["blend_mul"] = Pair<int *, int>(&blend_modei, BLEND_MODE_MUL);
2878
2879 actions.render_mode_values["alpha_to_coverage"] = Pair<int *, int>(&alpha_antialiasing_modei, ALPHA_ANTIALIASING_ALPHA_TO_COVERAGE);
2880 actions.render_mode_values["alpha_to_coverage_and_one"] = Pair<int *, int>(&alpha_antialiasing_modei, ALPHA_ANTIALIASING_ALPHA_TO_COVERAGE_AND_TO_ONE);
2881
2882 actions.render_mode_values["depth_draw_never"] = Pair<int *, int>(&depth_drawi, DEPTH_DRAW_DISABLED);
2883 actions.render_mode_values["depth_draw_opaque"] = Pair<int *, int>(&depth_drawi, DEPTH_DRAW_OPAQUE);
2884 actions.render_mode_values["depth_draw_always"] = Pair<int *, int>(&depth_drawi, DEPTH_DRAW_ALWAYS);
2885
2886 actions.render_mode_values["depth_test_disabled"] = Pair<int *, int>(&depth_testi, DEPTH_TEST_DISABLED);
2887
2888 actions.render_mode_values["cull_disabled"] = Pair<int *, int>(&cull_modei, CULL_DISABLED);
2889 actions.render_mode_values["cull_front"] = Pair<int *, int>(&cull_modei, CULL_FRONT);
2890 actions.render_mode_values["cull_back"] = Pair<int *, int>(&cull_modei, CULL_BACK);
2891
2892 actions.render_mode_flags["unshaded"] = &unshaded;
2893 actions.render_mode_flags["wireframe"] = &wireframe;
2894 actions.render_mode_flags["particle_trails"] = &uses_particle_trails;
2895
2896 actions.usage_flag_pointers["ALPHA"] = &uses_alpha;
2897 actions.usage_flag_pointers["ALPHA_SCISSOR_THRESHOLD"] = &uses_alpha_clip;
2898 // Use alpha clip pipeline for alpha hash/dither.
2899 // This prevents sorting issues inherent to alpha blending and allows such materials to cast shadows.
2900 actions.usage_flag_pointers["ALPHA_HASH_SCALE"] = &uses_alpha_clip;
2901 actions.render_mode_flags["depth_prepass_alpha"] = &uses_depth_prepass_alpha;
2902
2903 actions.usage_flag_pointers["SSS_STRENGTH"] = &uses_sss;
2904 actions.usage_flag_pointers["SSS_TRANSMITTANCE_DEPTH"] = &uses_transmittance;
2905
2906 actions.usage_flag_pointers["DISCARD"] = &uses_discard;
2907 actions.usage_flag_pointers["TIME"] = &uses_time;
2908 actions.usage_flag_pointers["ROUGHNESS"] = &uses_roughness;
2909 actions.usage_flag_pointers["NORMAL"] = &uses_normal;
2910 actions.usage_flag_pointers["NORMAL_MAP"] = &uses_normal;
2911
2912 actions.usage_flag_pointers["POINT_SIZE"] = &uses_point_size;
2913 actions.usage_flag_pointers["POINT_COORD"] = &uses_point_size;
2914
2915 actions.write_flag_pointers["MODELVIEW_MATRIX"] = &writes_modelview_or_projection;
2916 actions.write_flag_pointers["PROJECTION_MATRIX"] = &writes_modelview_or_projection;
2917 actions.write_flag_pointers["VERTEX"] = &uses_vertex;
2918 actions.write_flag_pointers["POSITION"] = &uses_position;
2919
2920 actions.usage_flag_pointers["TANGENT"] = &uses_tangent;
2921 actions.usage_flag_pointers["BINORMAL"] = &uses_tangent;
2922 actions.usage_flag_pointers["COLOR"] = &uses_color;
2923 actions.usage_flag_pointers["UV"] = &uses_uv;
2924 actions.usage_flag_pointers["UV2"] = &uses_uv2;
2925 actions.usage_flag_pointers["CUSTOM0"] = &uses_custom0;
2926 actions.usage_flag_pointers["CUSTOM1"] = &uses_custom1;
2927 actions.usage_flag_pointers["CUSTOM2"] = &uses_custom2;
2928 actions.usage_flag_pointers["CUSTOM3"] = &uses_custom3;
2929 actions.usage_flag_pointers["BONE_INDICES"] = &uses_bones;
2930 actions.usage_flag_pointers["BONE_WEIGHTS"] = &uses_weights;
2931
2932 actions.uniforms = &uniforms;
2933
2934 Error err = MaterialStorage::get_singleton()->shaders.compiler_scene.compile(RS::SHADER_SPATIAL, code, &actions, path, gen_code);
2935 ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed.");
2936
2937 if (version.is_null()) {
2938 version = MaterialStorage::get_singleton()->shaders.scene_shader.version_create();
2939 }
2940
2941 depth_draw = DepthDraw(depth_drawi);
2942 depth_test = DepthTest(depth_testi);
2943 cull_mode = Cull(cull_modei);
2944 blend_mode = BlendMode(blend_modei);
2945 alpha_antialiasing_mode = AlphaAntiAliasing(alpha_antialiasing_modei);
2946 vertex_input_mask = uint32_t(uses_normal);
2947 vertex_input_mask |= uses_tangent << 1;
2948 vertex_input_mask |= uses_color << 2;
2949 vertex_input_mask |= uses_uv << 3;
2950 vertex_input_mask |= uses_uv2 << 4;
2951 vertex_input_mask |= uses_custom0 << 5;
2952 vertex_input_mask |= uses_custom1 << 6;
2953 vertex_input_mask |= uses_custom2 << 7;
2954 vertex_input_mask |= uses_custom3 << 8;
2955 vertex_input_mask |= uses_bones << 9;
2956 vertex_input_mask |= uses_weights << 10;
2957 uses_screen_texture_mipmaps = gen_code.uses_screen_texture_mipmaps;
2958 uses_screen_texture = gen_code.uses_screen_texture;
2959 uses_depth_texture = gen_code.uses_depth_texture;
2960 uses_normal_texture = gen_code.uses_normal_roughness_texture;
2961 uses_vertex_time = gen_code.uses_vertex_time;
2962 uses_fragment_time = gen_code.uses_fragment_time;
2963
2964#ifdef DEBUG_ENABLED
2965 if (uses_particle_trails) {
2966 WARN_PRINT_ONCE_ED("Particle trails are only available when using the Forward+ or Mobile rendering backends.");
2967 }
2968
2969 if (uses_sss) {
2970 WARN_PRINT_ONCE_ED("Sub-surface scattering is only available when using the Forward+ rendering backend.");
2971 }
2972
2973 if (uses_transmittance) {
2974 WARN_PRINT_ONCE_ED("Transmittance is only available when using the Forward+ rendering backend.");
2975 }
2976
2977 if (uses_depth_texture) {
2978 WARN_PRINT_ONCE_ED("Reading from the depth texture is not supported when using the GL Compatibility backend yet. Support will be added in a future release.");
2979 }
2980
2981 if (uses_normal_texture) {
2982 WARN_PRINT_ONCE_ED("Reading from the normal-roughness texture is only available when using the Forward+ or Mobile rendering backends.");
2983 }
2984#endif
2985
2986#if 0
2987 print_line("**compiling shader:");
2988 print_line("**defines:\n");
2989 for (int i = 0; i < gen_code.defines.size(); i++) {
2990 print_line(gen_code.defines[i]);
2991 }
2992
2993 HashMap<String, String>::Iterator el = gen_code.code.begin();
2994 while (el) {
2995 print_line("\n**code " + el->key + ":\n" + el->value);
2996 ++el;
2997 }
2998
2999 print_line("\n**uniforms:\n" + gen_code.uniforms);
3000 print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);
3001 print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);
3002#endif
3003
3004 LocalVector<ShaderGLES3::TextureUniformData> texture_uniform_data = get_texture_uniform_data(gen_code.texture_uniforms);
3005
3006 MaterialStorage::get_singleton()->shaders.scene_shader.version_set_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines, texture_uniform_data);
3007 ERR_FAIL_COND(!MaterialStorage::get_singleton()->shaders.scene_shader.version_is_valid(version));
3008
3009 ubo_size = gen_code.uniform_total_size;
3010 ubo_offsets = gen_code.uniform_offsets;
3011 texture_uniforms = gen_code.texture_uniforms;
3012
3013 // if any form of Alpha Antialiasing is enabled, set the blend mode to alpha to coverage
3014 if (alpha_antialiasing_mode != ALPHA_ANTIALIASING_OFF) {
3015 blend_mode = BLEND_MODE_ALPHA_TO_COVERAGE;
3016 }
3017
3018 if (blend_mode == BLEND_MODE_ADD || blend_mode == BLEND_MODE_SUB || blend_mode == BLEND_MODE_MUL) {
3019 uses_blend_alpha = true; // Force alpha used because of blend.
3020 }
3021
3022 valid = true;
3023}
3024
3025bool SceneShaderData::is_animated() const {
3026 return (uses_fragment_time && uses_discard) || (uses_vertex_time && uses_vertex);
3027}
3028
3029bool SceneShaderData::casts_shadows() const {
3030 bool has_read_screen_alpha = uses_screen_texture || uses_depth_texture || uses_normal_texture;
3031 bool has_base_alpha = (uses_alpha && !uses_alpha_clip) || has_read_screen_alpha;
3032 bool has_alpha = has_base_alpha || uses_blend_alpha;
3033
3034 return !has_alpha || (uses_depth_prepass_alpha && !(depth_draw == DEPTH_DRAW_DISABLED || depth_test == DEPTH_TEST_DISABLED));
3035}
3036
3037RS::ShaderNativeSourceCode SceneShaderData::get_native_source_code() const {
3038 return MaterialStorage::get_singleton()->shaders.scene_shader.version_get_native_source_code(version);
3039}
3040
3041SceneShaderData::SceneShaderData() {
3042 valid = false;
3043 uses_screen_texture = false;
3044}
3045
3046SceneShaderData::~SceneShaderData() {
3047 if (version.is_valid()) {
3048 MaterialStorage::get_singleton()->shaders.scene_shader.version_free(version);
3049 }
3050}
3051
3052GLES3::ShaderData *GLES3::_create_scene_shader_func() {
3053 SceneShaderData *shader_data = memnew(SceneShaderData);
3054 return shader_data;
3055}
3056
3057void SceneMaterialData::set_render_priority(int p_priority) {
3058 priority = p_priority - RS::MATERIAL_RENDER_PRIORITY_MIN; //8 bits
3059}
3060
3061void SceneMaterialData::set_next_pass(RID p_pass) {
3062 next_pass = p_pass;
3063}
3064
3065void SceneMaterialData::update_parameters(const HashMap<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
3066 update_parameters_internal(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, true);
3067}
3068
3069SceneMaterialData::~SceneMaterialData() {
3070}
3071
3072GLES3::MaterialData *GLES3::_create_scene_material_func(ShaderData *p_shader) {
3073 SceneMaterialData *material_data = memnew(SceneMaterialData);
3074 material_data->shader_data = static_cast<SceneShaderData *>(p_shader);
3075 //update will happen later anyway so do nothing.
3076 return material_data;
3077}
3078
3079void SceneMaterialData::bind_uniforms() {
3080 // Bind Material Uniforms
3081 glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_MATERIAL_UNIFORM_LOCATION, uniform_buffer);
3082
3083 bind_uniforms_generic(texture_cache, shader_data->texture_uniforms);
3084}
3085
3086/* Particles SHADER */
3087
3088void ParticlesShaderData::set_code(const String &p_code) {
3089 //compile
3090
3091 code = p_code;
3092 valid = false;
3093 ubo_size = 0;
3094 uniforms.clear();
3095 uses_collision = false;
3096
3097 if (code.is_empty()) {
3098 return; //just invalid, but no error
3099 }
3100
3101 ShaderCompiler::GeneratedCode gen_code;
3102 ShaderCompiler::IdentifierActions actions;
3103 actions.entry_point_stages["start"] = ShaderCompiler::STAGE_VERTEX;
3104 actions.entry_point_stages["process"] = ShaderCompiler::STAGE_VERTEX;
3105
3106 actions.usage_flag_pointers["COLLIDED"] = &uses_collision;
3107
3108 userdata_count = 0;
3109 for (uint32_t i = 0; i < PARTICLES_MAX_USERDATAS; i++) {
3110 userdatas_used[i] = false;
3111 actions.usage_flag_pointers["USERDATA" + itos(i + 1)] = &userdatas_used[i];
3112 }
3113
3114 actions.uniforms = &uniforms;
3115
3116 Error err = MaterialStorage::get_singleton()->shaders.compiler_particles.compile(RS::SHADER_PARTICLES, code, &actions, path, gen_code);
3117 ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed.");
3118
3119 if (version.is_null()) {
3120 version = MaterialStorage::get_singleton()->shaders.particles_process_shader.version_create();
3121 }
3122
3123 for (uint32_t i = 0; i < PARTICLES_MAX_USERDATAS; i++) {
3124 if (userdatas_used[i]) {
3125 userdata_count++;
3126 }
3127 }
3128
3129 LocalVector<ShaderGLES3::TextureUniformData> texture_uniform_data = get_texture_uniform_data(gen_code.texture_uniforms);
3130
3131 MaterialStorage::get_singleton()->shaders.particles_process_shader.version_set_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines, texture_uniform_data);
3132 ERR_FAIL_COND(!MaterialStorage::get_singleton()->shaders.particles_process_shader.version_is_valid(version));
3133
3134 ubo_size = gen_code.uniform_total_size;
3135 ubo_offsets = gen_code.uniform_offsets;
3136 texture_uniforms = gen_code.texture_uniforms;
3137
3138 valid = true;
3139}
3140
3141bool ParticlesShaderData::is_animated() const {
3142 return false;
3143}
3144
3145bool ParticlesShaderData::casts_shadows() const {
3146 return false;
3147}
3148
3149RS::ShaderNativeSourceCode ParticlesShaderData::get_native_source_code() const {
3150 return MaterialStorage::get_singleton()->shaders.particles_process_shader.version_get_native_source_code(version);
3151}
3152
3153ParticlesShaderData::~ParticlesShaderData() {
3154 if (version.is_valid()) {
3155 MaterialStorage::get_singleton()->shaders.particles_process_shader.version_free(version);
3156 }
3157}
3158
3159GLES3::ShaderData *GLES3::_create_particles_shader_func() {
3160 ParticlesShaderData *shader_data = memnew(ParticlesShaderData);
3161 return shader_data;
3162}
3163
3164void ParticleProcessMaterialData::update_parameters(const HashMap<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
3165 update_parameters_internal(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, true);
3166}
3167
3168ParticleProcessMaterialData::~ParticleProcessMaterialData() {
3169}
3170
3171GLES3::MaterialData *GLES3::_create_particles_material_func(ShaderData *p_shader) {
3172 ParticleProcessMaterialData *material_data = memnew(ParticleProcessMaterialData);
3173 material_data->shader_data = static_cast<ParticlesShaderData *>(p_shader);
3174 //update will happen later anyway so do nothing.
3175 return material_data;
3176}
3177
3178void ParticleProcessMaterialData::bind_uniforms() {
3179 // Bind Material Uniforms
3180 glBindBufferBase(GL_UNIFORM_BUFFER, GLES3::PARTICLES_MATERIAL_UNIFORM_LOCATION, uniform_buffer);
3181
3182 bind_uniforms_generic(texture_cache, shader_data->texture_uniforms, 1); // Start at GL_TEXTURE1 because texture slot 0 is reserved for the heightmap texture.
3183}
3184
3185#endif // !GLES3_ENABLED
3186