1/**************************************************************************/
2/* sky.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#include "sky.h"
32#include "core/config/project_settings.h"
33#include "core/math/math_defs.h"
34#include "servers/rendering/renderer_rd/effects/copy_effects.h"
35#include "servers/rendering/renderer_rd/framebuffer_cache_rd.h"
36#include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
37#include "servers/rendering/renderer_rd/renderer_scene_render_rd.h"
38#include "servers/rendering/renderer_rd/storage_rd/material_storage.h"
39#include "servers/rendering/renderer_rd/storage_rd/render_scene_buffers_rd.h"
40#include "servers/rendering/renderer_rd/storage_rd/texture_storage.h"
41#include "servers/rendering/renderer_rd/uniform_set_cache_rd.h"
42#include "servers/rendering/rendering_server_default.h"
43#include "servers/rendering/rendering_server_globals.h"
44
45using namespace RendererRD;
46
47#define RB_SCOPE_SKY SNAME("sky_buffers")
48#define RB_HALF_TEXTURE SNAME("half_texture")
49#define RB_QUARTER_TEXTURE SNAME("quarter_texture")
50
51////////////////////////////////////////////////////////////////////////////////
52// SKY SHADER
53
54void SkyRD::SkyShaderData::set_code(const String &p_code) {
55 //compile
56
57 code = p_code;
58 valid = false;
59 ubo_size = 0;
60 uniforms.clear();
61
62 if (code.is_empty()) {
63 return; //just invalid, but no error
64 }
65
66 ShaderCompiler::GeneratedCode gen_code;
67 ShaderCompiler::IdentifierActions actions;
68 actions.entry_point_stages["sky"] = ShaderCompiler::STAGE_FRAGMENT;
69
70 uses_time = false;
71 uses_half_res = false;
72 uses_quarter_res = false;
73 uses_position = false;
74 uses_light = false;
75
76 actions.render_mode_flags["use_half_res_pass"] = &uses_half_res;
77 actions.render_mode_flags["use_quarter_res_pass"] = &uses_quarter_res;
78
79 actions.usage_flag_pointers["TIME"] = &uses_time;
80 actions.usage_flag_pointers["POSITION"] = &uses_position;
81 actions.usage_flag_pointers["LIGHT0_ENABLED"] = &uses_light;
82 actions.usage_flag_pointers["LIGHT0_ENERGY"] = &uses_light;
83 actions.usage_flag_pointers["LIGHT0_DIRECTION"] = &uses_light;
84 actions.usage_flag_pointers["LIGHT0_COLOR"] = &uses_light;
85 actions.usage_flag_pointers["LIGHT0_SIZE"] = &uses_light;
86 actions.usage_flag_pointers["LIGHT1_ENABLED"] = &uses_light;
87 actions.usage_flag_pointers["LIGHT1_ENERGY"] = &uses_light;
88 actions.usage_flag_pointers["LIGHT1_DIRECTION"] = &uses_light;
89 actions.usage_flag_pointers["LIGHT1_COLOR"] = &uses_light;
90 actions.usage_flag_pointers["LIGHT1_SIZE"] = &uses_light;
91 actions.usage_flag_pointers["LIGHT2_ENABLED"] = &uses_light;
92 actions.usage_flag_pointers["LIGHT2_ENERGY"] = &uses_light;
93 actions.usage_flag_pointers["LIGHT2_DIRECTION"] = &uses_light;
94 actions.usage_flag_pointers["LIGHT2_COLOR"] = &uses_light;
95 actions.usage_flag_pointers["LIGHT2_SIZE"] = &uses_light;
96 actions.usage_flag_pointers["LIGHT3_ENABLED"] = &uses_light;
97 actions.usage_flag_pointers["LIGHT3_ENERGY"] = &uses_light;
98 actions.usage_flag_pointers["LIGHT3_DIRECTION"] = &uses_light;
99 actions.usage_flag_pointers["LIGHT3_COLOR"] = &uses_light;
100 actions.usage_flag_pointers["LIGHT3_SIZE"] = &uses_light;
101
102 actions.uniforms = &uniforms;
103
104 // !BAS! Contemplate making `SkyShader sky` accessible from this struct or even part of this struct.
105 RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton);
106
107 Error err = scene_singleton->sky.sky_shader.compiler.compile(RS::SHADER_SKY, code, &actions, path, gen_code);
108 ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed.");
109
110 if (version.is_null()) {
111 version = scene_singleton->sky.sky_shader.shader.version_create();
112 }
113
114#if 0
115 print_line("**compiling shader:");
116 print_line("**defines:\n");
117 for (int i = 0; i < gen_code.defines.size(); i++) {
118 print_line(gen_code.defines[i]);
119 }
120
121 HashMap<String, String>::Iterator el = gen_code.code.begin();
122 while (el) {
123 print_line("\n**code " + el->key + ":\n" + el->value);
124 ++el;
125 }
126
127 print_line("\n**uniforms:\n" + gen_code.uniforms);
128 print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);
129 print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);
130#endif
131
132 scene_singleton->sky.sky_shader.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);
133 ERR_FAIL_COND(!scene_singleton->sky.sky_shader.shader.version_is_valid(version));
134
135 ubo_size = gen_code.uniform_total_size;
136 ubo_offsets = gen_code.uniform_offsets;
137 texture_uniforms = gen_code.texture_uniforms;
138
139 //update pipelines
140
141 for (int i = 0; i < SKY_VERSION_MAX; i++) {
142 RD::PipelineDepthStencilState depth_stencil_state;
143 depth_stencil_state.enable_depth_test = true;
144 depth_stencil_state.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
145
146 if (scene_singleton->sky.sky_shader.shader.is_variant_enabled(i)) {
147 RID shader_variant = scene_singleton->sky.sky_shader.shader.version_get_shader(version, i);
148 pipelines[i].setup(shader_variant, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), depth_stencil_state, RD::PipelineColorBlendState::create_disabled(), 0);
149 } else {
150 pipelines[i].clear();
151 }
152 }
153
154 valid = true;
155}
156
157bool SkyRD::SkyShaderData::is_animated() const {
158 return false;
159}
160
161bool SkyRD::SkyShaderData::casts_shadows() const {
162 return false;
163}
164
165RS::ShaderNativeSourceCode SkyRD::SkyShaderData::get_native_source_code() const {
166 RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton);
167
168 return scene_singleton->sky.sky_shader.shader.version_get_native_source_code(version);
169}
170
171SkyRD::SkyShaderData::~SkyShaderData() {
172 RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton);
173 ERR_FAIL_COND(!scene_singleton);
174 //pipeline variants will clear themselves if shader is gone
175 if (version.is_valid()) {
176 scene_singleton->sky.sky_shader.shader.version_free(version);
177 }
178}
179
180////////////////////////////////////////////////////////////////////////////////
181// Sky material
182
183bool SkyRD::SkyMaterialData::update_parameters(const HashMap<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
184 RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton);
185
186 uniform_set_updated = true;
187
188 return update_parameters_uniform_set(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, uniform_set, scene_singleton->sky.sky_shader.shader.version_get_shader(shader_data->version, 0), SKY_SET_MATERIAL, true, true);
189}
190
191SkyRD::SkyMaterialData::~SkyMaterialData() {
192 free_parameters_uniform_set(uniform_set);
193}
194
195////////////////////////////////////////////////////////////////////////////////
196// Render sky
197
198static _FORCE_INLINE_ void store_transform_3x3(const Basis &p_basis, float *p_array) {
199 p_array[0] = p_basis.rows[0][0];
200 p_array[1] = p_basis.rows[1][0];
201 p_array[2] = p_basis.rows[2][0];
202 p_array[3] = 0;
203 p_array[4] = p_basis.rows[0][1];
204 p_array[5] = p_basis.rows[1][1];
205 p_array[6] = p_basis.rows[2][1];
206 p_array[7] = 0;
207 p_array[8] = p_basis.rows[0][2];
208 p_array[9] = p_basis.rows[1][2];
209 p_array[10] = p_basis.rows[2][2];
210 p_array[11] = 0;
211}
212
213void SkyRD::_render_sky(RD::DrawListID p_list, float p_time, RID p_fb, PipelineCacheRD *p_pipeline, RID p_uniform_set, RID p_texture_set, const Projection &p_projection, const Basis &p_orientation, const Vector3 &p_position, float p_luminance_multiplier) {
214 SkyPushConstant sky_push_constant;
215
216 memset(&sky_push_constant, 0, sizeof(SkyPushConstant));
217
218 // We only need key components of our projection matrix
219 sky_push_constant.projection[0] = p_projection.columns[2][0];
220 sky_push_constant.projection[1] = p_projection.columns[0][0];
221 sky_push_constant.projection[2] = p_projection.columns[2][1];
222 sky_push_constant.projection[3] = p_projection.columns[1][1];
223
224 sky_push_constant.position[0] = p_position.x;
225 sky_push_constant.position[1] = p_position.y;
226 sky_push_constant.position[2] = p_position.z;
227 sky_push_constant.time = p_time;
228 sky_push_constant.luminance_multiplier = p_luminance_multiplier;
229 store_transform_3x3(p_orientation, sky_push_constant.orientation);
230
231 RenderingDevice::FramebufferFormatID fb_format = RD::get_singleton()->framebuffer_get_format(p_fb);
232
233 RD::DrawListID draw_list = p_list;
234
235 RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, p_pipeline->get_render_pipeline(RD::INVALID_ID, fb_format, false, RD::get_singleton()->draw_list_get_current_pass()));
236
237 // Update uniform sets.
238 {
239 RD::get_singleton()->draw_list_bind_uniform_set(draw_list, sky_scene_state.uniform_set, SKY_SET_UNIFORMS);
240 if (p_uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(p_uniform_set)) { // Material may not have a uniform set.
241 RD::get_singleton()->draw_list_bind_uniform_set(draw_list, p_uniform_set, SKY_SET_MATERIAL);
242 }
243 RD::get_singleton()->draw_list_bind_uniform_set(draw_list, p_texture_set, SKY_SET_TEXTURES);
244 // Fog uniform set can be invalidated before drawing, so validate at draw time
245 if (sky_scene_state.fog_uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(sky_scene_state.fog_uniform_set)) {
246 RD::get_singleton()->draw_list_bind_uniform_set(draw_list, sky_scene_state.fog_uniform_set, SKY_SET_FOG);
247 } else {
248 RD::get_singleton()->draw_list_bind_uniform_set(draw_list, sky_scene_state.default_fog_uniform_set, SKY_SET_FOG);
249 }
250 }
251
252 RD::get_singleton()->draw_list_set_push_constant(draw_list, &sky_push_constant, sizeof(SkyPushConstant));
253
254 RD::get_singleton()->draw_list_draw(draw_list, false, 1u, 3u);
255}
256
257////////////////////////////////////////////////////////////////////////////////
258// ReflectionData
259
260void SkyRD::ReflectionData::clear_reflection_data() {
261 layers.clear();
262 radiance_base_cubemap = RID();
263 if (downsampled_radiance_cubemap.is_valid()) {
264 RD::get_singleton()->free(downsampled_radiance_cubemap);
265 }
266 downsampled_radiance_cubemap = RID();
267 downsampled_layer.mipmaps.clear();
268 coefficient_buffer = RID();
269}
270
271void SkyRD::ReflectionData::update_reflection_data(int p_size, int p_mipmaps, bool p_use_array, RID p_base_cube, int p_base_layer, bool p_low_quality, int p_roughness_layers, RD::DataFormat p_texture_format) {
272 //recreate radiance and all data
273
274 int mipmaps = p_mipmaps;
275 uint32_t w = p_size, h = p_size;
276
277 bool render_buffers_can_be_storage = RendererSceneRenderRD::get_singleton()->_render_buffers_can_be_storage();
278
279 if (p_use_array) {
280 int num_layers = p_low_quality ? 8 : p_roughness_layers;
281
282 for (int i = 0; i < num_layers; i++) {
283 ReflectionData::Layer layer;
284 uint32_t mmw = w;
285 uint32_t mmh = h;
286 layer.mipmaps.resize(mipmaps);
287 layer.views.resize(mipmaps);
288 for (int j = 0; j < mipmaps; j++) {
289 ReflectionData::Layer::Mipmap &mm = layer.mipmaps.write[j];
290 mm.size.width = mmw;
291 mm.size.height = mmh;
292 for (int k = 0; k < 6; k++) {
293 mm.views[k] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + i * 6 + k, j);
294 Vector<RID> fbtex;
295 fbtex.push_back(mm.views[k]);
296 mm.framebuffers[k] = RD::get_singleton()->framebuffer_create(fbtex);
297 }
298
299 layer.views.write[j] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + i * 6, j, 1, RD::TEXTURE_SLICE_CUBEMAP);
300
301 mmw = MAX(1u, mmw >> 1);
302 mmh = MAX(1u, mmh >> 1);
303 }
304
305 layers.push_back(layer);
306 }
307
308 } else {
309 mipmaps = p_low_quality ? 8 : mipmaps;
310 //regular cubemap, lower quality (aliasing, less memory)
311 ReflectionData::Layer layer;
312 uint32_t mmw = w;
313 uint32_t mmh = h;
314 layer.mipmaps.resize(mipmaps);
315 layer.views.resize(mipmaps);
316 for (int j = 0; j < mipmaps; j++) {
317 ReflectionData::Layer::Mipmap &mm = layer.mipmaps.write[j];
318 mm.size.width = mmw;
319 mm.size.height = mmh;
320 for (int k = 0; k < 6; k++) {
321 mm.views[k] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + k, j);
322 Vector<RID> fbtex;
323 fbtex.push_back(mm.views[k]);
324 mm.framebuffers[k] = RD::get_singleton()->framebuffer_create(fbtex);
325 }
326
327 layer.views.write[j] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer, j, 1, RD::TEXTURE_SLICE_CUBEMAP);
328
329 mmw = MAX(1u, mmw >> 1);
330 mmh = MAX(1u, mmh >> 1);
331 }
332
333 layers.push_back(layer);
334 }
335
336 radiance_base_cubemap = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer, 0, 1, RD::TEXTURE_SLICE_CUBEMAP);
337 RD::get_singleton()->set_resource_name(radiance_base_cubemap, "radiance base cubemap");
338
339 RD::TextureFormat tf;
340 tf.format = p_texture_format;
341 tf.width = p_low_quality ? 64 : p_size >> 1; // Always 64x64 when using REALTIME.
342 tf.height = p_low_quality ? 64 : p_size >> 1;
343 tf.texture_type = RD::TEXTURE_TYPE_CUBE;
344 tf.array_layers = 6;
345 tf.mipmaps = p_low_quality ? 7 : mipmaps - 1;
346 tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
347 if (render_buffers_can_be_storage) {
348 tf.usage_bits |= RD::TEXTURE_USAGE_STORAGE_BIT;
349 }
350
351 downsampled_radiance_cubemap = RD::get_singleton()->texture_create(tf, RD::TextureView());
352 RD::get_singleton()->set_resource_name(downsampled_radiance_cubemap, "downsampled radiance cubemap");
353 {
354 uint32_t mmw = tf.width;
355 uint32_t mmh = tf.height;
356 downsampled_layer.mipmaps.resize(tf.mipmaps);
357 for (int j = 0; j < downsampled_layer.mipmaps.size(); j++) {
358 ReflectionData::DownsampleLayer::Mipmap &mm = downsampled_layer.mipmaps.write[j];
359 mm.size.width = mmw;
360 mm.size.height = mmh;
361 mm.view = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), downsampled_radiance_cubemap, 0, j, 1, RD::TEXTURE_SLICE_CUBEMAP);
362 RD::get_singleton()->set_resource_name(mm.view, "Downsampled Radiance Cubemap Mip " + itos(j) + " ");
363 if (!render_buffers_can_be_storage) {
364 // we need a framebuffer for each side of our cubemap
365
366 for (int k = 0; k < 6; k++) {
367 mm.views[k] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), downsampled_radiance_cubemap, k, j);
368 RD::get_singleton()->set_resource_name(mm.view, "Downsampled Radiance Cubemap Mip: " + itos(j) + " Face: " + itos(k) + " ");
369 Vector<RID> fbtex;
370 fbtex.push_back(mm.views[k]);
371 mm.framebuffers[k] = RD::get_singleton()->framebuffer_create(fbtex);
372 }
373 }
374
375 mmw = MAX(1u, mmw >> 1);
376 mmh = MAX(1u, mmh >> 1);
377 }
378 }
379}
380
381void SkyRD::ReflectionData::create_reflection_fast_filter(bool p_use_arrays) {
382 RendererRD::CopyEffects *copy_effects = RendererRD::CopyEffects::get_singleton();
383 ERR_FAIL_NULL_MSG(copy_effects, "Effects haven't been initialized");
384 bool prefer_raster_effects = copy_effects->get_prefer_raster_effects();
385
386 if (prefer_raster_effects) {
387 RD::get_singleton()->draw_command_begin_label("Downsample radiance map");
388 for (int k = 0; k < 6; k++) {
389 copy_effects->cubemap_downsample_raster(radiance_base_cubemap, downsampled_layer.mipmaps[0].framebuffers[k], k, downsampled_layer.mipmaps[0].size);
390 }
391
392 for (int i = 1; i < downsampled_layer.mipmaps.size(); i++) {
393 for (int k = 0; k < 6; k++) {
394 copy_effects->cubemap_downsample_raster(downsampled_layer.mipmaps[i - 1].view, downsampled_layer.mipmaps[i].framebuffers[k], k, downsampled_layer.mipmaps[i].size);
395 }
396 }
397 RD::get_singleton()->draw_command_end_label(); // Downsample Radiance
398
399 if (p_use_arrays) {
400 RD::get_singleton()->draw_command_begin_label("filter radiance map into array heads");
401 for (int i = 0; i < layers.size(); i++) {
402 for (int k = 0; k < 6; k++) {
403 copy_effects->cubemap_filter_raster(downsampled_radiance_cubemap, layers[i].mipmaps[0].framebuffers[k], k, i);
404 }
405 }
406 } else {
407 RD::get_singleton()->draw_command_begin_label("filter radiance map into mipmaps directly");
408 for (int j = 0; j < layers[0].mipmaps.size(); j++) {
409 for (int k = 0; k < 6; k++) {
410 copy_effects->cubemap_filter_raster(downsampled_radiance_cubemap, layers[0].mipmaps[j].framebuffers[k], k, j);
411 }
412 }
413 }
414 RD::get_singleton()->draw_command_end_label(); // Filter radiance
415 } else {
416 RD::get_singleton()->draw_command_begin_label("Downsample radiance map");
417 copy_effects->cubemap_downsample(radiance_base_cubemap, downsampled_layer.mipmaps[0].view, downsampled_layer.mipmaps[0].size);
418
419 for (int i = 1; i < downsampled_layer.mipmaps.size(); i++) {
420 copy_effects->cubemap_downsample(downsampled_layer.mipmaps[i - 1].view, downsampled_layer.mipmaps[i].view, downsampled_layer.mipmaps[i].size);
421 }
422 RD::get_singleton()->draw_command_end_label(); // Downsample Radiance
423 Vector<RID> views;
424 if (p_use_arrays) {
425 for (int i = 1; i < layers.size(); i++) {
426 views.push_back(layers[i].views[0]);
427 }
428 } else {
429 for (int i = 1; i < layers[0].views.size(); i++) {
430 views.push_back(layers[0].views[i]);
431 }
432 }
433 RD::get_singleton()->draw_command_begin_label("Fast filter radiance");
434 copy_effects->cubemap_filter(downsampled_radiance_cubemap, views, p_use_arrays);
435 RD::get_singleton()->draw_command_end_label(); // Filter radiance
436 }
437}
438
439void SkyRD::ReflectionData::create_reflection_importance_sample(bool p_use_arrays, int p_cube_side, int p_base_layer, uint32_t p_sky_ggx_samples_quality) {
440 RendererRD::CopyEffects *copy_effects = RendererRD::CopyEffects::get_singleton();
441 ERR_FAIL_NULL_MSG(copy_effects, "Effects haven't been initialized");
442 bool prefer_raster_effects = copy_effects->get_prefer_raster_effects();
443
444 if (prefer_raster_effects) {
445 if (p_base_layer == 1) {
446 RD::get_singleton()->draw_command_begin_label("Downsample radiance map");
447 for (int k = 0; k < 6; k++) {
448 copy_effects->cubemap_downsample_raster(radiance_base_cubemap, downsampled_layer.mipmaps[0].framebuffers[k], k, downsampled_layer.mipmaps[0].size);
449 }
450
451 for (int i = 1; i < downsampled_layer.mipmaps.size(); i++) {
452 for (int k = 0; k < 6; k++) {
453 copy_effects->cubemap_downsample_raster(downsampled_layer.mipmaps[i - 1].view, downsampled_layer.mipmaps[i].framebuffers[k], k, downsampled_layer.mipmaps[i].size);
454 }
455 }
456 RD::get_singleton()->draw_command_end_label(); // Downsample Radiance
457 }
458
459 RD::get_singleton()->draw_command_begin_label("High Quality filter radiance");
460 if (p_use_arrays) {
461 for (int k = 0; k < 6; k++) {
462 copy_effects->cubemap_roughness_raster(
463 downsampled_radiance_cubemap,
464 layers[p_base_layer].mipmaps[0].framebuffers[k],
465 k,
466 p_sky_ggx_samples_quality,
467 float(p_base_layer) / (layers.size() - 1.0),
468 layers[p_base_layer].mipmaps[0].size.x);
469 }
470 } else {
471 for (int k = 0; k < 6; k++) {
472 copy_effects->cubemap_roughness_raster(
473 downsampled_radiance_cubemap,
474 layers[0].mipmaps[p_base_layer].framebuffers[k],
475 k,
476 p_sky_ggx_samples_quality,
477 float(p_base_layer) / (layers[0].mipmaps.size() - 1.0),
478 layers[0].mipmaps[p_base_layer].size.x);
479 }
480 }
481 } else {
482 if (p_base_layer == 1) {
483 RD::get_singleton()->draw_command_begin_label("Downsample radiance map");
484 copy_effects->cubemap_downsample(radiance_base_cubemap, downsampled_layer.mipmaps[0].view, downsampled_layer.mipmaps[0].size);
485
486 for (int i = 1; i < downsampled_layer.mipmaps.size(); i++) {
487 copy_effects->cubemap_downsample(downsampled_layer.mipmaps[i - 1].view, downsampled_layer.mipmaps[i].view, downsampled_layer.mipmaps[i].size);
488 }
489 RD::get_singleton()->draw_command_end_label(); // Downsample Radiance
490 }
491
492 RD::get_singleton()->draw_command_begin_label("High Quality filter radiance");
493 if (p_use_arrays) {
494 copy_effects->cubemap_roughness(downsampled_radiance_cubemap, layers[p_base_layer].views[0], p_cube_side, p_sky_ggx_samples_quality, float(p_base_layer) / (layers.size() - 1.0), layers[p_base_layer].mipmaps[0].size.x);
495 } else {
496 copy_effects->cubemap_roughness(
497 downsampled_radiance_cubemap,
498 layers[0].views[p_base_layer],
499 p_cube_side,
500 p_sky_ggx_samples_quality,
501 float(p_base_layer) / (layers[0].mipmaps.size() - 1.0),
502 layers[0].mipmaps[p_base_layer].size.x);
503 }
504 }
505 RD::get_singleton()->draw_command_end_label(); // Filter radiance
506}
507
508void SkyRD::ReflectionData::update_reflection_mipmaps(int p_start, int p_end) {
509 RendererRD::CopyEffects *copy_effects = RendererRD::CopyEffects::get_singleton();
510 ERR_FAIL_NULL_MSG(copy_effects, "Effects haven't been initialized");
511 bool prefer_raster_effects = copy_effects->get_prefer_raster_effects();
512
513 RD::get_singleton()->draw_command_begin_label("Update Radiance Cubemap Array Mipmaps");
514 for (int i = p_start; i < p_end; i++) {
515 for (int j = 0; j < layers[i].views.size() - 1; j++) {
516 RID view = layers[i].views[j];
517 Size2i size = layers[i].mipmaps[j + 1].size;
518 if (prefer_raster_effects) {
519 for (int k = 0; k < 6; k++) {
520 RID framebuffer = layers[i].mipmaps[j + 1].framebuffers[k];
521 copy_effects->cubemap_downsample_raster(view, framebuffer, k, size);
522 }
523 } else {
524 RID texture = layers[i].views[j + 1];
525 copy_effects->cubemap_downsample(view, texture, size);
526 }
527 }
528 }
529 RD::get_singleton()->draw_command_end_label();
530}
531
532////////////////////////////////////////////////////////////////////////////////
533// SkyRD::Sky
534
535void SkyRD::Sky::free() {
536 if (radiance.is_valid()) {
537 RD::get_singleton()->free(radiance);
538 radiance = RID();
539 }
540 reflection.clear_reflection_data();
541
542 if (uniform_buffer.is_valid()) {
543 RD::get_singleton()->free(uniform_buffer);
544 uniform_buffer = RID();
545 }
546
547 if (material.is_valid()) {
548 RSG::material_storage->material_free(material);
549 material = RID();
550 }
551}
552
553RID SkyRD::Sky::get_textures(SkyTextureSetVersion p_version, RID p_default_shader_rd, Ref<RenderSceneBuffersRD> p_render_buffers) {
554 RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();
555
556 Vector<RD::Uniform> uniforms;
557 {
558 RD::Uniform u;
559 u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
560 u.binding = 0;
561 if (radiance.is_valid() && p_version <= SKY_TEXTURE_SET_QUARTER_RES) {
562 u.append_id(radiance);
563 } else {
564 u.append_id(texture_storage->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
565 }
566 uniforms.push_back(u);
567 }
568 {
569 RD::Uniform u;
570 u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
571 u.binding = 1; // half res
572 if (p_version >= SKY_TEXTURE_SET_CUBEMAP) {
573 if (reflection.layers.size() && reflection.layers[0].views.size() >= 2 && reflection.layers[0].views[1].is_valid() && p_version != SKY_TEXTURE_SET_CUBEMAP_HALF_RES) {
574 u.append_id(reflection.layers[0].views[1]);
575 } else {
576 u.append_id(texture_storage->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
577 }
578 } else {
579 RID half_texture = p_render_buffers->has_texture(RB_SCOPE_SKY, RB_HALF_TEXTURE) ? p_render_buffers->get_texture(RB_SCOPE_SKY, RB_HALF_TEXTURE) : RID();
580 if (half_texture.is_valid() && p_version != SKY_TEXTURE_SET_HALF_RES) {
581 u.append_id(half_texture);
582 } else {
583 u.append_id(texture_storage->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_WHITE));
584 }
585 }
586 uniforms.push_back(u);
587 }
588 {
589 RD::Uniform u;
590 u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
591 u.binding = 2; // quarter res
592 if (p_version >= SKY_TEXTURE_SET_CUBEMAP) {
593 if (reflection.layers.size() && reflection.layers[0].views.size() >= 3 && reflection.layers[0].views[2].is_valid() && p_version != SKY_TEXTURE_SET_CUBEMAP_QUARTER_RES) {
594 u.append_id(reflection.layers[0].views[2]);
595 } else {
596 u.append_id(texture_storage->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
597 }
598 } else {
599 RID quarter_texture = p_render_buffers->has_texture(RB_SCOPE_SKY, RB_QUARTER_TEXTURE) ? p_render_buffers->get_texture(RB_SCOPE_SKY, RB_QUARTER_TEXTURE) : RID();
600 if (quarter_texture.is_valid() && p_version != SKY_TEXTURE_SET_QUARTER_RES) {
601 u.append_id(quarter_texture);
602 } else {
603 u.append_id(texture_storage->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_WHITE));
604 }
605 }
606 uniforms.push_back(u);
607 }
608
609 return UniformSetCacheRD::get_singleton()->get_cache_vec(p_default_shader_rd, SKY_SET_TEXTURES, uniforms);
610}
611
612bool SkyRD::Sky::set_radiance_size(int p_radiance_size) {
613 ERR_FAIL_COND_V(p_radiance_size < 32 || p_radiance_size > 2048, false);
614 if (radiance_size == p_radiance_size) {
615 return false;
616 }
617 radiance_size = p_radiance_size;
618
619 if (mode == RS::SKY_MODE_REALTIME && radiance_size != 256) {
620 WARN_PRINT("Realtime Skies can only use a radiance size of 256. Radiance size will be set to 256 internally.");
621 radiance_size = 256;
622 }
623
624 if (radiance.is_valid()) {
625 RD::get_singleton()->free(radiance);
626 radiance = RID();
627 }
628 reflection.clear_reflection_data();
629
630 return true;
631}
632
633bool SkyRD::Sky::set_mode(RS::SkyMode p_mode) {
634 if (mode == p_mode) {
635 return false;
636 }
637
638 mode = p_mode;
639
640 if (mode == RS::SKY_MODE_REALTIME && radiance_size != 256) {
641 WARN_PRINT("Realtime Skies can only use a radiance size of 256. Radiance size will be set to 256 internally.");
642 set_radiance_size(256);
643 }
644
645 if (radiance.is_valid()) {
646 RD::get_singleton()->free(radiance);
647 radiance = RID();
648 }
649 reflection.clear_reflection_data();
650
651 return true;
652}
653
654bool SkyRD::Sky::set_material(RID p_material) {
655 if (material == p_material) {
656 return false;
657 }
658
659 material = p_material;
660 return true;
661}
662
663Ref<Image> SkyRD::Sky::bake_panorama(float p_energy, int p_roughness_layers, const Size2i &p_size) {
664 if (radiance.is_valid()) {
665 RendererRD::CopyEffects *copy_effects = RendererRD::CopyEffects::get_singleton();
666
667 RD::TextureFormat tf;
668 tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; // Could be RGBA16
669 tf.width = p_size.width;
670 tf.height = p_size.height;
671 tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
672
673 RID rad_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
674 copy_effects->copy_cubemap_to_panorama(radiance, rad_tex, p_size, p_roughness_layers, reflection.layers.size() > 1);
675 Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rad_tex, 0);
676 RD::get_singleton()->free(rad_tex);
677
678 Ref<Image> img = Image::create_from_data(p_size.width, p_size.height, false, Image::FORMAT_RGBAF, data);
679 for (int i = 0; i < p_size.width; i++) {
680 for (int j = 0; j < p_size.height; j++) {
681 Color c = img->get_pixel(i, j);
682 c.r *= p_energy;
683 c.g *= p_energy;
684 c.b *= p_energy;
685 img->set_pixel(i, j, c);
686 }
687 }
688 return img;
689 }
690
691 return Ref<Image>();
692}
693
694////////////////////////////////////////////////////////////////////////////////
695// SkyRD
696
697RendererRD::MaterialStorage::ShaderData *SkyRD::_create_sky_shader_func() {
698 SkyShaderData *shader_data = memnew(SkyShaderData);
699 return shader_data;
700}
701
702RendererRD::MaterialStorage::ShaderData *SkyRD::_create_sky_shader_funcs() {
703 // !BAS! Why isn't _create_sky_shader_func not just static too?
704 return static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton)->sky._create_sky_shader_func();
705};
706
707RendererRD::MaterialStorage::MaterialData *SkyRD::_create_sky_material_func(SkyShaderData *p_shader) {
708 SkyMaterialData *material_data = memnew(SkyMaterialData);
709 material_data->shader_data = p_shader;
710 //update will happen later anyway so do nothing.
711 return material_data;
712}
713
714RendererRD::MaterialStorage::MaterialData *SkyRD::_create_sky_material_funcs(RendererRD::MaterialStorage::ShaderData *p_shader) {
715 // !BAS! same here, we could just make _create_sky_material_func static?
716 return static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton)->sky._create_sky_material_func(static_cast<SkyShaderData *>(p_shader));
717};
718
719SkyRD::SkyRD() {
720 roughness_layers = GLOBAL_GET("rendering/reflections/sky_reflections/roughness_layers");
721 sky_ggx_samples_quality = GLOBAL_GET("rendering/reflections/sky_reflections/ggx_samples");
722 sky_use_cubemap_array = GLOBAL_GET("rendering/reflections/sky_reflections/texture_array_reflections");
723}
724
725void SkyRD::init() {
726 RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();
727 RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
728
729 {
730 // Start with the directional lights for the sky
731 sky_scene_state.max_directional_lights = 4;
732 uint32_t directional_light_buffer_size = sky_scene_state.max_directional_lights * sizeof(SkyDirectionalLightData);
733 sky_scene_state.directional_lights = memnew_arr(SkyDirectionalLightData, sky_scene_state.max_directional_lights);
734 sky_scene_state.last_frame_directional_lights = memnew_arr(SkyDirectionalLightData, sky_scene_state.max_directional_lights);
735 sky_scene_state.last_frame_directional_light_count = sky_scene_state.max_directional_lights + 1;
736 sky_scene_state.directional_light_buffer = RD::get_singleton()->uniform_buffer_create(directional_light_buffer_size);
737
738 String defines = "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(sky_scene_state.max_directional_lights) + "\n";
739 defines += "\n#define SAMPLERS_BINDING_FIRST_INDEX " + itos(SAMPLERS_BINDING_FIRST_INDEX) + "\n";
740
741 // Initialize sky
742 Vector<String> sky_modes;
743 sky_modes.push_back(""); // Full size
744 sky_modes.push_back("\n#define USE_HALF_RES_PASS\n"); // Half Res
745 sky_modes.push_back("\n#define USE_QUARTER_RES_PASS\n"); // Quarter res
746 sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n"); // Cubemap
747 sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n#define USE_HALF_RES_PASS\n"); // Half Res Cubemap
748 sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n#define USE_QUARTER_RES_PASS\n"); // Quarter res Cubemap
749
750 sky_modes.push_back("\n#define USE_MULTIVIEW\n"); // Full size multiview
751 sky_modes.push_back("\n#define USE_HALF_RES_PASS\n#define USE_MULTIVIEW\n"); // Half Res multiview
752 sky_modes.push_back("\n#define USE_QUARTER_RES_PASS\n#define USE_MULTIVIEW\n"); // Quarter res multiview
753
754 sky_shader.shader.initialize(sky_modes, defines);
755
756 if (!RendererCompositorRD::get_singleton()->is_xr_enabled()) {
757 sky_shader.shader.set_variant_enabled(SKY_VERSION_BACKGROUND_MULTIVIEW, false);
758 sky_shader.shader.set_variant_enabled(SKY_VERSION_HALF_RES_MULTIVIEW, false);
759 sky_shader.shader.set_variant_enabled(SKY_VERSION_QUARTER_RES_MULTIVIEW, false);
760 }
761 }
762
763 // register our shader funds
764 material_storage->shader_set_data_request_function(RendererRD::MaterialStorage::SHADER_TYPE_SKY, _create_sky_shader_funcs);
765 material_storage->material_set_data_request_function(RendererRD::MaterialStorage::SHADER_TYPE_SKY, _create_sky_material_funcs);
766
767 {
768 ShaderCompiler::DefaultIdentifierActions actions;
769
770 actions.renames["COLOR"] = "color";
771 actions.renames["ALPHA"] = "alpha";
772 actions.renames["EYEDIR"] = "cube_normal";
773 actions.renames["POSITION"] = "params.position";
774 actions.renames["SKY_COORDS"] = "panorama_coords";
775 actions.renames["SCREEN_UV"] = "uv";
776 actions.renames["FRAGCOORD"] = "gl_FragCoord";
777 actions.renames["TIME"] = "params.time";
778 actions.renames["PI"] = _MKSTR(Math_PI);
779 actions.renames["TAU"] = _MKSTR(Math_TAU);
780 actions.renames["E"] = _MKSTR(Math_E);
781 actions.renames["HALF_RES_COLOR"] = "half_res_color";
782 actions.renames["QUARTER_RES_COLOR"] = "quarter_res_color";
783 actions.renames["RADIANCE"] = "radiance";
784 actions.renames["FOG"] = "custom_fog";
785 actions.renames["LIGHT0_ENABLED"] = "directional_lights.data[0].enabled";
786 actions.renames["LIGHT0_DIRECTION"] = "directional_lights.data[0].direction_energy.xyz";
787 actions.renames["LIGHT0_ENERGY"] = "directional_lights.data[0].direction_energy.w";
788 actions.renames["LIGHT0_COLOR"] = "directional_lights.data[0].color_size.xyz";
789 actions.renames["LIGHT0_SIZE"] = "directional_lights.data[0].color_size.w";
790 actions.renames["LIGHT1_ENABLED"] = "directional_lights.data[1].enabled";
791 actions.renames["LIGHT1_DIRECTION"] = "directional_lights.data[1].direction_energy.xyz";
792 actions.renames["LIGHT1_ENERGY"] = "directional_lights.data[1].direction_energy.w";
793 actions.renames["LIGHT1_COLOR"] = "directional_lights.data[1].color_size.xyz";
794 actions.renames["LIGHT1_SIZE"] = "directional_lights.data[1].color_size.w";
795 actions.renames["LIGHT2_ENABLED"] = "directional_lights.data[2].enabled";
796 actions.renames["LIGHT2_DIRECTION"] = "directional_lights.data[2].direction_energy.xyz";
797 actions.renames["LIGHT2_ENERGY"] = "directional_lights.data[2].direction_energy.w";
798 actions.renames["LIGHT2_COLOR"] = "directional_lights.data[2].color_size.xyz";
799 actions.renames["LIGHT2_SIZE"] = "directional_lights.data[2].color_size.w";
800 actions.renames["LIGHT3_ENABLED"] = "directional_lights.data[3].enabled";
801 actions.renames["LIGHT3_DIRECTION"] = "directional_lights.data[3].direction_energy.xyz";
802 actions.renames["LIGHT3_ENERGY"] = "directional_lights.data[3].direction_energy.w";
803 actions.renames["LIGHT3_COLOR"] = "directional_lights.data[3].color_size.xyz";
804 actions.renames["LIGHT3_SIZE"] = "directional_lights.data[3].color_size.w";
805 actions.renames["AT_CUBEMAP_PASS"] = "AT_CUBEMAP_PASS";
806 actions.renames["AT_HALF_RES_PASS"] = "AT_HALF_RES_PASS";
807 actions.renames["AT_QUARTER_RES_PASS"] = "AT_QUARTER_RES_PASS";
808 actions.custom_samplers["RADIANCE"] = "SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP";
809 actions.usage_defines["HALF_RES_COLOR"] = "\n#define USES_HALF_RES_COLOR\n";
810 actions.usage_defines["QUARTER_RES_COLOR"] = "\n#define USES_QUARTER_RES_COLOR\n";
811 actions.render_mode_defines["disable_fog"] = "#define DISABLE_FOG\n";
812 actions.render_mode_defines["use_debanding"] = "#define USE_DEBANDING\n";
813
814 actions.base_texture_binding_index = 1;
815 actions.texture_layout_set = 1;
816 actions.base_uniform_string = "material.";
817 actions.base_varying_index = 10;
818
819 actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
820 actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
821 actions.global_buffer_array_variable = "global_shader_uniforms.data";
822
823 sky_shader.compiler.initialize(actions);
824 }
825
826 {
827 // default material and shader for sky shader
828 sky_shader.default_shader = material_storage->shader_allocate();
829 material_storage->shader_initialize(sky_shader.default_shader);
830
831 material_storage->shader_set_code(sky_shader.default_shader, R"(
832// Default sky shader.
833
834shader_type sky;
835
836void sky() {
837 COLOR = vec3(0.0);
838}
839)");
840
841 sky_shader.default_material = material_storage->material_allocate();
842 material_storage->material_initialize(sky_shader.default_material);
843
844 material_storage->material_set_shader(sky_shader.default_material, sky_shader.default_shader);
845
846 SkyMaterialData *md = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_shader.default_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
847 sky_shader.default_shader_rd = sky_shader.shader.version_get_shader(md->shader_data->version, SKY_VERSION_BACKGROUND);
848
849 sky_scene_state.uniform_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(SkySceneState::UBO));
850
851 Vector<RD::Uniform> uniforms;
852
853 {
854 RD::Uniform u;
855 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
856 u.binding = 1;
857 u.append_id(RendererRD::MaterialStorage::get_singleton()->global_shader_uniforms_get_storage_buffer());
858 uniforms.push_back(u);
859 }
860
861 {
862 RD::Uniform u;
863 u.binding = 2;
864 u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
865 u.append_id(sky_scene_state.uniform_buffer);
866 uniforms.push_back(u);
867 }
868
869 {
870 RD::Uniform u;
871 u.binding = 3;
872 u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
873 u.append_id(sky_scene_state.directional_light_buffer);
874 uniforms.push_back(u);
875 }
876
877 uniforms.append_array(material_storage->get_default_sampler_uniforms(SAMPLERS_BINDING_FIRST_INDEX));
878
879 sky_scene_state.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_UNIFORMS);
880 }
881
882 {
883 Vector<RD::Uniform> uniforms;
884 {
885 RD::Uniform u;
886 u.binding = 0;
887 u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
888 RID vfog = texture_storage->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_3D_WHITE);
889 u.append_id(vfog);
890 uniforms.push_back(u);
891 }
892
893 sky_scene_state.default_fog_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_FOG);
894 }
895
896 {
897 // Need defaults for using fog with clear color
898 sky_scene_state.fog_shader = material_storage->shader_allocate();
899 material_storage->shader_initialize(sky_scene_state.fog_shader);
900
901 material_storage->shader_set_code(sky_scene_state.fog_shader, R"(
902// Default clear color sky shader.
903
904shader_type sky;
905
906uniform vec4 clear_color;
907
908void sky() {
909 COLOR = clear_color.rgb;
910}
911)");
912 sky_scene_state.fog_material = material_storage->material_allocate();
913 material_storage->material_initialize(sky_scene_state.fog_material);
914
915 material_storage->material_set_shader(sky_scene_state.fog_material, sky_scene_state.fog_shader);
916
917 Vector<RD::Uniform> uniforms;
918 {
919 RD::Uniform u;
920 u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
921 u.binding = 0;
922 u.append_id(texture_storage->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
923 uniforms.push_back(u);
924 }
925 {
926 RD::Uniform u;
927 u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
928 u.binding = 1;
929 u.append_id(texture_storage->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_WHITE));
930 uniforms.push_back(u);
931 }
932 {
933 RD::Uniform u;
934 u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
935 u.binding = 2;
936 u.append_id(texture_storage->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_WHITE));
937 uniforms.push_back(u);
938 }
939
940 sky_scene_state.fog_only_texture_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_TEXTURES);
941 }
942}
943
944void SkyRD::set_texture_format(RD::DataFormat p_texture_format) {
945 texture_format = p_texture_format;
946}
947
948SkyRD::~SkyRD() {
949 // cleanup anything created in init...
950 RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
951
952 SkyMaterialData *md = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_shader.default_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
953 sky_shader.shader.version_free(md->shader_data->version);
954 RD::get_singleton()->free(sky_scene_state.directional_light_buffer);
955 RD::get_singleton()->free(sky_scene_state.uniform_buffer);
956 memdelete_arr(sky_scene_state.directional_lights);
957 memdelete_arr(sky_scene_state.last_frame_directional_lights);
958 material_storage->shader_free(sky_shader.default_shader);
959 material_storage->material_free(sky_shader.default_material);
960 material_storage->shader_free(sky_scene_state.fog_shader);
961 material_storage->material_free(sky_scene_state.fog_material);
962
963 if (RD::get_singleton()->uniform_set_is_valid(sky_scene_state.uniform_set)) {
964 RD::get_singleton()->free(sky_scene_state.uniform_set);
965 }
966
967 if (RD::get_singleton()->uniform_set_is_valid(sky_scene_state.default_fog_uniform_set)) {
968 RD::get_singleton()->free(sky_scene_state.default_fog_uniform_set);
969 }
970
971 if (RD::get_singleton()->uniform_set_is_valid(sky_scene_state.fog_only_texture_uniform_set)) {
972 RD::get_singleton()->free(sky_scene_state.fog_only_texture_uniform_set);
973 }
974}
975
976void SkyRD::setup_sky(RID p_env, Ref<RenderSceneBuffersRD> p_render_buffers, const PagedArray<RID> &p_lights, RID p_camera_attributes, uint32_t p_view_count, const Projection *p_view_projections, const Vector3 *p_view_eye_offsets, const Transform3D &p_cam_transform, const Projection &p_cam_projection, const Size2i p_screen_size, RendererSceneRenderRD *p_scene_render) {
977 RendererRD::LightStorage *light_storage = RendererRD::LightStorage::get_singleton();
978 RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
979 ERR_FAIL_COND(p_env.is_null());
980
981 ERR_FAIL_COND(p_render_buffers.is_null());
982
983 // make sure we support our view count
984 ERR_FAIL_COND(p_view_count == 0);
985 ERR_FAIL_COND(p_view_count > RendererSceneRender::MAX_RENDER_VIEWS);
986
987 SkyMaterialData *material = nullptr;
988 Sky *sky = get_sky(RendererSceneRenderRD::get_singleton()->environment_get_sky(p_env));
989
990 RID sky_material;
991
992 SkyShaderData *shader_data = nullptr;
993
994 if (sky) {
995 sky_material = sky_get_material(RendererSceneRenderRD::get_singleton()->environment_get_sky(p_env));
996
997 if (sky_material.is_valid()) {
998 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
999 if (!material || !material->shader_data->valid) {
1000 material = nullptr;
1001 }
1002 }
1003 }
1004
1005 if (!material) {
1006 sky_material = sky_shader.default_material;
1007 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
1008 }
1009
1010 ERR_FAIL_COND(!material);
1011
1012 shader_data = material->shader_data;
1013
1014 ERR_FAIL_COND(!shader_data);
1015
1016 material->set_as_used();
1017
1018 if (sky) {
1019 // Save our screen size; our buffers will already have been cleared.
1020 sky->screen_size.x = p_screen_size.x < 4 ? 4 : p_screen_size.x;
1021 sky->screen_size.y = p_screen_size.y < 4 ? 4 : p_screen_size.y;
1022
1023 // Trigger updating radiance buffers.
1024 if (sky->radiance.is_null()) {
1025 invalidate_sky(sky);
1026 update_dirty_skys();
1027 }
1028
1029 if (shader_data->uses_time && p_scene_render->time - sky->prev_time > 0.00001) {
1030 sky->prev_time = p_scene_render->time;
1031 sky->reflection.dirty = true;
1032 RenderingServerDefault::redraw_request();
1033 }
1034
1035 if (material != sky->prev_material) {
1036 sky->prev_material = material;
1037 sky->reflection.dirty = true;
1038 }
1039
1040 if (material->uniform_set_updated) {
1041 material->uniform_set_updated = false;
1042 sky->reflection.dirty = true;
1043 }
1044
1045 if (!p_cam_transform.origin.is_equal_approx(sky->prev_position) && shader_data->uses_position) {
1046 sky->prev_position = p_cam_transform.origin;
1047 sky->reflection.dirty = true;
1048 }
1049 }
1050
1051 sky_scene_state.ubo.directional_light_count = 0;
1052 if (shader_data->uses_light) {
1053 // Run through the list of lights in the scene and pick out the Directional Lights.
1054 // This can't be done in RenderSceneRenderRD::_setup lights because that needs to be called
1055 // after the depth prepass, but this runs before the depth prepass.
1056 for (int i = 0; i < (int)p_lights.size(); i++) {
1057 if (!light_storage->owns_light_instance(p_lights[i])) {
1058 continue;
1059 }
1060 RID base = light_storage->light_instance_get_base_light(p_lights[i]);
1061
1062 ERR_CONTINUE(base.is_null());
1063
1064 RS::LightType type = light_storage->light_get_type(base);
1065 if (type == RS::LIGHT_DIRECTIONAL && light_storage->light_directional_get_sky_mode(base) != RS::LIGHT_DIRECTIONAL_SKY_MODE_LIGHT_ONLY) {
1066 SkyDirectionalLightData &sky_light_data = sky_scene_state.directional_lights[sky_scene_state.ubo.directional_light_count];
1067 Transform3D light_transform = light_storage->light_instance_get_base_transform(p_lights[i]);
1068 Vector3 world_direction = light_transform.basis.xform(Vector3(0, 0, 1)).normalized();
1069
1070 sky_light_data.direction[0] = world_direction.x;
1071 sky_light_data.direction[1] = world_direction.y;
1072 sky_light_data.direction[2] = world_direction.z;
1073
1074 float sign = light_storage->light_is_negative(base) ? -1 : 1;
1075 sky_light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY);
1076
1077 if (p_scene_render->is_using_physical_light_units()) {
1078 sky_light_data.energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
1079 }
1080
1081 if (p_camera_attributes.is_valid()) {
1082 sky_light_data.energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_camera_attributes);
1083 }
1084
1085 Color linear_col = light_storage->light_get_color(base).srgb_to_linear();
1086 sky_light_data.color[0] = linear_col.r;
1087 sky_light_data.color[1] = linear_col.g;
1088 sky_light_data.color[2] = linear_col.b;
1089
1090 sky_light_data.enabled = true;
1091
1092 float angular_diameter = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
1093 if (angular_diameter > 0.0) {
1094 // I know tan(0) is 0, but let's not risk it with numerical precision.
1095 // Technically this will keep expanding until reaching the sun, but all we care about
1096 // is expanding until we reach the radius of the near plane. There can't be more occluders than that.
1097 angular_diameter = Math::tan(Math::deg_to_rad(angular_diameter));
1098 } else {
1099 angular_diameter = 0.0;
1100 }
1101 sky_light_data.size = angular_diameter;
1102 sky_scene_state.ubo.directional_light_count++;
1103 if (sky_scene_state.ubo.directional_light_count >= sky_scene_state.max_directional_lights) {
1104 break;
1105 }
1106 }
1107 }
1108 // Check whether the directional_light_buffer changes.
1109 bool light_data_dirty = false;
1110
1111 // Light buffer is dirty if we have fewer or more lights.
1112 // If we have fewer lights, make sure that old lights are disabled.
1113 if (sky_scene_state.ubo.directional_light_count != sky_scene_state.last_frame_directional_light_count) {
1114 light_data_dirty = true;
1115 for (uint32_t i = sky_scene_state.ubo.directional_light_count; i < sky_scene_state.max_directional_lights; i++) {
1116 sky_scene_state.directional_lights[i].enabled = false;
1117 sky_scene_state.last_frame_directional_lights[i].enabled = false;
1118 }
1119 }
1120
1121 if (!light_data_dirty) {
1122 for (uint32_t i = 0; i < sky_scene_state.ubo.directional_light_count; i++) {
1123 if (sky_scene_state.directional_lights[i].direction[0] != sky_scene_state.last_frame_directional_lights[i].direction[0] ||
1124 sky_scene_state.directional_lights[i].direction[1] != sky_scene_state.last_frame_directional_lights[i].direction[1] ||
1125 sky_scene_state.directional_lights[i].direction[2] != sky_scene_state.last_frame_directional_lights[i].direction[2] ||
1126 sky_scene_state.directional_lights[i].energy != sky_scene_state.last_frame_directional_lights[i].energy ||
1127 sky_scene_state.directional_lights[i].color[0] != sky_scene_state.last_frame_directional_lights[i].color[0] ||
1128 sky_scene_state.directional_lights[i].color[1] != sky_scene_state.last_frame_directional_lights[i].color[1] ||
1129 sky_scene_state.directional_lights[i].color[2] != sky_scene_state.last_frame_directional_lights[i].color[2] ||
1130 sky_scene_state.directional_lights[i].enabled != sky_scene_state.last_frame_directional_lights[i].enabled ||
1131 sky_scene_state.directional_lights[i].size != sky_scene_state.last_frame_directional_lights[i].size) {
1132 light_data_dirty = true;
1133 break;
1134 }
1135 }
1136 }
1137
1138 if (light_data_dirty) {
1139 RD::get_singleton()->buffer_update(sky_scene_state.directional_light_buffer, 0, sizeof(SkyDirectionalLightData) * sky_scene_state.max_directional_lights, sky_scene_state.directional_lights);
1140
1141 SkyDirectionalLightData *temp = sky_scene_state.last_frame_directional_lights;
1142 sky_scene_state.last_frame_directional_lights = sky_scene_state.directional_lights;
1143 sky_scene_state.directional_lights = temp;
1144 sky_scene_state.last_frame_directional_light_count = sky_scene_state.ubo.directional_light_count;
1145 if (sky) {
1146 sky->reflection.dirty = true;
1147 }
1148 }
1149 }
1150
1151 // Setup fog variables.
1152 sky_scene_state.ubo.volumetric_fog_enabled = false;
1153 if (p_render_buffers.is_valid()) {
1154 if (p_render_buffers->has_custom_data(RB_SCOPE_FOG)) {
1155 Ref<RendererRD::Fog::VolumetricFog> fog = p_render_buffers->get_custom_data(RB_SCOPE_FOG);
1156 sky_scene_state.ubo.volumetric_fog_enabled = true;
1157
1158 float fog_end = fog->length;
1159 if (fog_end > 0.0) {
1160 sky_scene_state.ubo.volumetric_fog_inv_length = 1.0 / fog_end;
1161 } else {
1162 sky_scene_state.ubo.volumetric_fog_inv_length = 1.0;
1163 }
1164
1165 float fog_detail_spread = fog->spread; // Reverse lookup.
1166 if (fog_detail_spread > 0.0) {
1167 sky_scene_state.ubo.volumetric_fog_detail_spread = 1.0 / fog_detail_spread;
1168 } else {
1169 sky_scene_state.ubo.volumetric_fog_detail_spread = 1.0;
1170 }
1171
1172 sky_scene_state.fog_uniform_set = fog->sky_uniform_set;
1173 }
1174 }
1175
1176 sky_scene_state.view_count = p_view_count;
1177 sky_scene_state.cam_transform = p_cam_transform;
1178 sky_scene_state.cam_projection = p_cam_projection; // We only use this when rendering a single view.
1179
1180 // Our info in our UBO is only used if we're rendering stereo.
1181 for (uint32_t i = 0; i < p_view_count; i++) {
1182 Projection view_inv_projection = p_view_projections[i].inverse();
1183 if (p_view_count > 1) {
1184 RendererRD::MaterialStorage::store_camera(p_cam_projection * view_inv_projection, sky_scene_state.ubo.combined_reprojection[i]);
1185 } else {
1186 Projection ident;
1187 RendererRD::MaterialStorage::store_camera(ident, sky_scene_state.ubo.combined_reprojection[i]);
1188 }
1189
1190 RendererRD::MaterialStorage::store_camera(view_inv_projection, sky_scene_state.ubo.view_inv_projections[i]);
1191 sky_scene_state.ubo.view_eye_offsets[i][0] = p_view_eye_offsets[i].x;
1192 sky_scene_state.ubo.view_eye_offsets[i][1] = p_view_eye_offsets[i].y;
1193 sky_scene_state.ubo.view_eye_offsets[i][2] = p_view_eye_offsets[i].z;
1194 sky_scene_state.ubo.view_eye_offsets[i][3] = 0.0;
1195 }
1196
1197 sky_scene_state.ubo.z_far = p_view_projections[0].get_z_far(); // Should be the same for all projection.
1198 sky_scene_state.ubo.fog_enabled = RendererSceneRenderRD::get_singleton()->environment_get_fog_enabled(p_env);
1199 sky_scene_state.ubo.fog_density = RendererSceneRenderRD::get_singleton()->environment_get_fog_density(p_env);
1200 sky_scene_state.ubo.fog_aerial_perspective = RendererSceneRenderRD::get_singleton()->environment_get_fog_aerial_perspective(p_env);
1201 Color fog_color = RendererSceneRenderRD::get_singleton()->environment_get_fog_light_color(p_env).srgb_to_linear();
1202 float fog_energy = RendererSceneRenderRD::get_singleton()->environment_get_fog_light_energy(p_env);
1203 sky_scene_state.ubo.fog_light_color[0] = fog_color.r * fog_energy;
1204 sky_scene_state.ubo.fog_light_color[1] = fog_color.g * fog_energy;
1205 sky_scene_state.ubo.fog_light_color[2] = fog_color.b * fog_energy;
1206 sky_scene_state.ubo.fog_sun_scatter = RendererSceneRenderRD::get_singleton()->environment_get_fog_sun_scatter(p_env);
1207
1208 sky_scene_state.ubo.fog_sky_affect = RendererSceneRenderRD::get_singleton()->environment_get_fog_sky_affect(p_env);
1209 sky_scene_state.ubo.volumetric_fog_sky_affect = RendererSceneRenderRD::get_singleton()->environment_get_volumetric_fog_sky_affect(p_env);
1210
1211 RD::get_singleton()->buffer_update(sky_scene_state.uniform_buffer, 0, sizeof(SkySceneState::UBO), &sky_scene_state.ubo);
1212}
1213
1214void SkyRD::update_radiance_buffers(Ref<RenderSceneBuffersRD> p_render_buffers, RID p_env, const Vector3 &p_global_pos, double p_time, float p_luminance_multiplier) {
1215 ERR_FAIL_COND(p_render_buffers.is_null());
1216 RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
1217 ERR_FAIL_COND(p_env.is_null());
1218
1219 Sky *sky = get_sky(RendererSceneRenderRD::get_singleton()->environment_get_sky(p_env));
1220 ERR_FAIL_COND(!sky);
1221
1222 RID sky_material = sky_get_material(RendererSceneRenderRD::get_singleton()->environment_get_sky(p_env));
1223
1224 SkyMaterialData *material = nullptr;
1225
1226 if (sky_material.is_valid()) {
1227 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
1228 if (!material || !material->shader_data->valid) {
1229 material = nullptr;
1230 }
1231 }
1232
1233 if (!material) {
1234 sky_material = sky_shader.default_material;
1235 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
1236 }
1237
1238 ERR_FAIL_COND(!material);
1239
1240 SkyShaderData *shader_data = material->shader_data;
1241
1242 ERR_FAIL_COND(!shader_data);
1243
1244 bool update_single_frame = sky->mode == RS::SKY_MODE_REALTIME || sky->mode == RS::SKY_MODE_QUALITY;
1245 RS::SkyMode sky_mode = sky->mode;
1246
1247 if (sky_mode == RS::SKY_MODE_AUTOMATIC) {
1248 if (shader_data->uses_time || shader_data->uses_position) {
1249 update_single_frame = true;
1250 sky_mode = RS::SKY_MODE_REALTIME;
1251 } else if (shader_data->uses_light || shader_data->ubo_size > 0) {
1252 update_single_frame = false;
1253 sky_mode = RS::SKY_MODE_INCREMENTAL;
1254 } else {
1255 update_single_frame = true;
1256 sky_mode = RS::SKY_MODE_QUALITY;
1257 }
1258 }
1259
1260 if (sky->processing_layer == 0 && sky_mode == RS::SKY_MODE_INCREMENTAL) {
1261 // On the first frame after creating sky, rebuild in single frame
1262 update_single_frame = true;
1263 sky_mode = RS::SKY_MODE_QUALITY;
1264 }
1265
1266 int max_processing_layer = sky_use_cubemap_array ? sky->reflection.layers.size() : sky->reflection.layers[0].mipmaps.size();
1267
1268 // Update radiance cubemap
1269 if (sky->reflection.dirty && (sky->processing_layer >= max_processing_layer || update_single_frame)) {
1270 static const Vector3 view_normals[6] = {
1271 Vector3(+1, 0, 0),
1272 Vector3(-1, 0, 0),
1273 Vector3(0, +1, 0),
1274 Vector3(0, -1, 0),
1275 Vector3(0, 0, +1),
1276 Vector3(0, 0, -1)
1277 };
1278 static const Vector3 view_up[6] = {
1279 Vector3(0, -1, 0),
1280 Vector3(0, -1, 0),
1281 Vector3(0, 0, +1),
1282 Vector3(0, 0, -1),
1283 Vector3(0, -1, 0),
1284 Vector3(0, -1, 0)
1285 };
1286
1287 Projection cm;
1288 cm.set_perspective(90, 1, 0.01, 10.0);
1289 Projection correction;
1290 correction.set_depth_correction(true);
1291 cm = correction * cm;
1292
1293 // Note, we ignore environment_get_sky_orientation here as this is applied when we do our lookup in our scene shader.
1294
1295 if (shader_data->uses_quarter_res && roughness_layers >= 3) {
1296 RD::get_singleton()->draw_command_begin_label("Render Sky to Quarter Res Cubemap");
1297 PipelineCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP_QUARTER_RES];
1298
1299 Vector<Color> clear_colors;
1300 clear_colors.push_back(Color(0.0, 0.0, 0.0));
1301 RD::DrawListID cubemap_draw_list;
1302
1303 for (int i = 0; i < 6; i++) {
1304 Basis local_view = Basis::looking_at(view_normals[i], view_up[i]);
1305 RID texture_uniform_set = sky->get_textures(SKY_TEXTURE_SET_CUBEMAP_QUARTER_RES, sky_shader.default_shader_rd, p_render_buffers);
1306
1307 cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[2].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
1308 _render_sky(cubemap_draw_list, p_time, sky->reflection.layers[0].mipmaps[2].framebuffers[i], pipeline, material->uniform_set, texture_uniform_set, cm, local_view, p_global_pos, p_luminance_multiplier);
1309 RD::get_singleton()->draw_list_end();
1310 }
1311 RD::get_singleton()->draw_command_end_label();
1312 } else if (shader_data->uses_quarter_res && roughness_layers < 3) {
1313 ERR_PRINT_ED("Cannot use quarter res buffer in sky shader when roughness layers is less than 3. Please increase rendering/reflections/sky_reflections/roughness_layers.");
1314 }
1315
1316 if (shader_data->uses_half_res && roughness_layers >= 2) {
1317 RD::get_singleton()->draw_command_begin_label("Render Sky to Half Res Cubemap");
1318 PipelineCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP_HALF_RES];
1319
1320 Vector<Color> clear_colors;
1321 clear_colors.push_back(Color(0.0, 0.0, 0.0));
1322 RD::DrawListID cubemap_draw_list;
1323
1324 for (int i = 0; i < 6; i++) {
1325 Basis local_view = Basis::looking_at(view_normals[i], view_up[i]);
1326 RID texture_uniform_set = sky->get_textures(SKY_TEXTURE_SET_CUBEMAP_HALF_RES, sky_shader.default_shader_rd, p_render_buffers);
1327
1328 cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[1].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
1329 _render_sky(cubemap_draw_list, p_time, sky->reflection.layers[0].mipmaps[1].framebuffers[i], pipeline, material->uniform_set, texture_uniform_set, cm, local_view, p_global_pos, p_luminance_multiplier);
1330 RD::get_singleton()->draw_list_end();
1331 }
1332 RD::get_singleton()->draw_command_end_label();
1333 } else if (shader_data->uses_half_res && roughness_layers < 2) {
1334 ERR_PRINT_ED("Cannot use half res buffer in sky shader when roughness layers is less than 2. Please increase rendering/reflections/sky_reflections/roughness_layers.");
1335 }
1336
1337 RD::DrawListID cubemap_draw_list;
1338 PipelineCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP];
1339
1340 RD::get_singleton()->draw_command_begin_label("Render Sky Cubemap");
1341 for (int i = 0; i < 6; i++) {
1342 Basis local_view = Basis::looking_at(view_normals[i], view_up[i]);
1343 RID texture_uniform_set = sky->get_textures(SKY_TEXTURE_SET_CUBEMAP, sky_shader.default_shader_rd, p_render_buffers);
1344
1345 cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[0].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
1346 _render_sky(cubemap_draw_list, p_time, sky->reflection.layers[0].mipmaps[0].framebuffers[i], pipeline, material->uniform_set, texture_uniform_set, cm, local_view, p_global_pos, p_luminance_multiplier);
1347 RD::get_singleton()->draw_list_end();
1348 }
1349 RD::get_singleton()->draw_command_end_label();
1350
1351 if (sky_mode == RS::SKY_MODE_REALTIME) {
1352 sky->reflection.create_reflection_fast_filter(sky_use_cubemap_array);
1353 if (sky_use_cubemap_array) {
1354 sky->reflection.update_reflection_mipmaps(0, sky->reflection.layers.size());
1355 }
1356 } else {
1357 if (update_single_frame) {
1358 for (int i = 1; i < max_processing_layer; i++) {
1359 sky->reflection.create_reflection_importance_sample(sky_use_cubemap_array, 10, i, sky_ggx_samples_quality);
1360 }
1361 if (sky_use_cubemap_array) {
1362 sky->reflection.update_reflection_mipmaps(0, sky->reflection.layers.size());
1363 }
1364 } else {
1365 if (sky_use_cubemap_array) {
1366 // Multi-Frame so just update the first array level
1367 sky->reflection.update_reflection_mipmaps(0, 1);
1368 }
1369 }
1370 sky->processing_layer = 1;
1371 }
1372 sky->baked_exposure = p_luminance_multiplier;
1373 sky->reflection.dirty = false;
1374
1375 } else {
1376 if (sky_mode == RS::SKY_MODE_INCREMENTAL && sky->processing_layer < max_processing_layer) {
1377 sky->reflection.create_reflection_importance_sample(sky_use_cubemap_array, 10, sky->processing_layer, sky_ggx_samples_quality);
1378
1379 if (sky_use_cubemap_array) {
1380 sky->reflection.update_reflection_mipmaps(sky->processing_layer, sky->processing_layer + 1);
1381 }
1382
1383 sky->processing_layer++;
1384 }
1385 }
1386}
1387
1388void SkyRD::update_res_buffers(Ref<RenderSceneBuffersRD> p_render_buffers, RID p_env, double p_time, float p_luminance_multiplier) {
1389 ERR_FAIL_COND(p_render_buffers.is_null());
1390 RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
1391 ERR_FAIL_COND(p_env.is_null());
1392
1393 Sky *sky = get_sky(RendererSceneRenderRD::get_singleton()->environment_get_sky(p_env));
1394
1395 SkyMaterialData *material = nullptr;
1396 RID sky_material;
1397
1398 RS::EnvironmentBG background = RendererSceneRenderRD::get_singleton()->environment_get_background(p_env);
1399
1400 if (!(background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) || sky) {
1401 ERR_FAIL_COND(!sky);
1402 sky_material = sky_get_material(RendererSceneRenderRD::get_singleton()->environment_get_sky(p_env));
1403
1404 if (sky_material.is_valid()) {
1405 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
1406 if (!material || !material->shader_data->valid) {
1407 material = nullptr;
1408 }
1409 }
1410
1411 if (!material) {
1412 sky_material = sky_shader.default_material;
1413 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
1414 }
1415 }
1416
1417 if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
1418 sky_material = sky_scene_state.fog_material;
1419 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
1420 }
1421
1422 ERR_FAIL_COND(!material);
1423
1424 SkyShaderData *shader_data = material->shader_data;
1425 ERR_FAIL_COND(!shader_data);
1426
1427 if (!shader_data->uses_quarter_res && !shader_data->uses_half_res) {
1428 return;
1429 }
1430
1431 material->set_as_used();
1432
1433 RENDER_TIMESTAMP("Setup Sky Resolution Buffers");
1434 RD::get_singleton()->draw_command_begin_label("Setup Sky Resolution Buffers");
1435
1436 Basis sky_transform = RendererSceneRenderRD::get_singleton()->environment_get_sky_orientation(p_env);
1437 sky_transform.invert();
1438
1439 float custom_fov = RendererSceneRenderRD::get_singleton()->environment_get_sky_custom_fov(p_env);
1440
1441 // Camera
1442 Projection projection = sky_scene_state.cam_projection;
1443
1444 if (custom_fov && sky_scene_state.view_count == 1) {
1445 // With custom fov we don't support stereo...
1446 float near_plane = projection.get_z_near();
1447 float far_plane = projection.get_z_far();
1448 float aspect = projection.get_aspect();
1449
1450 projection.set_perspective(custom_fov, aspect, near_plane, far_plane);
1451 }
1452
1453 sky_transform = sky_transform * sky_scene_state.cam_transform.basis;
1454
1455 if (shader_data->uses_quarter_res) {
1456 PipelineCacheRD *pipeline = &shader_data->pipelines[sky_scene_state.view_count > 1 ? SKY_VERSION_QUARTER_RES_MULTIVIEW : SKY_VERSION_QUARTER_RES];
1457
1458 // Grab texture and framebuffer from cache, create if needed...
1459 uint32_t usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
1460 Size2i quarter_size = sky->screen_size / 4;
1461 RID texture = p_render_buffers->create_texture(RB_SCOPE_SKY, RB_QUARTER_TEXTURE, texture_format, usage_bits, RD::TEXTURE_SAMPLES_1, quarter_size);
1462 RID framebuffer = FramebufferCacheRD::get_singleton()->get_cache_multiview(sky_scene_state.view_count, texture);
1463
1464 RID texture_uniform_set = sky->get_textures(SKY_TEXTURE_SET_QUARTER_RES, sky_shader.default_shader_rd, p_render_buffers);
1465
1466 Vector<Color> clear_colors;
1467 clear_colors.push_back(Color(0.0, 0.0, 0.0));
1468
1469 RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(framebuffer, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
1470 _render_sky(draw_list, p_time, framebuffer, pipeline, material->uniform_set, texture_uniform_set, projection, sky_transform, sky_scene_state.cam_transform.origin, p_luminance_multiplier);
1471 RD::get_singleton()->draw_list_end();
1472 }
1473
1474 if (shader_data->uses_half_res) {
1475 PipelineCacheRD *pipeline = &shader_data->pipelines[sky_scene_state.view_count > 1 ? SKY_VERSION_HALF_RES_MULTIVIEW : SKY_VERSION_HALF_RES];
1476
1477 // Grab texture and framebuffer from cache, create if needed...
1478 uint32_t usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
1479 Size2i half_size = sky->screen_size / 2;
1480 RID texture = p_render_buffers->create_texture(RB_SCOPE_SKY, RB_HALF_TEXTURE, texture_format, usage_bits, RD::TEXTURE_SAMPLES_1, half_size);
1481 RID framebuffer = FramebufferCacheRD::get_singleton()->get_cache_multiview(sky_scene_state.view_count, texture);
1482
1483 RID texture_uniform_set = sky->get_textures(SKY_TEXTURE_SET_HALF_RES, sky_shader.default_shader_rd, p_render_buffers);
1484
1485 Vector<Color> clear_colors;
1486 clear_colors.push_back(Color(0.0, 0.0, 0.0));
1487
1488 RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(framebuffer, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
1489 _render_sky(draw_list, p_time, framebuffer, pipeline, material->uniform_set, texture_uniform_set, projection, sky_transform, sky_scene_state.cam_transform.origin, p_luminance_multiplier);
1490 RD::get_singleton()->draw_list_end();
1491 }
1492
1493 RD::get_singleton()->draw_command_end_label(); // Setup Sky resolution buffers
1494}
1495
1496void SkyRD::draw_sky(RD::DrawListID p_draw_list, Ref<RenderSceneBuffersRD> p_render_buffers, RID p_env, RID p_fb, double p_time, float p_luminance_multiplier) {
1497 ERR_FAIL_COND(p_render_buffers.is_null());
1498 RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
1499 ERR_FAIL_COND(p_env.is_null());
1500
1501 Sky *sky = get_sky(RendererSceneRenderRD::get_singleton()->environment_get_sky(p_env));
1502
1503 SkyMaterialData *material = nullptr;
1504 RID sky_material;
1505
1506 RS::EnvironmentBG background = RendererSceneRenderRD::get_singleton()->environment_get_background(p_env);
1507
1508 if (!(background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) || sky) {
1509 ERR_FAIL_COND(!sky);
1510 sky_material = sky_get_material(RendererSceneRenderRD::get_singleton()->environment_get_sky(p_env));
1511
1512 if (sky_material.is_valid()) {
1513 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
1514 if (!material || !material->shader_data->valid) {
1515 material = nullptr;
1516 }
1517 }
1518
1519 if (!material) {
1520 sky_material = sky_shader.default_material;
1521 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
1522 }
1523 }
1524
1525 if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
1526 sky_material = sky_scene_state.fog_material;
1527 material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::MaterialStorage::SHADER_TYPE_SKY));
1528 }
1529
1530 ERR_FAIL_COND(!material);
1531
1532 SkyShaderData *shader_data = material->shader_data;
1533 ERR_FAIL_COND(!shader_data);
1534
1535 material->set_as_used();
1536
1537 Basis sky_transform = RendererSceneRenderRD::get_singleton()->environment_get_sky_orientation(p_env);
1538 sky_transform.invert();
1539
1540 float custom_fov = RendererSceneRenderRD::get_singleton()->environment_get_sky_custom_fov(p_env);
1541
1542 // Camera
1543 Projection projection = sky_scene_state.cam_projection;
1544
1545 if (custom_fov && sky_scene_state.view_count == 1) {
1546 // With custom fov we don't support stereo...
1547 float near_plane = projection.get_z_near();
1548 float far_plane = projection.get_z_far();
1549 float aspect = projection.get_aspect();
1550
1551 projection.set_perspective(custom_fov, aspect, near_plane, far_plane);
1552 }
1553
1554 sky_transform = sky_transform * sky_scene_state.cam_transform.basis;
1555
1556 PipelineCacheRD *pipeline = &shader_data->pipelines[sky_scene_state.view_count > 1 ? SKY_VERSION_BACKGROUND_MULTIVIEW : SKY_VERSION_BACKGROUND];
1557
1558 RID texture_uniform_set;
1559 if (sky) {
1560 texture_uniform_set = sky->get_textures(SKY_TEXTURE_SET_BACKGROUND, sky_shader.default_shader_rd, p_render_buffers);
1561 } else {
1562 texture_uniform_set = sky_scene_state.fog_only_texture_uniform_set;
1563 }
1564
1565 _render_sky(p_draw_list, p_time, p_fb, pipeline, material->uniform_set, texture_uniform_set, projection, sky_transform, sky_scene_state.cam_transform.origin, p_luminance_multiplier);
1566}
1567
1568void SkyRD::invalidate_sky(Sky *p_sky) {
1569 if (!p_sky->dirty) {
1570 p_sky->dirty = true;
1571 p_sky->dirty_list = dirty_sky_list;
1572 dirty_sky_list = p_sky;
1573 }
1574}
1575
1576void SkyRD::update_dirty_skys() {
1577 Sky *sky = dirty_sky_list;
1578
1579 while (sky) {
1580 //update sky configuration if texture is missing
1581
1582 // TODO See if we can move this into `update_radiance_buffers` and remove our dirty_sky logic.
1583 // As this is basically a duplicate of the logic in reflection probes we could move this logic
1584 // into RenderSceneBuffersRD and use that from both places.
1585 if (sky->radiance.is_null()) {
1586 int mipmaps = Image::get_image_required_mipmaps(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBAH) + 1;
1587
1588 uint32_t w = sky->radiance_size, h = sky->radiance_size;
1589 int layers = roughness_layers;
1590 if (sky->mode == RS::SKY_MODE_REALTIME) {
1591 layers = 8;
1592 if (roughness_layers != 8) {
1593 WARN_PRINT("When using the Real-Time sky update mode (or Automatic with a sky shader using \"TIME\"), \"rendering/reflections/sky_reflections/roughness_layers\" should be set to 8 in the project settings for best quality reflections.");
1594 }
1595 }
1596
1597 if (sky_use_cubemap_array) {
1598 //array (higher quality, 6 times more memory)
1599 RD::TextureFormat tf;
1600 tf.array_layers = layers * 6;
1601 tf.format = texture_format;
1602 tf.texture_type = RD::TEXTURE_TYPE_CUBE_ARRAY;
1603 tf.mipmaps = mipmaps;
1604 tf.width = w;
1605 tf.height = h;
1606 tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
1607 if (RendererSceneRenderRD::get_singleton()->_render_buffers_can_be_storage()) {
1608 tf.usage_bits |= RD::TEXTURE_USAGE_STORAGE_BIT;
1609 }
1610
1611 sky->radiance = RD::get_singleton()->texture_create(tf, RD::TextureView());
1612
1613 sky->reflection.update_reflection_data(sky->radiance_size, mipmaps, true, sky->radiance, 0, sky->mode == RS::SKY_MODE_REALTIME, roughness_layers, texture_format);
1614
1615 } else {
1616 //regular cubemap, lower quality (aliasing, less memory)
1617 RD::TextureFormat tf;
1618 tf.array_layers = 6;
1619 tf.format = texture_format;
1620 tf.texture_type = RD::TEXTURE_TYPE_CUBE;
1621 tf.mipmaps = MIN(mipmaps, layers);
1622 tf.width = w;
1623 tf.height = h;
1624 tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
1625 if (RendererSceneRenderRD::get_singleton()->_render_buffers_can_be_storage()) {
1626 tf.usage_bits |= RD::TEXTURE_USAGE_STORAGE_BIT;
1627 }
1628
1629 sky->radiance = RD::get_singleton()->texture_create(tf, RD::TextureView());
1630
1631 sky->reflection.update_reflection_data(sky->radiance_size, MIN(mipmaps, layers), false, sky->radiance, 0, sky->mode == RS::SKY_MODE_REALTIME, roughness_layers, texture_format);
1632 }
1633 }
1634
1635 sky->reflection.dirty = true;
1636 sky->processing_layer = 0;
1637
1638 Sky *next = sky->dirty_list;
1639 sky->dirty_list = nullptr;
1640 sky->dirty = false;
1641 sky = next;
1642 }
1643
1644 dirty_sky_list = nullptr;
1645}
1646
1647RID SkyRD::sky_get_material(RID p_sky) const {
1648 Sky *sky = get_sky(p_sky);
1649 ERR_FAIL_COND_V(!sky, RID());
1650
1651 return sky->material;
1652}
1653
1654float SkyRD::sky_get_baked_exposure(RID p_sky) const {
1655 Sky *sky = get_sky(p_sky);
1656 ERR_FAIL_COND_V(!sky, 1.0);
1657
1658 return sky->baked_exposure;
1659}
1660
1661RID SkyRD::allocate_sky_rid() {
1662 return sky_owner.allocate_rid();
1663}
1664
1665void SkyRD::initialize_sky_rid(RID p_rid) {
1666 sky_owner.initialize_rid(p_rid, Sky());
1667}
1668
1669SkyRD::Sky *SkyRD::get_sky(RID p_sky) const {
1670 return sky_owner.get_or_null(p_sky);
1671}
1672
1673void SkyRD::free_sky(RID p_sky) {
1674 Sky *sky = get_sky(p_sky);
1675 ERR_FAIL_COND(!sky);
1676
1677 sky->free();
1678 sky_owner.free(p_sky);
1679}
1680
1681void SkyRD::sky_set_radiance_size(RID p_sky, int p_radiance_size) {
1682 Sky *sky = get_sky(p_sky);
1683 ERR_FAIL_COND(!sky);
1684
1685 if (sky->set_radiance_size(p_radiance_size)) {
1686 invalidate_sky(sky);
1687 }
1688}
1689
1690void SkyRD::sky_set_mode(RID p_sky, RS::SkyMode p_mode) {
1691 Sky *sky = get_sky(p_sky);
1692 ERR_FAIL_COND(!sky);
1693
1694 if (sky->set_mode(p_mode)) {
1695 invalidate_sky(sky);
1696 }
1697}
1698
1699void SkyRD::sky_set_material(RID p_sky, RID p_material) {
1700 Sky *sky = get_sky(p_sky);
1701 ERR_FAIL_COND(!sky);
1702
1703 if (sky->set_material(p_material)) {
1704 invalidate_sky(sky);
1705 }
1706}
1707
1708Ref<Image> SkyRD::sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) {
1709 Sky *sky = get_sky(p_sky);
1710 ERR_FAIL_COND_V(!sky, Ref<Image>());
1711
1712 update_dirty_skys();
1713
1714 return sky->bake_panorama(p_energy, p_bake_irradiance ? roughness_layers : 0, p_size);
1715}
1716
1717RID SkyRD::sky_get_radiance_texture_rd(RID p_sky) const {
1718 Sky *sky = get_sky(p_sky);
1719 ERR_FAIL_COND_V(!sky, RID());
1720
1721 return sky->radiance;
1722}
1723