sky.cpp 79 KB

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