lightmapper_rd.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426
  1. /**************************************************************************/
  2. /* lightmapper_rd.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "lightmapper_rd.h"
  31. #include "core/string/print_string.h"
  32. #include "lm_blendseams.glsl.gen.h"
  33. #include "lm_compute.glsl.gen.h"
  34. #include "lm_raster.glsl.gen.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/io/dir_access.h"
  37. #include "core/math/geometry_2d.h"
  38. #include "editor/editor_paths.h"
  39. #include "editor/editor_settings.h"
  40. #include "servers/rendering/rendering_device_binds.h"
  41. #include "servers/rendering/rendering_server_globals.h"
  42. #if defined(VULKAN_ENABLED)
  43. #include "drivers/vulkan/rendering_context_driver_vulkan.h"
  44. #endif
  45. #if defined(METAL_ENABLED)
  46. #include "drivers/metal/rendering_context_driver_metal.h"
  47. #endif
  48. //uncomment this if you want to see textures from all the process saved
  49. //#define DEBUG_TEXTURES
  50. void LightmapperRD::add_mesh(const MeshData &p_mesh) {
  51. ERR_FAIL_COND(p_mesh.albedo_on_uv2.is_null() || p_mesh.albedo_on_uv2->is_empty());
  52. ERR_FAIL_COND(p_mesh.emission_on_uv2.is_null() || p_mesh.emission_on_uv2->is_empty());
  53. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_width() != p_mesh.emission_on_uv2->get_width());
  54. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_height() != p_mesh.emission_on_uv2->get_height());
  55. ERR_FAIL_COND(p_mesh.points.is_empty());
  56. MeshInstance mi;
  57. mi.data = p_mesh;
  58. mesh_instances.push_back(mi);
  59. }
  60. void LightmapperRD::add_directional_light(const String &p_name, bool p_static, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_angular_distance, float p_shadow_blur) {
  61. Light l;
  62. l.type = LIGHT_TYPE_DIRECTIONAL;
  63. l.direction[0] = p_direction.x;
  64. l.direction[1] = p_direction.y;
  65. l.direction[2] = p_direction.z;
  66. l.color[0] = p_color.r;
  67. l.color[1] = p_color.g;
  68. l.color[2] = p_color.b;
  69. l.energy = p_energy;
  70. l.indirect_energy = p_indirect_energy;
  71. l.static_bake = p_static;
  72. l.size = Math::tan(Math::deg_to_rad(p_angular_distance));
  73. l.shadow_blur = p_shadow_blur;
  74. lights.push_back(l);
  75. LightMetadata md;
  76. md.name = p_name;
  77. md.type = LIGHT_TYPE_DIRECTIONAL;
  78. light_metadata.push_back(md);
  79. }
  80. void LightmapperRD::add_omni_light(const String &p_name, bool p_static, const Vector3 &p_position, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_size, float p_shadow_blur) {
  81. Light l;
  82. l.type = LIGHT_TYPE_OMNI;
  83. l.position[0] = p_position.x;
  84. l.position[1] = p_position.y;
  85. l.position[2] = p_position.z;
  86. l.range = p_range;
  87. l.attenuation = p_attenuation;
  88. l.color[0] = p_color.r;
  89. l.color[1] = p_color.g;
  90. l.color[2] = p_color.b;
  91. l.energy = p_energy;
  92. l.indirect_energy = p_indirect_energy;
  93. l.static_bake = p_static;
  94. l.size = p_size;
  95. l.shadow_blur = p_shadow_blur;
  96. lights.push_back(l);
  97. LightMetadata md;
  98. md.name = p_name;
  99. md.type = LIGHT_TYPE_OMNI;
  100. light_metadata.push_back(md);
  101. }
  102. void LightmapperRD::add_spot_light(const String &p_name, bool p_static, const Vector3 &p_position, const Vector3 p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size, float p_shadow_blur) {
  103. Light l;
  104. l.type = LIGHT_TYPE_SPOT;
  105. l.position[0] = p_position.x;
  106. l.position[1] = p_position.y;
  107. l.position[2] = p_position.z;
  108. l.direction[0] = p_direction.x;
  109. l.direction[1] = p_direction.y;
  110. l.direction[2] = p_direction.z;
  111. l.range = p_range;
  112. l.attenuation = p_attenuation;
  113. l.cos_spot_angle = Math::cos(Math::deg_to_rad(p_spot_angle));
  114. l.inv_spot_attenuation = 1.0f / p_spot_attenuation;
  115. l.color[0] = p_color.r;
  116. l.color[1] = p_color.g;
  117. l.color[2] = p_color.b;
  118. l.energy = p_energy;
  119. l.indirect_energy = p_indirect_energy;
  120. l.static_bake = p_static;
  121. l.size = p_size;
  122. l.shadow_blur = p_shadow_blur;
  123. lights.push_back(l);
  124. LightMetadata md;
  125. md.name = p_name;
  126. md.type = LIGHT_TYPE_SPOT;
  127. light_metadata.push_back(md);
  128. }
  129. void LightmapperRD::add_probe(const Vector3 &p_position) {
  130. Probe probe;
  131. probe.position[0] = p_position.x;
  132. probe.position[1] = p_position.y;
  133. probe.position[2] = p_position.z;
  134. probe.position[3] = 0;
  135. probe_positions.push_back(probe);
  136. }
  137. void LightmapperRD::_plot_triangle_into_triangle_index_list(int p_size, const Vector3i &p_ofs, const AABB &p_bounds, const Vector3 p_points[3], uint32_t p_triangle_index, LocalVector<TriangleSort> &p_triangles_sort, uint32_t p_grid_size) {
  138. int half_size = p_size / 2;
  139. for (int i = 0; i < 8; i++) {
  140. AABB aabb = p_bounds;
  141. aabb.size *= 0.5;
  142. Vector3i n = p_ofs;
  143. if (i & 1) {
  144. aabb.position.x += aabb.size.x;
  145. n.x += half_size;
  146. }
  147. if (i & 2) {
  148. aabb.position.y += aabb.size.y;
  149. n.y += half_size;
  150. }
  151. if (i & 4) {
  152. aabb.position.z += aabb.size.z;
  153. n.z += half_size;
  154. }
  155. {
  156. Vector3 qsize = aabb.size * 0.5; //quarter size, for fast aabb test
  157. if (!Geometry3D::triangle_box_overlap(aabb.position + qsize, qsize, p_points)) {
  158. //does not fit in child, go on
  159. continue;
  160. }
  161. }
  162. if (half_size == 1) {
  163. //got to the end
  164. TriangleSort ts;
  165. ts.cell_index = n.x + (n.y * p_grid_size) + (n.z * p_grid_size * p_grid_size);
  166. ts.triangle_index = p_triangle_index;
  167. ts.triangle_aabb.position = p_points[0];
  168. ts.triangle_aabb.size = Vector3();
  169. ts.triangle_aabb.expand_to(p_points[1]);
  170. ts.triangle_aabb.expand_to(p_points[2]);
  171. p_triangles_sort.push_back(ts);
  172. } else {
  173. _plot_triangle_into_triangle_index_list(half_size, n, aabb, p_points, p_triangle_index, p_triangles_sort, p_grid_size);
  174. }
  175. }
  176. }
  177. void LightmapperRD::_sort_triangle_clusters(uint32_t p_cluster_size, uint32_t p_cluster_index, uint32_t p_index_start, uint32_t p_count, LocalVector<TriangleSort> &p_triangle_sort, LocalVector<ClusterAABB> &p_cluster_aabb) {
  178. if (p_count == 0) {
  179. return;
  180. }
  181. // Compute AABB for all triangles in the range.
  182. SortArray<TriangleSort, TriangleSortAxis<0>> triangle_sorter_x;
  183. SortArray<TriangleSort, TriangleSortAxis<1>> triangle_sorter_y;
  184. SortArray<TriangleSort, TriangleSortAxis<2>> triangle_sorter_z;
  185. AABB cluster_aabb = p_triangle_sort[p_index_start].triangle_aabb;
  186. for (uint32_t i = 1; i < p_count; i++) {
  187. cluster_aabb.merge_with(p_triangle_sort[p_index_start + i].triangle_aabb);
  188. }
  189. if (p_count > p_cluster_size) {
  190. int longest_axis_index = cluster_aabb.get_longest_axis_index();
  191. switch (longest_axis_index) {
  192. case 0:
  193. triangle_sorter_x.sort(&p_triangle_sort[p_index_start], p_count);
  194. break;
  195. case 1:
  196. triangle_sorter_y.sort(&p_triangle_sort[p_index_start], p_count);
  197. break;
  198. case 2:
  199. triangle_sorter_z.sort(&p_triangle_sort[p_index_start], p_count);
  200. break;
  201. default:
  202. DEV_ASSERT(false && "Invalid axis returned by AABB.");
  203. break;
  204. }
  205. uint32_t left_cluster_count = next_power_of_2(p_count / 2);
  206. left_cluster_count = MAX(left_cluster_count, p_cluster_size);
  207. left_cluster_count = MIN(left_cluster_count, p_count);
  208. _sort_triangle_clusters(p_cluster_size, p_cluster_index, p_index_start, left_cluster_count, p_triangle_sort, p_cluster_aabb);
  209. if (left_cluster_count < p_count) {
  210. uint32_t cluster_index_right = p_cluster_index + (left_cluster_count / p_cluster_size);
  211. _sort_triangle_clusters(p_cluster_size, cluster_index_right, p_index_start + left_cluster_count, p_count - left_cluster_count, p_triangle_sort, p_cluster_aabb);
  212. }
  213. } else {
  214. ClusterAABB &aabb = p_cluster_aabb[p_cluster_index];
  215. Vector3 aabb_end = cluster_aabb.get_end();
  216. aabb.min_bounds[0] = cluster_aabb.position.x;
  217. aabb.min_bounds[1] = cluster_aabb.position.y;
  218. aabb.min_bounds[2] = cluster_aabb.position.z;
  219. aabb.max_bounds[0] = aabb_end.x;
  220. aabb.max_bounds[1] = aabb_end.y;
  221. aabb.max_bounds[2] = aabb_end.z;
  222. }
  223. }
  224. Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_size, int p_denoiser_range, Vector<Ref<Image>> &albedo_images, Vector<Ref<Image>> &emission_images, AABB &bounds, Size2i &atlas_size, int &atlas_slices, float p_supersampling_factor, BakeStepFunc p_step_function, void *p_bake_userdata) {
  225. Vector<Size2i> sizes;
  226. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  227. MeshInstance &mi = mesh_instances.write[m_i];
  228. Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height());
  229. sizes.push_back(s);
  230. atlas_size = atlas_size.max(s + Size2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor);
  231. }
  232. int max = nearest_power_of_2_templated(atlas_size.width);
  233. max = MAX(max, nearest_power_of_2_templated(atlas_size.height));
  234. if (max > p_max_texture_size) {
  235. return BAKE_ERROR_TEXTURE_EXCEEDS_MAX_SIZE;
  236. }
  237. if (p_step_function) {
  238. if (p_step_function(0.1, RTR("Determining optimal atlas size"), p_bake_userdata, true)) {
  239. return BAKE_ERROR_USER_ABORTED;
  240. }
  241. }
  242. atlas_size = Size2i(max, max);
  243. Size2i best_atlas_size;
  244. int best_atlas_slices = 0;
  245. int best_atlas_memory = 0x7FFFFFFF;
  246. Vector<Vector3i> best_atlas_offsets;
  247. // Determine best texture array atlas size by bruteforce fitting.
  248. while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) {
  249. Vector<Vector2i> source_sizes;
  250. Vector<int> source_indices;
  251. source_sizes.resize(sizes.size());
  252. source_indices.resize(sizes.size());
  253. for (int i = 0; i < source_indices.size(); i++) {
  254. // Add padding between lightmaps.
  255. // Scale the padding if the lightmap will be downsampled at the end of the baking process
  256. // Otherwise the padding would be insufficient.
  257. source_sizes.write[i] = sizes[i] + Vector2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor;
  258. source_indices.write[i] = i;
  259. }
  260. Vector<Vector3i> atlas_offsets;
  261. atlas_offsets.resize(source_sizes.size());
  262. // Ensure the sizes can all fit into a single atlas layer.
  263. // This should always happen, and this check is only in place to prevent an infinite loop.
  264. for (int i = 0; i < source_sizes.size(); i++) {
  265. if (source_sizes[i] > atlas_size) {
  266. return BAKE_ERROR_ATLAS_TOO_SMALL;
  267. }
  268. }
  269. int slices = 0;
  270. while (source_sizes.size() > 0) {
  271. Vector<Vector3i> offsets = Geometry2D::partial_pack_rects(source_sizes, atlas_size);
  272. Vector<int> new_indices;
  273. Vector<Vector2i> new_sources;
  274. for (int i = 0; i < offsets.size(); i++) {
  275. Vector3i ofs = offsets[i];
  276. int sidx = source_indices[i];
  277. if (ofs.z > 0) {
  278. //valid
  279. ofs.z = slices;
  280. atlas_offsets.write[sidx] = ofs + Vector3i(1, 1, 0); // Center lightmap in the reserved oversized region
  281. } else {
  282. new_indices.push_back(sidx);
  283. new_sources.push_back(source_sizes[i]);
  284. }
  285. }
  286. source_sizes = new_sources;
  287. source_indices = new_indices;
  288. slices++;
  289. }
  290. int mem_used = atlas_size.x * atlas_size.y * slices;
  291. if (mem_used < best_atlas_memory) {
  292. best_atlas_size = atlas_size;
  293. best_atlas_offsets = atlas_offsets;
  294. best_atlas_slices = slices;
  295. best_atlas_memory = mem_used;
  296. }
  297. if (atlas_size.width == atlas_size.height) {
  298. atlas_size.width *= 2;
  299. } else {
  300. atlas_size.height *= 2;
  301. }
  302. }
  303. atlas_size = best_atlas_size;
  304. atlas_slices = best_atlas_slices;
  305. // apply the offsets and slice to all images, and also blit albedo and emission
  306. albedo_images.resize(atlas_slices);
  307. emission_images.resize(atlas_slices);
  308. if (p_step_function) {
  309. if (p_step_function(0.2, RTR("Blitting albedo and emission"), p_bake_userdata, true)) {
  310. return BAKE_ERROR_USER_ABORTED;
  311. }
  312. }
  313. for (int i = 0; i < atlas_slices; i++) {
  314. Ref<Image> albedo = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);
  315. albedo->set_as_black();
  316. albedo_images.write[i] = albedo;
  317. Ref<Image> emission = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);
  318. emission->set_as_black();
  319. emission_images.write[i] = emission;
  320. }
  321. //assign uv positions
  322. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  323. MeshInstance &mi = mesh_instances.write[m_i];
  324. mi.offset.x = best_atlas_offsets[m_i].x;
  325. mi.offset.y = best_atlas_offsets[m_i].y;
  326. mi.slice = best_atlas_offsets[m_i].z;
  327. albedo_images.write[mi.slice]->blit_rect(mi.data.albedo_on_uv2, Rect2i(Vector2i(), mi.data.albedo_on_uv2->get_size()), mi.offset);
  328. emission_images.write[mi.slice]->blit_rect(mi.data.emission_on_uv2, Rect2(Vector2i(), mi.data.emission_on_uv2->get_size()), mi.offset);
  329. }
  330. return BAKE_OK;
  331. }
  332. void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, uint32_t p_cluster_size, Vector<Probe> &p_probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &lights_buffer, RID &r_triangle_indices_buffer, RID &r_cluster_indices_buffer, RID &r_cluster_aabbs_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) {
  333. HashMap<Vertex, uint32_t, VertexHash> vertex_map;
  334. //fill triangles array and vertex array
  335. LocalVector<Triangle> triangles;
  336. LocalVector<Vertex> vertex_array;
  337. LocalVector<Seam> seams;
  338. slice_triangle_count.resize(atlas_slices);
  339. slice_seam_count.resize(atlas_slices);
  340. for (int i = 0; i < atlas_slices; i++) {
  341. slice_triangle_count.write[i] = 0;
  342. slice_seam_count.write[i] = 0;
  343. }
  344. bounds = AABB();
  345. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  346. if (p_step_function) {
  347. float p = float(m_i + 1) / MAX(1, mesh_instances.size()) * 0.1;
  348. p_step_function(0.3 + p, vformat(RTR("Plotting mesh into acceleration structure %d/%d"), m_i + 1, mesh_instances.size()), p_bake_userdata, false);
  349. }
  350. HashMap<Edge, EdgeUV2, EdgeHash> edges;
  351. MeshInstance &mi = mesh_instances.write[m_i];
  352. Vector2 uv_scale = Vector2(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()) / Vector2(atlas_size);
  353. Vector2 uv_offset = Vector2(mi.offset) / Vector2(atlas_size);
  354. if (m_i == 0) {
  355. bounds.position = mi.data.points[0];
  356. }
  357. for (int i = 0; i < mi.data.points.size(); i += 3) {
  358. Vector3 vtxs[3] = { mi.data.points[i + 0], mi.data.points[i + 1], mi.data.points[i + 2] };
  359. Vector2 uvs[3] = { mi.data.uv2[i + 0] * uv_scale + uv_offset, mi.data.uv2[i + 1] * uv_scale + uv_offset, mi.data.uv2[i + 2] * uv_scale + uv_offset };
  360. Vector3 normal[3] = { mi.data.normal[i + 0], mi.data.normal[i + 1], mi.data.normal[i + 2] };
  361. AABB taabb;
  362. Triangle t;
  363. t.slice = mi.slice;
  364. for (int k = 0; k < 3; k++) {
  365. bounds.expand_to(vtxs[k]);
  366. Vertex v;
  367. v.position[0] = vtxs[k].x;
  368. v.position[1] = vtxs[k].y;
  369. v.position[2] = vtxs[k].z;
  370. v.uv[0] = uvs[k].x;
  371. v.uv[1] = uvs[k].y;
  372. v.normal_xy[0] = normal[k].x;
  373. v.normal_xy[1] = normal[k].y;
  374. v.normal_z = normal[k].z;
  375. uint32_t *indexptr = vertex_map.getptr(v);
  376. if (indexptr) {
  377. t.indices[k] = *indexptr;
  378. } else {
  379. uint32_t new_index = vertex_map.size();
  380. t.indices[k] = new_index;
  381. vertex_map[v] = new_index;
  382. vertex_array.push_back(v);
  383. }
  384. if (k == 0) {
  385. taabb.position = vtxs[k];
  386. } else {
  387. taabb.expand_to(vtxs[k]);
  388. }
  389. }
  390. //compute seams that will need to be blended later
  391. for (int k = 0; k < 3; k++) {
  392. int n = (k + 1) % 3;
  393. Edge edge(vtxs[k], vtxs[n], normal[k], normal[n]);
  394. Vector2i edge_indices(t.indices[k], t.indices[n]);
  395. EdgeUV2 uv2(uvs[k], uvs[n], edge_indices);
  396. if (edge.b == edge.a) {
  397. continue; //degenerate, somehow
  398. }
  399. if (edge.b < edge.a) {
  400. SWAP(edge.a, edge.b);
  401. SWAP(edge.na, edge.nb);
  402. SWAP(uv2.a, uv2.b);
  403. SWAP(uv2.indices.x, uv2.indices.y);
  404. SWAP(edge_indices.x, edge_indices.y);
  405. }
  406. EdgeUV2 *euv2 = edges.getptr(edge);
  407. if (!euv2) {
  408. edges[edge] = uv2;
  409. } else {
  410. if (*euv2 == uv2) {
  411. continue; // seam shared UV space, no need to blend
  412. }
  413. if (euv2->seam_found) {
  414. continue; //bad geometry
  415. }
  416. Seam seam;
  417. seam.a = edge_indices;
  418. seam.b = euv2->indices;
  419. seam.slice = mi.slice;
  420. seams.push_back(seam);
  421. slice_seam_count.write[mi.slice]++;
  422. euv2->seam_found = true;
  423. }
  424. }
  425. t.min_bounds[0] = taabb.position.x;
  426. t.min_bounds[1] = taabb.position.y;
  427. t.min_bounds[2] = taabb.position.z;
  428. t.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);
  429. t.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);
  430. t.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);
  431. t.cull_mode = RS::CULL_MODE_BACK;
  432. RID material = mi.data.material[i];
  433. if (material.is_valid()) {
  434. t.cull_mode = RSG::material_storage->material_get_cull_mode(material);
  435. }
  436. t.pad1 = 0; //make valgrind not complain
  437. triangles.push_back(t);
  438. slice_triangle_count.write[t.slice]++;
  439. }
  440. }
  441. //also consider probe positions for bounds
  442. for (int i = 0; i < p_probe_positions.size(); i++) {
  443. Vector3 pp(p_probe_positions[i].position[0], p_probe_positions[i].position[1], p_probe_positions[i].position[2]);
  444. bounds.expand_to(pp);
  445. }
  446. bounds.grow_by(0.1); //grow a bit to avoid numerical error
  447. triangles.sort(); //sort by slice
  448. seams.sort();
  449. if (p_step_function) {
  450. p_step_function(0.4, RTR("Optimizing acceleration structure"), p_bake_userdata, true);
  451. }
  452. //fill list of triangles in grid
  453. LocalVector<TriangleSort> triangle_sort;
  454. for (uint32_t i = 0; i < triangles.size(); i++) {
  455. const Triangle &t = triangles[i];
  456. Vector3 face[3] = {
  457. Vector3(vertex_array[t.indices[0]].position[0], vertex_array[t.indices[0]].position[1], vertex_array[t.indices[0]].position[2]),
  458. Vector3(vertex_array[t.indices[1]].position[0], vertex_array[t.indices[1]].position[1], vertex_array[t.indices[1]].position[2]),
  459. Vector3(vertex_array[t.indices[2]].position[0], vertex_array[t.indices[2]].position[1], vertex_array[t.indices[2]].position[2])
  460. };
  461. _plot_triangle_into_triangle_index_list(grid_size, Vector3i(), bounds, face, i, triangle_sort, grid_size);
  462. }
  463. //sort it
  464. triangle_sort.sort();
  465. LocalVector<uint32_t> cluster_indices;
  466. LocalVector<ClusterAABB> cluster_aabbs;
  467. Vector<uint32_t> triangle_indices;
  468. triangle_indices.resize(triangle_sort.size());
  469. Vector<uint32_t> grid_indices;
  470. grid_indices.resize(grid_size * grid_size * grid_size * 2);
  471. memset(grid_indices.ptrw(), 0, grid_indices.size() * sizeof(uint32_t));
  472. {
  473. // Fill grid with cell indices.
  474. uint32_t last_cell = 0xFFFFFFFF;
  475. uint32_t *giw = grid_indices.ptrw();
  476. uint32_t cluster_count = 0;
  477. uint32_t solid_cell_count = 0;
  478. for (uint32_t i = 0; i < triangle_sort.size(); i++) {
  479. uint32_t cell = triangle_sort[i].cell_index;
  480. if (cell != last_cell) {
  481. giw[cell * 2 + 1] = solid_cell_count;
  482. solid_cell_count++;
  483. }
  484. if ((giw[cell * 2] % p_cluster_size) == 0) {
  485. // Add an extra cluster every time the triangle counter reaches a multiple of the cluster size.
  486. cluster_count++;
  487. }
  488. giw[cell * 2]++;
  489. last_cell = cell;
  490. }
  491. // Build fixed-size triangle clusters for all the cells to speed up the traversal. A cell can hold multiple clusters that each contain a fixed
  492. // amount of triangles and an AABB. The tracer will check against the AABBs first to know whether it needs to visit the cell's triangles.
  493. //
  494. // The building algorithm will divide the triangles recursively contained inside each cell, sorting by the longest axis of the AABB on each step.
  495. //
  496. // - If the amount of triangles is less or equal to the cluster size, the AABB will be stored and the algorithm stops.
  497. //
  498. // - The division by two is increased to the next power of two of half the amount of triangles (with cluster size as the minimum value) to
  499. // ensure the first half always fills the cluster.
  500. cluster_indices.resize(solid_cell_count * 2);
  501. cluster_aabbs.resize(cluster_count);
  502. uint32_t i = 0;
  503. uint32_t cluster_index = 0;
  504. uint32_t solid_cell_index = 0;
  505. uint32_t *tiw = triangle_indices.ptrw();
  506. while (i < triangle_sort.size()) {
  507. cluster_indices[solid_cell_index * 2] = cluster_index;
  508. cluster_indices[solid_cell_index * 2 + 1] = i;
  509. uint32_t cell = triangle_sort[i].cell_index;
  510. uint32_t triangle_count = giw[cell * 2];
  511. uint32_t cell_cluster_count = (triangle_count + p_cluster_size - 1) / p_cluster_size;
  512. _sort_triangle_clusters(p_cluster_size, cluster_index, i, triangle_count, triangle_sort, cluster_aabbs);
  513. for (uint32_t j = 0; j < triangle_count; j++) {
  514. tiw[i + j] = triangle_sort[i + j].triangle_index;
  515. }
  516. i += triangle_count;
  517. cluster_index += cell_cluster_count;
  518. solid_cell_index++;
  519. }
  520. }
  521. #if 0
  522. for (int i = 0; i < grid_size; i++) {
  523. for (int j = 0; j < grid_size; j++) {
  524. for (int k = 0; k < grid_size; k++) {
  525. uint32_t index = i * (grid_size * grid_size) + j * grid_size + k;
  526. grid_indices.write[index * 2] = float(i) / grid_size * 255;
  527. grid_indices.write[index * 2 + 1] = float(j) / grid_size * 255;
  528. }
  529. }
  530. }
  531. #endif
  532. #if 0
  533. for (int i = 0; i < grid_size; i++) {
  534. Vector<uint8_t> grid_usage;
  535. grid_usage.resize(grid_size * grid_size);
  536. for (int j = 0; j < grid_usage.size(); j++) {
  537. uint32_t ofs = i * grid_size * grid_size + j;
  538. uint32_t count = grid_indices[ofs * 2];
  539. grid_usage.write[j] = count > 0 ? 255 : 0;
  540. }
  541. Ref<Image> img = Image::create_from_data(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);
  542. img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png");
  543. }
  544. #endif
  545. /*****************************/
  546. /*** CREATE GPU STRUCTURES ***/
  547. /*****************************/
  548. lights.sort();
  549. light_metadata.sort();
  550. Vector<Vector2i> seam_buffer_vec;
  551. seam_buffer_vec.resize(seams.size() * 2);
  552. for (uint32_t i = 0; i < seams.size(); i++) {
  553. seam_buffer_vec.write[i * 2 + 0] = seams[i].a;
  554. seam_buffer_vec.write[i * 2 + 1] = seams[i].b;
  555. }
  556. { //buffers
  557. Vector<uint8_t> vb = vertex_array.to_byte_array();
  558. vertex_buffer = rd->storage_buffer_create(vb.size(), vb);
  559. Vector<uint8_t> tb = triangles.to_byte_array();
  560. triangle_buffer = rd->storage_buffer_create(tb.size(), tb);
  561. Vector<uint8_t> tib = triangle_indices.to_byte_array();
  562. r_triangle_indices_buffer = rd->storage_buffer_create(tib.size(), tib);
  563. Vector<uint8_t> cib = cluster_indices.to_byte_array();
  564. r_cluster_indices_buffer = rd->storage_buffer_create(cib.size(), cib);
  565. Vector<uint8_t> cab = cluster_aabbs.to_byte_array();
  566. r_cluster_aabbs_buffer = rd->storage_buffer_create(cab.size(), cab);
  567. Vector<uint8_t> lb = lights.to_byte_array();
  568. if (lb.is_empty()) {
  569. lb.resize(sizeof(Light)); //even if no lights, the buffer must exist
  570. }
  571. lights_buffer = rd->storage_buffer_create(lb.size(), lb);
  572. Vector<uint8_t> sb = seam_buffer_vec.to_byte_array();
  573. if (sb.is_empty()) {
  574. sb.resize(sizeof(Vector2i) * 2); //even if no seams, the buffer must exist
  575. }
  576. seams_buffer = rd->storage_buffer_create(sb.size(), sb);
  577. Vector<uint8_t> pb = p_probe_positions.to_byte_array();
  578. if (pb.is_empty()) {
  579. pb.resize(sizeof(Probe));
  580. }
  581. probe_positions_buffer = rd->storage_buffer_create(pb.size(), pb);
  582. }
  583. { //grid
  584. RD::TextureFormat tf;
  585. tf.width = grid_size;
  586. tf.height = grid_size;
  587. tf.depth = grid_size;
  588. tf.texture_type = RD::TEXTURE_TYPE_3D;
  589. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  590. Vector<Vector<uint8_t>> texdata;
  591. texdata.resize(1);
  592. //grid and indices
  593. tf.format = RD::DATA_FORMAT_R32G32_UINT;
  594. texdata.write[0] = grid_indices.to_byte_array();
  595. grid_texture = rd->texture_create(tf, RD::TextureView(), texdata);
  596. }
  597. }
  598. void LightmapperRD::_raster_geometry(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, int grid_size, AABB bounds, float p_bias, Vector<int> slice_triangle_count, RID position_tex, RID unocclude_tex, RID normal_tex, RID raster_depth_buffer, RID rasterize_shader, RID raster_base_uniform) {
  599. Vector<RID> framebuffers;
  600. for (int i = 0; i < atlas_slices; i++) {
  601. RID slice_pos_tex = rd->texture_create_shared_from_slice(RD::TextureView(), position_tex, i, 0);
  602. RID slice_unoc_tex = rd->texture_create_shared_from_slice(RD::TextureView(), unocclude_tex, i, 0);
  603. RID slice_norm_tex = rd->texture_create_shared_from_slice(RD::TextureView(), normal_tex, i, 0);
  604. Vector<RID> fb;
  605. fb.push_back(slice_pos_tex);
  606. fb.push_back(slice_norm_tex);
  607. fb.push_back(slice_unoc_tex);
  608. fb.push_back(raster_depth_buffer);
  609. framebuffers.push_back(rd->framebuffer_create(fb));
  610. }
  611. RD::PipelineDepthStencilState ds;
  612. ds.enable_depth_test = true;
  613. ds.enable_depth_write = true;
  614. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does render same pixel twice
  615. RID raster_pipeline = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0);
  616. RID raster_pipeline_wire;
  617. {
  618. RD::PipelineRasterizationState rw;
  619. rw.wireframe = true;
  620. raster_pipeline_wire = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, rw, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0);
  621. }
  622. uint32_t triangle_offset = 0;
  623. Vector<Color> clear_colors;
  624. clear_colors.push_back(Color(0, 0, 0, 0));
  625. clear_colors.push_back(Color(0, 0, 0, 0));
  626. clear_colors.push_back(Color(0, 0, 0, 0));
  627. for (int i = 0; i < atlas_slices; i++) {
  628. RasterPushConstant raster_push_constant;
  629. raster_push_constant.atlas_size[0] = atlas_size.x;
  630. raster_push_constant.atlas_size[1] = atlas_size.y;
  631. raster_push_constant.base_triangle = triangle_offset;
  632. raster_push_constant.to_cell_offset[0] = bounds.position.x;
  633. raster_push_constant.to_cell_offset[1] = bounds.position.y;
  634. raster_push_constant.to_cell_offset[2] = bounds.position.z;
  635. raster_push_constant.bias = p_bias;
  636. raster_push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  637. raster_push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  638. raster_push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  639. raster_push_constant.grid_size[0] = grid_size;
  640. raster_push_constant.grid_size[1] = grid_size;
  641. raster_push_constant.grid_size[2] = grid_size;
  642. // Half pixel offset is required so the rasterizer doesn't output face edges directly aligned into pixels.
  643. // This fixes artifacts where the pixel would be traced from the edge of a face, causing half the rays to
  644. // be outside of the boundaries of the geometry. See <https://github.com/godotengine/godot/issues/69126>.
  645. raster_push_constant.uv_offset[0] = -0.5f / float(atlas_size.x);
  646. raster_push_constant.uv_offset[1] = -0.5f / float(atlas_size.y);
  647. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::DRAW_CLEAR_ALL, clear_colors, 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::LIGHTMAPPER_PASS);
  648. //draw opaque
  649. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline);
  650. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  651. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  652. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  653. //draw wire
  654. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline_wire);
  655. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  656. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  657. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  658. rd->draw_list_end();
  659. triangle_offset += slice_triangle_count[i];
  660. }
  661. }
  662. static Vector<RD::Uniform> dilate_or_denoise_common_uniforms(RID &p_source_light_tex, RID &p_dest_light_tex) {
  663. Vector<RD::Uniform> uniforms;
  664. {
  665. RD::Uniform u;
  666. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  667. u.binding = 0;
  668. u.append_id(p_dest_light_tex);
  669. uniforms.push_back(u);
  670. }
  671. {
  672. RD::Uniform u;
  673. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  674. u.binding = 1;
  675. u.append_id(p_source_light_tex);
  676. uniforms.push_back(u);
  677. }
  678. return uniforms;
  679. }
  680. LightmapperRD::BakeError LightmapperRD::_dilate(RenderingDevice *rd, Ref<RDShaderFile> &compute_shader, RID &compute_base_uniform_set, PushConstant &push_constant, RID &source_light_tex, RID &dest_light_tex, const Size2i &atlas_size, int atlas_slices) {
  681. Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex);
  682. RID compute_shader_dilate = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("dilate"));
  683. ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  684. RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate);
  685. RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_dilate, 1);
  686. RD::ComputeListID compute_list = rd->compute_list_begin();
  687. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_dilate_pipeline);
  688. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  689. rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
  690. push_constant.region_ofs[0] = 0;
  691. push_constant.region_ofs[1] = 0;
  692. Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size
  693. for (int i = 0; i < atlas_slices; i++) {
  694. push_constant.atlas_slice = i;
  695. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  696. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  697. //no barrier, let them run all together
  698. }
  699. rd->compute_list_end();
  700. rd->free(compute_shader_dilate);
  701. #ifdef DEBUG_TEXTURES
  702. for (int i = 0; i < atlas_slices; i++) {
  703. Vector<uint8_t> s = rd->texture_get_data(source_light_tex, i);
  704. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  705. img->convert(Image::FORMAT_RGBA8);
  706. img->save_png("res://5_dilated_" + itos(i) + ".png");
  707. }
  708. #endif
  709. return BAKE_OK;
  710. }
  711. LightmapperRD::BakeError LightmapperRD::_pack_l1(RenderingDevice *rd, Ref<RDShaderFile> &compute_shader, RID &compute_base_uniform_set, PushConstant &push_constant, RID &source_light_tex, RID &dest_light_tex, const Size2i &atlas_size, int atlas_slices) {
  712. Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex);
  713. RID compute_shader_pack = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("pack_coeffs"));
  714. ERR_FAIL_COND_V(compute_shader_pack.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  715. RID compute_shader_pack_pipeline = rd->compute_pipeline_create(compute_shader_pack);
  716. RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_pack, 1);
  717. RD::ComputeListID compute_list = rd->compute_list_begin();
  718. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_pack_pipeline);
  719. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  720. rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
  721. push_constant.region_ofs[0] = 0;
  722. push_constant.region_ofs[1] = 0;
  723. Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size
  724. for (int i = 0; i < atlas_slices; i++) {
  725. push_constant.atlas_slice = i;
  726. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  727. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  728. //no barrier, let them run all together
  729. }
  730. rd->compute_list_end();
  731. rd->free(compute_shader_pack);
  732. return BAKE_OK;
  733. }
  734. Error LightmapperRD::_store_pfm(RenderingDevice *p_rd, RID p_atlas_tex, int p_index, const Size2i &p_atlas_size, const String &p_name, bool p_shadowmask) {
  735. Vector<uint8_t> data = p_rd->texture_get_data(p_atlas_tex, p_index);
  736. Ref<Image> img = Image::create_from_data(p_atlas_size.width, p_atlas_size.height, false, p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH, data);
  737. img->convert(Image::FORMAT_RGBF);
  738. Vector<uint8_t> data_float = img->get_data();
  739. Error err = OK;
  740. Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::WRITE, &err);
  741. ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save PFN at path: '%s'.", p_name));
  742. file->store_line("PF");
  743. file->store_line(vformat("%d %d", img->get_width(), img->get_height()));
  744. #ifdef BIG_ENDIAN_ENABLED
  745. file->store_line("1.0");
  746. #else
  747. file->store_line("-1.0");
  748. #endif
  749. file->store_buffer(data_float);
  750. file->close();
  751. return OK;
  752. }
  753. Ref<Image> LightmapperRD::_read_pfm(const String &p_name, bool p_shadowmask) {
  754. Error err = OK;
  755. Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::READ, &err);
  756. ERR_FAIL_COND_V_MSG(err, Ref<Image>(), vformat("Can't load PFM at path: '%s'.", p_name));
  757. ERR_FAIL_COND_V(file->get_line() != "PF", Ref<Image>());
  758. Vector<String> new_size = file->get_line().split(" ");
  759. ERR_FAIL_COND_V(new_size.size() != 2, Ref<Image>());
  760. int new_width = new_size[0].to_int();
  761. int new_height = new_size[1].to_int();
  762. float endian = file->get_line().to_float();
  763. Vector<uint8_t> new_data = file->get_buffer(file->get_length() - file->get_position());
  764. file->close();
  765. #ifdef BIG_ENDIAN_ENABLED
  766. if (unlikely(endian < 0.0)) {
  767. uint32_t count = new_data.size() / 4;
  768. uint16_t *dst = (uint16_t *)new_data.ptrw();
  769. for (uint32_t j = 0; j < count; j++) {
  770. dst[j * 4] = BSWAP32(dst[j * 4]);
  771. }
  772. }
  773. #else
  774. if (unlikely(endian > 0.0)) {
  775. uint32_t count = new_data.size() / 4;
  776. uint16_t *dst = (uint16_t *)new_data.ptrw();
  777. for (uint32_t j = 0; j < count; j++) {
  778. dst[j * 4] = BSWAP32(dst[j * 4]);
  779. }
  780. }
  781. #endif
  782. Ref<Image> img = Image::create_from_data(new_width, new_height, false, Image::FORMAT_RGBF, new_data);
  783. img->convert(p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH);
  784. return img;
  785. }
  786. LightmapperRD::BakeError LightmapperRD::_denoise_oidn(RenderingDevice *p_rd, RID p_source_light_tex, RID p_source_normal_tex, RID p_dest_light_tex, const Size2i &p_atlas_size, int p_atlas_slices, bool p_bake_sh, bool p_shadowmask, const String &p_exe) {
  787. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  788. for (int i = 0; i < p_atlas_slices; i++) {
  789. String fname_norm_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_norm_%d.pfm", i));
  790. _store_pfm(p_rd, p_source_normal_tex, i, p_atlas_size, fname_norm_in, false);
  791. for (int j = 0; j < (p_bake_sh ? 4 : 1); j++) {
  792. int index = i * (p_bake_sh ? 4 : 1) + j;
  793. String fname_light_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_light_%d.pfm", index));
  794. String fname_out = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_denoised_%d.pfm", index));
  795. _store_pfm(p_rd, p_source_light_tex, index, p_atlas_size, fname_light_in, p_shadowmask);
  796. List<String> args;
  797. args.push_back("--device");
  798. args.push_back("default");
  799. args.push_back("--filter");
  800. args.push_back("RTLightmap");
  801. args.push_back(p_shadowmask ? "--ldr" : "--hdr");
  802. args.push_back(fname_light_in);
  803. args.push_back("--nrm");
  804. args.push_back(fname_norm_in);
  805. args.push_back("--output");
  806. args.push_back(fname_out);
  807. String str;
  808. int exitcode = 0;
  809. Error err = OS::get_singleton()->execute(p_exe, args, &str, &exitcode, true);
  810. da->remove(fname_light_in);
  811. if (err != OK || exitcode != 0) {
  812. da->remove(fname_out);
  813. print_verbose(str);
  814. ERR_FAIL_V_MSG(BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, vformat("OIDN denoiser failed, return code: %d", exitcode));
  815. }
  816. Ref<Image> img = _read_pfm(fname_out, p_shadowmask);
  817. da->remove(fname_out);
  818. ERR_FAIL_COND_V(img.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  819. Vector<uint8_t> old_data = p_rd->texture_get_data(p_source_light_tex, index);
  820. Vector<uint8_t> new_data = img->get_data();
  821. img.unref(); // Avoid copy on write.
  822. uint32_t count = old_data.size() / 2;
  823. const uint16_t *src = (const uint16_t *)old_data.ptr();
  824. uint16_t *dst = (uint16_t *)new_data.ptrw();
  825. for (uint32_t k = 0; k < count; k += 4) {
  826. dst[k + 3] = src[k + 3];
  827. }
  828. p_rd->texture_update(p_dest_light_tex, index, new_data);
  829. }
  830. da->remove(fname_norm_in);
  831. }
  832. return BAKE_OK;
  833. }
  834. LightmapperRD::BakeError LightmapperRD::_denoise(RenderingDevice *p_rd, Ref<RDShaderFile> &p_compute_shader, const RID &p_compute_base_uniform_set, PushConstant &p_push_constant, RID p_source_light_tex, RID p_source_normal_tex, RID p_dest_light_tex, RID p_unocclude_tex, float p_denoiser_strength, int p_denoiser_range, const Size2i &p_atlas_size, int p_atlas_slices, bool p_bake_sh, BakeStepFunc p_step_function, void *p_bake_userdata) {
  835. RID denoise_params_buffer = p_rd->uniform_buffer_create(sizeof(DenoiseParams));
  836. DenoiseParams denoise_params;
  837. denoise_params.spatial_bandwidth = 5.0f;
  838. denoise_params.light_bandwidth = p_denoiser_strength;
  839. denoise_params.albedo_bandwidth = 1.0f;
  840. denoise_params.normal_bandwidth = 0.1f;
  841. denoise_params.filter_strength = 10.0f;
  842. denoise_params.half_search_window = p_denoiser_range;
  843. p_rd->buffer_update(denoise_params_buffer, 0, sizeof(DenoiseParams), &denoise_params);
  844. Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(p_source_light_tex, p_dest_light_tex);
  845. {
  846. RD::Uniform u;
  847. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  848. u.binding = 2;
  849. u.append_id(p_source_normal_tex);
  850. uniforms.push_back(u);
  851. }
  852. {
  853. RD::Uniform u;
  854. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  855. u.binding = 3;
  856. u.append_id(p_unocclude_tex);
  857. uniforms.push_back(u);
  858. }
  859. {
  860. RD::Uniform u;
  861. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  862. u.binding = 4;
  863. u.append_id(denoise_params_buffer);
  864. uniforms.push_back(u);
  865. }
  866. RID compute_shader_denoise = p_rd->shader_create_from_spirv(p_compute_shader->get_spirv_stages("denoise"));
  867. ERR_FAIL_COND_V(compute_shader_denoise.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  868. RID compute_shader_denoise_pipeline = p_rd->compute_pipeline_create(compute_shader_denoise);
  869. RID denoise_uniform_set = p_rd->uniform_set_create(uniforms, compute_shader_denoise, 1);
  870. // We denoise in fixed size regions and synchronize execution to avoid GPU timeouts.
  871. // We use a region with 1/4 the amount of pixels if we're denoising SH lightmaps, as
  872. // all four of them are denoised in the shader in one dispatch.
  873. const int user_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));
  874. const int max_region_size = p_bake_sh ? user_region_size / 2 : user_region_size;
  875. int x_regions = Math::division_round_up(p_atlas_size.width, max_region_size);
  876. int y_regions = Math::division_round_up(p_atlas_size.height, max_region_size);
  877. for (int s = 0; s < p_atlas_slices; s++) {
  878. p_push_constant.atlas_slice = s;
  879. for (int i = 0; i < x_regions; i++) {
  880. for (int j = 0; j < y_regions; j++) {
  881. int x = i * max_region_size;
  882. int y = j * max_region_size;
  883. int w = MIN((i + 1) * max_region_size, p_atlas_size.width) - x;
  884. int h = MIN((j + 1) * max_region_size, p_atlas_size.height) - y;
  885. p_push_constant.region_ofs[0] = x;
  886. p_push_constant.region_ofs[1] = y;
  887. RD::ComputeListID compute_list = p_rd->compute_list_begin();
  888. p_rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_denoise_pipeline);
  889. p_rd->compute_list_bind_uniform_set(compute_list, p_compute_base_uniform_set, 0);
  890. p_rd->compute_list_bind_uniform_set(compute_list, denoise_uniform_set, 1);
  891. p_rd->compute_list_set_push_constant(compute_list, &p_push_constant, sizeof(PushConstant));
  892. p_rd->compute_list_dispatch(compute_list, Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
  893. p_rd->compute_list_end();
  894. p_rd->submit();
  895. p_rd->sync();
  896. }
  897. }
  898. if (p_step_function) {
  899. int percent = (s + 1) * 100 / p_atlas_slices;
  900. float p = float(s) / p_atlas_slices * 0.1;
  901. if (p_step_function(0.8 + p, vformat(RTR("Denoising %d%%"), percent), p_bake_userdata, false)) {
  902. return BAKE_ERROR_USER_ABORTED;
  903. }
  904. }
  905. }
  906. p_rd->free(compute_shader_denoise);
  907. p_rd->free(denoise_params_buffer);
  908. return BAKE_OK;
  909. }
  910. LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_denoiser, float p_denoiser_strength, int p_denoiser_range, int p_bounces, float p_bounce_indirect_energy, float p_bias, int p_max_texture_size, bool p_bake_sh, bool p_bake_shadowmask, bool p_texture_for_bounces, GenerateProbes p_generate_probes, const Ref<Image> &p_environment_panorama, const Basis &p_environment_transform, BakeStepFunc p_step_function, void *p_bake_userdata, float p_exposure_normalization, float p_supersampling_factor) {
  911. int denoiser = GLOBAL_GET("rendering/lightmapping/denoising/denoiser");
  912. String oidn_path = EDITOR_GET("filesystem/tools/oidn/oidn_denoise_path");
  913. if (p_use_denoiser && denoiser == 1) {
  914. // OIDN (external).
  915. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  916. if (da->dir_exists(oidn_path)) {
  917. if (OS::get_singleton()->get_name() == "Windows") {
  918. oidn_path = oidn_path.path_join("oidnDenoise.exe");
  919. } else {
  920. oidn_path = oidn_path.path_join("oidnDenoise");
  921. }
  922. }
  923. ERR_FAIL_COND_V_MSG(oidn_path.is_empty() || !da->file_exists(oidn_path), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, "OIDN denoiser is selected in the project settings, but no or invalid OIDN executable path is configured in the editor settings.");
  924. }
  925. if (p_step_function) {
  926. p_step_function(0.0, RTR("Begin Bake"), p_bake_userdata, true);
  927. }
  928. lightmap_textures.clear();
  929. shadowmask_textures.clear();
  930. int grid_size = 128;
  931. /* STEP 1: Fetch material textures and compute the bounds */
  932. AABB bounds;
  933. Size2i atlas_size;
  934. int atlas_slices;
  935. Vector<Ref<Image>> albedo_images;
  936. Vector<Ref<Image>> emission_images;
  937. BakeError bake_error = _blit_meshes_into_atlas(p_max_texture_size, p_denoiser_range, albedo_images, emission_images, bounds, atlas_size, atlas_slices, p_supersampling_factor, p_step_function, p_bake_userdata);
  938. if (bake_error != BAKE_OK) {
  939. return bake_error;
  940. }
  941. // Find any directional light suitable for shadowmasking.
  942. if (p_bake_shadowmask) {
  943. bool found = false;
  944. for (int i = 0; i < lights.size(); i++) {
  945. if (lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL && !lights[i].static_bake) {
  946. found = true;
  947. break;
  948. }
  949. }
  950. if (!found) {
  951. p_bake_shadowmask = false;
  952. WARN_PRINT("Shadowmask disabled: no directional light with their bake mode set to dynamic exists.");
  953. }
  954. }
  955. #ifdef DEBUG_TEXTURES
  956. for (int i = 0; i < atlas_slices; i++) {
  957. albedo_images[i]->save_png("res://0_albedo_" + itos(i) + ".png");
  958. emission_images[i]->save_png("res://0_emission_" + itos(i) + ".png");
  959. }
  960. #endif
  961. // Attempt to create a local device by requesting it from rendering server first.
  962. // If that fails because the current renderer is not implemented on top of RD, we fall back to creating
  963. // a local rendering device manually depending on the current platform.
  964. Error err;
  965. RenderingContextDriver *rcd = nullptr;
  966. RenderingDevice *rd = RenderingServer::get_singleton()->create_local_rendering_device();
  967. if (rd == nullptr) {
  968. #if defined(RD_ENABLED)
  969. #if defined(METAL_ENABLED)
  970. rcd = memnew(RenderingContextDriverMetal);
  971. rd = memnew(RenderingDevice);
  972. #endif
  973. #if defined(VULKAN_ENABLED)
  974. if (rcd == nullptr) {
  975. rcd = memnew(RenderingContextDriverVulkan);
  976. rd = memnew(RenderingDevice);
  977. }
  978. #endif
  979. #endif
  980. if (rcd != nullptr && rd != nullptr) {
  981. err = rcd->initialize();
  982. if (err == OK) {
  983. err = rd->initialize(rcd);
  984. }
  985. if (err != OK) {
  986. memdelete(rd);
  987. memdelete(rcd);
  988. rd = nullptr;
  989. rcd = nullptr;
  990. }
  991. }
  992. }
  993. ERR_FAIL_NULL_V(rd, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  994. RID albedo_array_tex;
  995. RID emission_array_tex;
  996. RID normal_tex;
  997. RID position_tex;
  998. RID unocclude_tex;
  999. RID light_source_tex;
  1000. RID light_dest_tex;
  1001. RID light_accum_tex;
  1002. RID light_accum_tex2;
  1003. RID light_environment_tex;
  1004. RID shadowmask_tex;
  1005. RID shadowmask_tex2;
  1006. #define FREE_TEXTURES \
  1007. rd->free(albedo_array_tex); \
  1008. rd->free(emission_array_tex); \
  1009. rd->free(normal_tex); \
  1010. rd->free(position_tex); \
  1011. rd->free(unocclude_tex); \
  1012. rd->free(light_source_tex); \
  1013. rd->free(light_accum_tex2); \
  1014. rd->free(light_accum_tex); \
  1015. rd->free(light_environment_tex); \
  1016. if (p_bake_shadowmask) { \
  1017. rd->free(shadowmask_tex); \
  1018. rd->free(shadowmask_tex2); \
  1019. }
  1020. { // create all textures
  1021. Vector<Vector<uint8_t>> albedo_data;
  1022. Vector<Vector<uint8_t>> emission_data;
  1023. for (int i = 0; i < atlas_slices; i++) {
  1024. albedo_data.push_back(albedo_images[i]->get_data());
  1025. emission_data.push_back(emission_images[i]->get_data());
  1026. }
  1027. RD::TextureFormat tf;
  1028. tf.width = atlas_size.width;
  1029. tf.height = atlas_size.height;
  1030. tf.array_layers = atlas_slices;
  1031. tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  1032. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  1033. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  1034. albedo_array_tex = rd->texture_create(tf, RD::TextureView(), albedo_data);
  1035. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1036. emission_array_tex = rd->texture_create(tf, RD::TextureView(), emission_data);
  1037. //this will be rastered to
  1038. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  1039. normal_tex = rd->texture_create(tf, RD::TextureView());
  1040. tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  1041. position_tex = rd->texture_create(tf, RD::TextureView());
  1042. unocclude_tex = rd->texture_create(tf, RD::TextureView());
  1043. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  1044. // shadowmask
  1045. if (p_bake_shadowmask) {
  1046. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  1047. shadowmask_tex = rd->texture_create(tf, RD::TextureView());
  1048. rd->texture_clear(shadowmask_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  1049. shadowmask_tex2 = rd->texture_create(tf, RD::TextureView());
  1050. rd->texture_clear(shadowmask_tex2, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  1051. }
  1052. // lightmap
  1053. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1054. light_source_tex = rd->texture_create(tf, RD::TextureView());
  1055. rd->texture_clear(light_source_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  1056. if (p_bake_sh) {
  1057. tf.array_layers *= 4;
  1058. }
  1059. light_accum_tex = rd->texture_create(tf, RD::TextureView());
  1060. rd->texture_clear(light_accum_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  1061. light_dest_tex = rd->texture_create(tf, RD::TextureView());
  1062. rd->texture_clear(light_dest_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  1063. light_accum_tex2 = light_dest_tex;
  1064. //env
  1065. {
  1066. Ref<Image> panorama_tex;
  1067. if (p_environment_panorama.is_valid()) {
  1068. panorama_tex = p_environment_panorama;
  1069. panorama_tex->convert(Image::FORMAT_RGBAF);
  1070. } else {
  1071. panorama_tex.instantiate();
  1072. panorama_tex->initialize_data(8, 8, false, Image::FORMAT_RGBAF);
  1073. panorama_tex->fill(Color(0, 0, 0, 1));
  1074. }
  1075. RD::TextureFormat tfp;
  1076. tfp.width = panorama_tex->get_width();
  1077. tfp.height = panorama_tex->get_height();
  1078. tfp.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  1079. tfp.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  1080. Vector<Vector<uint8_t>> tdata;
  1081. tdata.push_back(panorama_tex->get_data());
  1082. light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata);
  1083. #ifdef DEBUG_TEXTURES
  1084. panorama_tex->save_exr("res://0_panorama.exr", false);
  1085. #endif
  1086. }
  1087. }
  1088. /* STEP 2: create the acceleration structure for the GPU*/
  1089. Vector<int> slice_triangle_count;
  1090. RID bake_parameters_buffer;
  1091. RID vertex_buffer;
  1092. RID triangle_buffer;
  1093. RID lights_buffer;
  1094. RID triangle_indices_buffer;
  1095. RID cluster_indices_buffer;
  1096. RID cluster_aabbs_buffer;
  1097. RID grid_texture;
  1098. RID seams_buffer;
  1099. RID probe_positions_buffer;
  1100. Vector<int> slice_seam_count;
  1101. #define FREE_BUFFERS \
  1102. rd->free(bake_parameters_buffer); \
  1103. rd->free(vertex_buffer); \
  1104. rd->free(triangle_buffer); \
  1105. rd->free(lights_buffer); \
  1106. rd->free(triangle_indices_buffer); \
  1107. rd->free(cluster_indices_buffer); \
  1108. rd->free(cluster_aabbs_buffer); \
  1109. rd->free(grid_texture); \
  1110. rd->free(seams_buffer); \
  1111. rd->free(probe_positions_buffer);
  1112. const uint32_t cluster_size = 16;
  1113. _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, cluster_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, lights_buffer, triangle_indices_buffer, cluster_indices_buffer, cluster_aabbs_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata);
  1114. // The index of the directional light used for shadowmasking.
  1115. int shadowmask_light_idx = -1;
  1116. // Find the directional light index in the sorted lights array.
  1117. if (p_bake_shadowmask) {
  1118. int shadowmask_lights_count = 0;
  1119. for (int i = 0; i < lights.size(); i++) {
  1120. if (lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL && !lights[i].static_bake) {
  1121. if (shadowmask_light_idx < 0) {
  1122. shadowmask_light_idx = i;
  1123. }
  1124. shadowmask_lights_count += 1;
  1125. }
  1126. }
  1127. if (shadowmask_lights_count > 1) {
  1128. WARN_PRINT(
  1129. vformat("%d directional lights detected for shadowmask baking. Only %s will be used.",
  1130. shadowmask_lights_count, light_metadata[shadowmask_light_idx].name));
  1131. }
  1132. }
  1133. // Create global bake parameters buffer.
  1134. BakeParameters bake_parameters;
  1135. bake_parameters.world_size[0] = bounds.size.x;
  1136. bake_parameters.world_size[1] = bounds.size.y;
  1137. bake_parameters.world_size[2] = bounds.size.z;
  1138. bake_parameters.bias = p_bias;
  1139. bake_parameters.to_cell_offset[0] = bounds.position.x;
  1140. bake_parameters.to_cell_offset[1] = bounds.position.y;
  1141. bake_parameters.to_cell_offset[2] = bounds.position.z;
  1142. bake_parameters.grid_size = grid_size;
  1143. bake_parameters.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  1144. bake_parameters.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  1145. bake_parameters.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  1146. bake_parameters.light_count = lights.size();
  1147. bake_parameters.env_transform[0] = p_environment_transform.rows[0][0];
  1148. bake_parameters.env_transform[1] = p_environment_transform.rows[1][0];
  1149. bake_parameters.env_transform[2] = p_environment_transform.rows[2][0];
  1150. bake_parameters.env_transform[3] = 0.0f;
  1151. bake_parameters.env_transform[4] = p_environment_transform.rows[0][1];
  1152. bake_parameters.env_transform[5] = p_environment_transform.rows[1][1];
  1153. bake_parameters.env_transform[6] = p_environment_transform.rows[2][1];
  1154. bake_parameters.env_transform[7] = 0.0f;
  1155. bake_parameters.env_transform[8] = p_environment_transform.rows[0][2];
  1156. bake_parameters.env_transform[9] = p_environment_transform.rows[1][2];
  1157. bake_parameters.env_transform[10] = p_environment_transform.rows[2][2];
  1158. bake_parameters.env_transform[11] = 0.0f;
  1159. bake_parameters.atlas_size[0] = atlas_size.width;
  1160. bake_parameters.atlas_size[1] = atlas_size.height;
  1161. bake_parameters.exposure_normalization = p_exposure_normalization;
  1162. bake_parameters.bounces = p_bounces;
  1163. bake_parameters.bounce_indirect_energy = p_bounce_indirect_energy;
  1164. bake_parameters.shadowmask_light_idx = shadowmask_light_idx;
  1165. // Same number of rays for transparency regardless of quality (it's more of a retry rather than shooting new ones).
  1166. bake_parameters.transparency_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_transparency_rays");
  1167. bake_parameters.supersampling_factor = p_supersampling_factor;
  1168. bake_parameters_buffer = rd->uniform_buffer_create(sizeof(BakeParameters));
  1169. rd->buffer_update(bake_parameters_buffer, 0, sizeof(BakeParameters), &bake_parameters);
  1170. if (p_step_function) {
  1171. if (p_step_function(0.47, RTR("Preparing shaders"), p_bake_userdata, true)) {
  1172. FREE_TEXTURES
  1173. FREE_BUFFERS
  1174. memdelete(rd);
  1175. if (rcd != nullptr) {
  1176. memdelete(rcd);
  1177. }
  1178. return BAKE_ERROR_USER_ABORTED;
  1179. }
  1180. }
  1181. //shaders
  1182. Ref<RDShaderFile> raster_shader;
  1183. raster_shader.instantiate();
  1184. err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl);
  1185. if (err != OK) {
  1186. raster_shader->print_errors("raster_shader");
  1187. FREE_TEXTURES
  1188. FREE_BUFFERS
  1189. memdelete(rd);
  1190. if (rcd != nullptr) {
  1191. memdelete(rcd);
  1192. }
  1193. }
  1194. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1195. RID rasterize_shader = rd->shader_create_from_spirv(raster_shader->get_spirv_stages());
  1196. ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen
  1197. RID sampler;
  1198. {
  1199. RD::SamplerState s;
  1200. s.mag_filter = RD::SAMPLER_FILTER_LINEAR;
  1201. s.min_filter = RD::SAMPLER_FILTER_LINEAR;
  1202. s.max_lod = 0;
  1203. sampler = rd->sampler_create(s);
  1204. }
  1205. Vector<RD::Uniform> base_uniforms;
  1206. {
  1207. {
  1208. RD::Uniform u;
  1209. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  1210. u.binding = 0;
  1211. u.append_id(bake_parameters_buffer);
  1212. base_uniforms.push_back(u);
  1213. }
  1214. {
  1215. RD::Uniform u;
  1216. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1217. u.binding = 1;
  1218. u.append_id(vertex_buffer);
  1219. base_uniforms.push_back(u);
  1220. }
  1221. {
  1222. RD::Uniform u;
  1223. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1224. u.binding = 2;
  1225. u.append_id(triangle_buffer);
  1226. base_uniforms.push_back(u);
  1227. }
  1228. {
  1229. RD::Uniform u;
  1230. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1231. u.binding = 3;
  1232. u.append_id(triangle_indices_buffer);
  1233. base_uniforms.push_back(u);
  1234. }
  1235. {
  1236. RD::Uniform u;
  1237. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1238. u.binding = 4;
  1239. u.append_id(lights_buffer);
  1240. base_uniforms.push_back(u);
  1241. }
  1242. {
  1243. RD::Uniform u;
  1244. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1245. u.binding = 5;
  1246. u.append_id(seams_buffer);
  1247. base_uniforms.push_back(u);
  1248. }
  1249. {
  1250. RD::Uniform u;
  1251. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1252. u.binding = 6;
  1253. u.append_id(probe_positions_buffer);
  1254. base_uniforms.push_back(u);
  1255. }
  1256. {
  1257. RD::Uniform u;
  1258. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1259. u.binding = 7;
  1260. u.append_id(grid_texture);
  1261. base_uniforms.push_back(u);
  1262. }
  1263. {
  1264. RD::Uniform u;
  1265. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1266. u.binding = 8;
  1267. u.append_id(albedo_array_tex);
  1268. base_uniforms.push_back(u);
  1269. }
  1270. {
  1271. RD::Uniform u;
  1272. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1273. u.binding = 9;
  1274. u.append_id(emission_array_tex);
  1275. base_uniforms.push_back(u);
  1276. }
  1277. {
  1278. RD::Uniform u;
  1279. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  1280. u.binding = 10;
  1281. u.append_id(sampler);
  1282. base_uniforms.push_back(u);
  1283. }
  1284. {
  1285. RD::Uniform u;
  1286. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1287. u.binding = 11;
  1288. u.append_id(cluster_indices_buffer);
  1289. base_uniforms.push_back(u);
  1290. }
  1291. {
  1292. RD::Uniform u;
  1293. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1294. u.binding = 12;
  1295. u.append_id(cluster_aabbs_buffer);
  1296. base_uniforms.push_back(u);
  1297. }
  1298. }
  1299. RID raster_base_uniform = rd->uniform_set_create(base_uniforms, rasterize_shader, 0);
  1300. RID raster_depth_buffer;
  1301. {
  1302. RD::TextureFormat tf;
  1303. tf.width = atlas_size.width;
  1304. tf.height = atlas_size.height;
  1305. tf.depth = 1;
  1306. tf.texture_type = RD::TEXTURE_TYPE_2D;
  1307. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1308. tf.format = RD::DATA_FORMAT_D32_SFLOAT;
  1309. tf.is_discardable = true;
  1310. raster_depth_buffer = rd->texture_create(tf, RD::TextureView());
  1311. }
  1312. rd->submit();
  1313. rd->sync();
  1314. /* STEP 3: Raster the geometry to UV2 coords in the atlas textures GPU*/
  1315. _raster_geometry(rd, atlas_size, atlas_slices, grid_size, bounds, p_bias, slice_triangle_count, position_tex, unocclude_tex, normal_tex, raster_depth_buffer, rasterize_shader, raster_base_uniform);
  1316. #ifdef DEBUG_TEXTURES
  1317. for (int i = 0; i < atlas_slices; i++) {
  1318. Vector<uint8_t> s = rd->texture_get_data(position_tex, i);
  1319. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
  1320. img->save_exr("res://1_position_" + itos(i) + ".exr", false);
  1321. s = rd->texture_get_data(normal_tex, i);
  1322. img->set_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1323. img->save_exr("res://1_normal_" + itos(i) + ".exr", false);
  1324. }
  1325. #endif
  1326. #define FREE_RASTER_RESOURCES \
  1327. rd->free(rasterize_shader); \
  1328. rd->free(sampler); \
  1329. rd->free(raster_depth_buffer);
  1330. /* Plot direct light */
  1331. Ref<RDShaderFile> compute_shader;
  1332. String defines = "";
  1333. defines += "\n#define CLUSTER_SIZE " + uitos(cluster_size) + "\n";
  1334. if (p_bake_sh) {
  1335. defines += "\n#define USE_SH_LIGHTMAPS\n";
  1336. }
  1337. if (p_texture_for_bounces) {
  1338. defines += "\n#define USE_LIGHT_TEXTURE_FOR_BOUNCES\n";
  1339. }
  1340. if (p_bake_shadowmask) {
  1341. defines += "\n#define USE_SHADOWMASK\n";
  1342. }
  1343. compute_shader.instantiate();
  1344. err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, defines);
  1345. if (err != OK) {
  1346. FREE_TEXTURES
  1347. FREE_BUFFERS
  1348. FREE_RASTER_RESOURCES
  1349. memdelete(rd);
  1350. if (rcd != nullptr) {
  1351. memdelete(rcd);
  1352. }
  1353. compute_shader->print_errors("compute_shader");
  1354. }
  1355. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1356. // Unoccluder
  1357. RID compute_shader_unocclude = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("unocclude"));
  1358. ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  1359. RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude);
  1360. // Direct light
  1361. RID compute_shader_primary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("primary"));
  1362. ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  1363. RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary);
  1364. // Indirect light
  1365. RID compute_shader_secondary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("secondary"));
  1366. ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  1367. RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary);
  1368. // Light probes
  1369. RID compute_shader_light_probes = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("light_probes"));
  1370. ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  1371. RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes);
  1372. RID compute_base_uniform_set = rd->uniform_set_create(base_uniforms, compute_shader_primary, 0);
  1373. #define FREE_COMPUTE_RESOURCES \
  1374. rd->free(compute_shader_unocclude); \
  1375. rd->free(compute_shader_primary); \
  1376. rd->free(compute_shader_secondary); \
  1377. rd->free(compute_shader_light_probes);
  1378. Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1);
  1379. rd->submit();
  1380. rd->sync();
  1381. if (p_step_function) {
  1382. if (p_step_function(0.49, RTR("Un-occluding geometry"), p_bake_userdata, true)) {
  1383. FREE_TEXTURES
  1384. FREE_BUFFERS
  1385. FREE_RASTER_RESOURCES
  1386. FREE_COMPUTE_RESOURCES
  1387. memdelete(rd);
  1388. if (rcd != nullptr) {
  1389. memdelete(rcd);
  1390. }
  1391. return BAKE_ERROR_USER_ABORTED;
  1392. }
  1393. }
  1394. PushConstant push_constant;
  1395. push_constant.denoiser_range = p_use_denoiser ? p_denoiser_range : 1.0;
  1396. /* UNOCCLUDE */
  1397. {
  1398. Vector<RD::Uniform> uniforms;
  1399. {
  1400. {
  1401. RD::Uniform u;
  1402. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1403. u.binding = 0;
  1404. u.append_id(position_tex);
  1405. uniforms.push_back(u);
  1406. }
  1407. {
  1408. RD::Uniform u;
  1409. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1410. u.binding = 1;
  1411. u.append_id(unocclude_tex);
  1412. uniforms.push_back(u);
  1413. }
  1414. }
  1415. RID unocclude_uniform_set = rd->uniform_set_create(uniforms, compute_shader_unocclude, 1);
  1416. RD::ComputeListID compute_list = rd->compute_list_begin();
  1417. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_unocclude_pipeline);
  1418. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1419. rd->compute_list_bind_uniform_set(compute_list, unocclude_uniform_set, 1);
  1420. for (int i = 0; i < atlas_slices; i++) {
  1421. push_constant.atlas_slice = i;
  1422. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1423. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1424. //no barrier, let them run all together
  1425. }
  1426. rd->compute_list_end(); //done
  1427. }
  1428. #ifdef DEBUG_TEXTURES
  1429. for (int i = 0; i < atlas_slices; i++) {
  1430. Vector<uint8_t> s = rd->texture_get_data(unocclude_tex, i);
  1431. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
  1432. img->save_exr("res://1_unocclude_" + itos(i) + ".exr", false);
  1433. }
  1434. #endif
  1435. if (p_step_function) {
  1436. if (p_step_function(0.5, RTR("Plot direct lighting"), p_bake_userdata, true)) {
  1437. FREE_TEXTURES
  1438. FREE_BUFFERS
  1439. FREE_RASTER_RESOURCES
  1440. FREE_COMPUTE_RESOURCES
  1441. memdelete(rd);
  1442. if (rcd != nullptr) {
  1443. memdelete(rcd);
  1444. }
  1445. return BAKE_ERROR_USER_ABORTED;
  1446. }
  1447. }
  1448. const int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));
  1449. const int x_regions = Math::division_round_up(atlas_size.width, max_region_size);
  1450. const int y_regions = Math::division_round_up(atlas_size.height, max_region_size);
  1451. // Set ray count to the quality used for direct light and bounces.
  1452. switch (p_quality) {
  1453. case BAKE_QUALITY_LOW: {
  1454. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_ray_count");
  1455. } break;
  1456. case BAKE_QUALITY_MEDIUM: {
  1457. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_ray_count");
  1458. } break;
  1459. case BAKE_QUALITY_HIGH: {
  1460. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_ray_count");
  1461. } break;
  1462. case BAKE_QUALITY_ULTRA: {
  1463. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_ray_count");
  1464. } break;
  1465. }
  1466. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1467. /* PRIMARY (direct) LIGHT PASS */
  1468. {
  1469. Vector<RD::Uniform> uniforms;
  1470. {
  1471. {
  1472. RD::Uniform u;
  1473. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1474. u.binding = 0;
  1475. u.append_id(light_source_tex);
  1476. uniforms.push_back(u);
  1477. }
  1478. {
  1479. RD::Uniform u;
  1480. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1481. u.binding = 1;
  1482. u.append_id(light_dest_tex); //will be unused
  1483. uniforms.push_back(u);
  1484. }
  1485. {
  1486. RD::Uniform u;
  1487. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1488. u.binding = 2;
  1489. u.append_id(position_tex);
  1490. uniforms.push_back(u);
  1491. }
  1492. {
  1493. RD::Uniform u;
  1494. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1495. u.binding = 3;
  1496. u.append_id(normal_tex);
  1497. uniforms.push_back(u);
  1498. }
  1499. {
  1500. RD::Uniform u;
  1501. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1502. u.binding = 4;
  1503. u.append_id(light_accum_tex);
  1504. uniforms.push_back(u);
  1505. }
  1506. if (p_bake_shadowmask) {
  1507. RD::Uniform u;
  1508. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1509. u.binding = 5;
  1510. u.append_id(shadowmask_tex);
  1511. uniforms.push_back(u);
  1512. }
  1513. }
  1514. RID light_uniform_set = rd->uniform_set_create(uniforms, compute_shader_primary, 1);
  1515. int count = 0;
  1516. for (int s = 0; s < atlas_slices; s++) {
  1517. push_constant.atlas_slice = s;
  1518. for (int i = 0; i < x_regions; i++) {
  1519. for (int j = 0; j < y_regions; j++) {
  1520. int x = i * max_region_size;
  1521. int y = j * max_region_size;
  1522. int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
  1523. int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
  1524. push_constant.region_ofs[0] = x;
  1525. push_constant.region_ofs[1] = y;
  1526. group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
  1527. RD::ComputeListID compute_list = rd->compute_list_begin();
  1528. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_primary_pipeline);
  1529. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1530. rd->compute_list_bind_uniform_set(compute_list, light_uniform_set, 1);
  1531. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1532. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1533. rd->compute_list_end();
  1534. rd->submit();
  1535. rd->sync();
  1536. count++;
  1537. if (p_step_function) {
  1538. int total = (atlas_slices * x_regions * y_regions);
  1539. int percent = count * 100 / total;
  1540. float p = float(count) / total * 0.1;
  1541. if (p_step_function(0.5 + p, vformat(RTR("Plot direct lighting %d%%"), percent), p_bake_userdata, false)) {
  1542. FREE_TEXTURES
  1543. FREE_BUFFERS
  1544. FREE_RASTER_RESOURCES
  1545. FREE_COMPUTE_RESOURCES
  1546. memdelete(rd);
  1547. if (rcd != nullptr) {
  1548. memdelete(rcd);
  1549. }
  1550. return BAKE_ERROR_USER_ABORTED;
  1551. }
  1552. }
  1553. }
  1554. }
  1555. }
  1556. }
  1557. #ifdef DEBUG_TEXTURES
  1558. for (int i = 0; i < atlas_slices; i++) {
  1559. Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);
  1560. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1561. img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false);
  1562. }
  1563. if (p_bake_sh) {
  1564. for (int i = 0; i < atlas_slices * 4; i++) {
  1565. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1566. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1567. img->save_exr("res://2_light_primary_accum_" + itos(i) + ".exr", false);
  1568. }
  1569. }
  1570. #endif
  1571. /* SECONDARY (indirect) LIGHT PASS(ES) */
  1572. if (p_bounces > 0) {
  1573. Vector<RD::Uniform> uniforms;
  1574. {
  1575. {
  1576. // Unused.
  1577. RD::Uniform u;
  1578. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1579. u.binding = 0;
  1580. u.append_id(light_dest_tex);
  1581. uniforms.push_back(u);
  1582. }
  1583. {
  1584. RD::Uniform u;
  1585. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1586. u.binding = 1;
  1587. u.append_id(light_source_tex);
  1588. uniforms.push_back(u);
  1589. }
  1590. {
  1591. RD::Uniform u;
  1592. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1593. u.binding = 2;
  1594. u.append_id(position_tex);
  1595. uniforms.push_back(u);
  1596. }
  1597. {
  1598. RD::Uniform u;
  1599. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1600. u.binding = 3;
  1601. u.append_id(normal_tex);
  1602. uniforms.push_back(u);
  1603. }
  1604. {
  1605. RD::Uniform u;
  1606. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1607. u.binding = 4;
  1608. u.append_id(light_accum_tex);
  1609. uniforms.push_back(u);
  1610. }
  1611. {
  1612. RD::Uniform u;
  1613. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1614. u.binding = 5;
  1615. u.append_id(light_environment_tex);
  1616. uniforms.push_back(u);
  1617. }
  1618. }
  1619. RID secondary_uniform_set;
  1620. secondary_uniform_set = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
  1621. const int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass");
  1622. int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);
  1623. if (p_step_function) {
  1624. if (p_step_function(0.6, RTR("Integrate indirect lighting"), p_bake_userdata, true)) {
  1625. FREE_TEXTURES
  1626. FREE_BUFFERS
  1627. FREE_RASTER_RESOURCES
  1628. FREE_COMPUTE_RESOURCES
  1629. memdelete(rd);
  1630. if (rcd != nullptr) {
  1631. memdelete(rcd);
  1632. }
  1633. return BAKE_ERROR_USER_ABORTED;
  1634. }
  1635. }
  1636. int count = 0;
  1637. for (int s = 0; s < atlas_slices; s++) {
  1638. push_constant.atlas_slice = s;
  1639. for (int i = 0; i < x_regions; i++) {
  1640. for (int j = 0; j < y_regions; j++) {
  1641. int x = i * max_region_size;
  1642. int y = j * max_region_size;
  1643. int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
  1644. int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
  1645. push_constant.region_ofs[0] = x;
  1646. push_constant.region_ofs[1] = y;
  1647. group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
  1648. for (int k = 0; k < ray_iterations; k++) {
  1649. RD::ComputeListID compute_list = rd->compute_list_begin();
  1650. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline);
  1651. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1652. rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set, 1);
  1653. push_constant.ray_from = k * max_rays;
  1654. push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count));
  1655. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1656. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1657. rd->compute_list_end();
  1658. rd->submit();
  1659. rd->sync();
  1660. count++;
  1661. if (p_step_function) {
  1662. int total = (atlas_slices * x_regions * y_regions * ray_iterations);
  1663. int percent = count * 100 / total;
  1664. float p = float(count) / total * 0.1;
  1665. if (p_step_function(0.6 + p, vformat(RTR("Integrate indirect lighting %d%%"), percent), p_bake_userdata, false)) {
  1666. FREE_TEXTURES
  1667. FREE_BUFFERS
  1668. FREE_RASTER_RESOURCES
  1669. FREE_COMPUTE_RESOURCES
  1670. memdelete(rd);
  1671. if (rcd != nullptr) {
  1672. memdelete(rcd);
  1673. }
  1674. return BAKE_ERROR_USER_ABORTED;
  1675. }
  1676. }
  1677. }
  1678. }
  1679. }
  1680. }
  1681. }
  1682. /* LIGHTPROBES */
  1683. RID light_probe_buffer;
  1684. if (probe_positions.size()) {
  1685. light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size());
  1686. if (p_step_function) {
  1687. if (p_step_function(0.7, RTR("Baking light probes"), p_bake_userdata, true)) {
  1688. FREE_TEXTURES
  1689. FREE_BUFFERS
  1690. FREE_RASTER_RESOURCES
  1691. FREE_COMPUTE_RESOURCES
  1692. if (probe_positions.size() > 0) {
  1693. rd->free(light_probe_buffer);
  1694. }
  1695. memdelete(rd);
  1696. if (rcd != nullptr) {
  1697. memdelete(rcd);
  1698. }
  1699. return BAKE_ERROR_USER_ABORTED;
  1700. }
  1701. }
  1702. Vector<RD::Uniform> uniforms;
  1703. {
  1704. {
  1705. RD::Uniform u;
  1706. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1707. u.binding = 0;
  1708. u.append_id(light_probe_buffer);
  1709. uniforms.push_back(u);
  1710. }
  1711. {
  1712. RD::Uniform u;
  1713. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1714. u.binding = 1;
  1715. u.append_id(light_source_tex);
  1716. uniforms.push_back(u);
  1717. }
  1718. {
  1719. RD::Uniform u;
  1720. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1721. u.binding = 2;
  1722. u.append_id(light_environment_tex);
  1723. uniforms.push_back(u);
  1724. }
  1725. }
  1726. RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1);
  1727. switch (p_quality) {
  1728. case BAKE_QUALITY_LOW: {
  1729. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_probe_ray_count");
  1730. } break;
  1731. case BAKE_QUALITY_MEDIUM: {
  1732. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_probe_ray_count");
  1733. } break;
  1734. case BAKE_QUALITY_HIGH: {
  1735. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_probe_ray_count");
  1736. } break;
  1737. case BAKE_QUALITY_ULTRA: {
  1738. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count");
  1739. } break;
  1740. }
  1741. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1742. push_constant.probe_count = probe_positions.size();
  1743. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass");
  1744. int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);
  1745. for (int i = 0; i < ray_iterations; i++) {
  1746. RD::ComputeListID compute_list = rd->compute_list_begin();
  1747. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline);
  1748. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1749. rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1);
  1750. push_constant.ray_from = i * max_rays;
  1751. push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count));
  1752. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1753. rd->compute_list_dispatch(compute_list, Math::division_round_up((int)probe_positions.size(), 64), 1, 1);
  1754. rd->compute_list_end(); //done
  1755. rd->submit();
  1756. rd->sync();
  1757. if (p_step_function) {
  1758. int percent = i * 100 / ray_iterations;
  1759. float p = float(i) / ray_iterations * 0.1;
  1760. if (p_step_function(0.7 + p, vformat(RTR("Integrating light probes %d%%"), percent), p_bake_userdata, false)) {
  1761. FREE_TEXTURES
  1762. FREE_BUFFERS
  1763. FREE_RASTER_RESOURCES
  1764. FREE_COMPUTE_RESOURCES
  1765. if (probe_positions.size() > 0) {
  1766. rd->free(light_probe_buffer);
  1767. }
  1768. memdelete(rd);
  1769. if (rcd != nullptr) {
  1770. memdelete(rcd);
  1771. }
  1772. return BAKE_ERROR_USER_ABORTED;
  1773. }
  1774. }
  1775. }
  1776. }
  1777. #if 0
  1778. for (int i = 0; i < probe_positions.size(); i++) {
  1779. Ref<Image> img = Image::create_empty(6, 4, false, Image::FORMAT_RGB8);
  1780. for (int j = 0; j < 6; j++) {
  1781. Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);
  1782. Ref<Image> img2 = Image::create_from_data(2, 2, false, Image::FORMAT_RGBAF, s);
  1783. img2->convert(Image::FORMAT_RGB8);
  1784. img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2));
  1785. }
  1786. img->save_png("res://3_light_probe_" + itos(i) + ".png");
  1787. }
  1788. #endif
  1789. /* DENOISE */
  1790. if (p_use_denoiser) {
  1791. if (p_step_function) {
  1792. if (p_step_function(0.8, RTR("Denoising"), p_bake_userdata, true)) {
  1793. FREE_TEXTURES
  1794. FREE_BUFFERS
  1795. FREE_RASTER_RESOURCES
  1796. FREE_COMPUTE_RESOURCES
  1797. if (probe_positions.size() > 0) {
  1798. rd->free(light_probe_buffer);
  1799. }
  1800. memdelete(rd);
  1801. if (rcd != nullptr) {
  1802. memdelete(rcd);
  1803. }
  1804. return BAKE_ERROR_USER_ABORTED;
  1805. }
  1806. }
  1807. {
  1808. BakeError error;
  1809. if (denoiser == 1) {
  1810. // OIDN (external).
  1811. error = _denoise_oidn(rd, light_accum_tex, normal_tex, light_accum_tex, atlas_size, atlas_slices, p_bake_sh, false, oidn_path);
  1812. } else {
  1813. // JNLM (built-in).
  1814. SWAP(light_accum_tex, light_accum_tex2);
  1815. error = _denoise(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, normal_tex, light_accum_tex, unocclude_tex, p_denoiser_strength, p_denoiser_range, atlas_size, atlas_slices, p_bake_sh, p_step_function, p_bake_userdata);
  1816. }
  1817. if (unlikely(error != BAKE_OK)) {
  1818. return error;
  1819. }
  1820. }
  1821. if (p_bake_shadowmask) {
  1822. BakeError error;
  1823. if (denoiser == 1) {
  1824. // OIDN (external).
  1825. error = _denoise_oidn(rd, shadowmask_tex, normal_tex, shadowmask_tex, atlas_size, atlas_slices, false, true, oidn_path);
  1826. } else {
  1827. // JNLM (built-in).
  1828. SWAP(shadowmask_tex, shadowmask_tex2);
  1829. error = _denoise(rd, compute_shader, compute_base_uniform_set, push_constant, shadowmask_tex2, normal_tex, shadowmask_tex, unocclude_tex, p_denoiser_strength, p_denoiser_range, atlas_size, atlas_slices, false, p_step_function, p_bake_userdata);
  1830. }
  1831. if (unlikely(error != BAKE_OK)) {
  1832. return error;
  1833. }
  1834. }
  1835. }
  1836. /* DILATE */
  1837. {
  1838. SWAP(light_accum_tex, light_accum_tex2);
  1839. BakeError error = _dilate(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, light_accum_tex, atlas_size, atlas_slices * (p_bake_sh ? 4 : 1));
  1840. if (unlikely(error != BAKE_OK)) {
  1841. return error;
  1842. }
  1843. if (p_bake_shadowmask) {
  1844. SWAP(shadowmask_tex, shadowmask_tex2);
  1845. error = _dilate(rd, compute_shader, compute_base_uniform_set, push_constant, shadowmask_tex2, shadowmask_tex, atlas_size, atlas_slices);
  1846. if (unlikely(error != BAKE_OK)) {
  1847. return error;
  1848. }
  1849. }
  1850. }
  1851. #ifdef DEBUG_TEXTURES
  1852. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1853. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1854. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1855. img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false);
  1856. }
  1857. #endif
  1858. /* BLEND SEAMS */
  1859. //shaders
  1860. Ref<RDShaderFile> blendseams_shader;
  1861. blendseams_shader.instantiate();
  1862. err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl);
  1863. if (err != OK) {
  1864. FREE_TEXTURES
  1865. FREE_BUFFERS
  1866. FREE_RASTER_RESOURCES
  1867. FREE_COMPUTE_RESOURCES
  1868. memdelete(rd);
  1869. if (rcd != nullptr) {
  1870. memdelete(rcd);
  1871. }
  1872. blendseams_shader->print_errors("blendseams_shader");
  1873. }
  1874. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1875. RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines"));
  1876. ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1877. RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles"));
  1878. ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1879. #define FREE_BLENDSEAMS_RESOURCES \
  1880. rd->free(blendseams_line_raster_shader); \
  1881. rd->free(blendseams_triangle_raster_shader);
  1882. {
  1883. //pre copy
  1884. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1885. rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i);
  1886. }
  1887. Vector<RID> framebuffers;
  1888. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1889. RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0);
  1890. Vector<RID> fb;
  1891. fb.push_back(slice_tex);
  1892. fb.push_back(raster_depth_buffer);
  1893. framebuffers.push_back(rd->framebuffer_create(fb));
  1894. }
  1895. Vector<RD::Uniform> uniforms;
  1896. {
  1897. {
  1898. RD::Uniform u;
  1899. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1900. u.binding = 0;
  1901. u.append_id(light_accum_tex2);
  1902. uniforms.push_back(u);
  1903. }
  1904. }
  1905. RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1);
  1906. bool debug = false;
  1907. RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1);
  1908. bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
  1909. bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1910. RD::PipelineDepthStencilState ds;
  1911. ds.enable_depth_test = true;
  1912. ds.enable_depth_write = true;
  1913. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending
  1914. RID blendseams_line_raster_pipeline = rd->render_pipeline_create(blendseams_line_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_LINES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0);
  1915. RID blendseams_triangle_raster_pipeline = rd->render_pipeline_create(blendseams_triangle_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0);
  1916. uint32_t seam_offset = 0;
  1917. uint32_t triangle_offset = 0;
  1918. for (int i = 0; i < atlas_slices; i++) {
  1919. int subslices = (p_bake_sh ? 4 : 1);
  1920. if (slice_seam_count[i] == 0) {
  1921. continue;
  1922. }
  1923. for (int k = 0; k < subslices; k++) {
  1924. RasterSeamsPushConstant seams_push_constant;
  1925. seams_push_constant.slice = uint32_t(i * subslices + k);
  1926. seams_push_constant.debug = debug;
  1927. // Store the current subslice in the breadcrumb.
  1928. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i * subslices + k], RD::DRAW_CLEAR_DEPTH, Vector<Color>(), 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::LIGHTMAPPER_PASS | seams_push_constant.slice);
  1929. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  1930. rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1);
  1931. const int uv_offset_count = 9;
  1932. static const Vector3 uv_offsets[uv_offset_count] = {
  1933. Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards
  1934. Vector3(0, 1, 0.2),
  1935. Vector3(0, -1, 0.2),
  1936. Vector3(1, 0, 0.2),
  1937. Vector3(-1, 0, 0.2),
  1938. Vector3(-1, -1, 0.1),
  1939. Vector3(1, -1, 0.1),
  1940. Vector3(1, 1, 0.1),
  1941. Vector3(-1, 1, 0.1),
  1942. };
  1943. /* step 1 use lines to blend the edges */
  1944. {
  1945. seams_push_constant.base_index = seam_offset;
  1946. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1947. seams_push_constant.uv_offset[0] = (uv_offsets[0].x - 0.5f) / float(atlas_size.width);
  1948. seams_push_constant.uv_offset[1] = (uv_offsets[0].y - 0.5f) / float(atlas_size.height);
  1949. seams_push_constant.blend = uv_offsets[0].z;
  1950. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1951. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1952. }
  1953. /* step 2 use triangles to mask the interior */
  1954. {
  1955. seams_push_constant.base_index = triangle_offset;
  1956. rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline);
  1957. seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask
  1958. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1959. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  1960. }
  1961. /* step 3 blend around the triangle */
  1962. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1963. for (int j = 1; j < uv_offset_count; j++) {
  1964. seams_push_constant.base_index = seam_offset;
  1965. seams_push_constant.uv_offset[0] = (uv_offsets[j].x - 0.5f) / float(atlas_size.width);
  1966. seams_push_constant.uv_offset[1] = (uv_offsets[j].y - 0.5f) / float(atlas_size.height);
  1967. seams_push_constant.blend = uv_offsets[0].z;
  1968. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1969. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1970. }
  1971. rd->draw_list_end();
  1972. }
  1973. seam_offset += slice_seam_count[i];
  1974. triangle_offset += slice_triangle_count[i];
  1975. }
  1976. }
  1977. if (p_bake_sh) {
  1978. SWAP(light_accum_tex, light_accum_tex2);
  1979. BakeError error = _pack_l1(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, light_accum_tex, atlas_size, atlas_slices);
  1980. if (unlikely(error != BAKE_OK)) {
  1981. return error;
  1982. }
  1983. }
  1984. #ifdef DEBUG_TEXTURES
  1985. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1986. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1987. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1988. img->save_exr("res://5_blendseams" + itos(i) + ".exr", false);
  1989. }
  1990. #endif
  1991. if (p_step_function) {
  1992. p_step_function(0.9, RTR("Retrieving textures"), p_bake_userdata, true);
  1993. }
  1994. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1995. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1996. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1997. img->convert(Image::FORMAT_RGBH); //remove alpha
  1998. lightmap_textures.push_back(img);
  1999. }
  2000. if (p_bake_shadowmask) {
  2001. for (int i = 0; i < atlas_slices; i++) {
  2002. Vector<uint8_t> s = rd->texture_get_data(shadowmask_tex, i);
  2003. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8, s);
  2004. img->convert(Image::FORMAT_R8);
  2005. shadowmask_textures.push_back(img);
  2006. }
  2007. }
  2008. if (probe_positions.size() > 0) {
  2009. probe_values.resize(probe_positions.size() * 9);
  2010. Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer);
  2011. memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size());
  2012. rd->free(light_probe_buffer);
  2013. #ifdef DEBUG_TEXTURES
  2014. {
  2015. Ref<Image> img2 = Image::create_from_data(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
  2016. img2->save_exr("res://6_lightprobes.exr", false);
  2017. }
  2018. #endif
  2019. }
  2020. FREE_TEXTURES
  2021. FREE_BUFFERS
  2022. FREE_RASTER_RESOURCES
  2023. FREE_COMPUTE_RESOURCES
  2024. FREE_BLENDSEAMS_RESOURCES
  2025. memdelete(rd);
  2026. if (rcd != nullptr) {
  2027. memdelete(rcd);
  2028. }
  2029. return BAKE_OK;
  2030. }
  2031. int LightmapperRD::get_bake_texture_count() const {
  2032. return lightmap_textures.size();
  2033. }
  2034. Ref<Image> LightmapperRD::get_bake_texture(int p_index) const {
  2035. ERR_FAIL_INDEX_V(p_index, lightmap_textures.size(), Ref<Image>());
  2036. return lightmap_textures[p_index];
  2037. }
  2038. int LightmapperRD::get_shadowmask_texture_count() const {
  2039. return shadowmask_textures.size();
  2040. }
  2041. Ref<Image> LightmapperRD::get_shadowmask_texture(int p_index) const {
  2042. ERR_FAIL_INDEX_V(p_index, shadowmask_textures.size(), Ref<Image>());
  2043. return shadowmask_textures[p_index];
  2044. }
  2045. int LightmapperRD::get_bake_mesh_count() const {
  2046. return mesh_instances.size();
  2047. }
  2048. Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const {
  2049. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  2050. return mesh_instances[p_index].data.userdata;
  2051. }
  2052. Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const {
  2053. ERR_FAIL_COND_V(lightmap_textures.is_empty(), Rect2());
  2054. Rect2 uv_ofs;
  2055. Vector2 atlas_size = Vector2(lightmap_textures[0]->get_width(), lightmap_textures[0]->get_height());
  2056. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  2057. uv_ofs.size = Vector2(mesh_instances[p_index].data.albedo_on_uv2->get_width(), mesh_instances[p_index].data.albedo_on_uv2->get_height()) / atlas_size;
  2058. return uv_ofs;
  2059. }
  2060. int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const {
  2061. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  2062. return mesh_instances[p_index].slice;
  2063. }
  2064. int LightmapperRD::get_bake_probe_count() const {
  2065. return probe_positions.size();
  2066. }
  2067. Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const {
  2068. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant());
  2069. return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]);
  2070. }
  2071. Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const {
  2072. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>());
  2073. Vector<Color> ret;
  2074. ret.resize(9);
  2075. memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9);
  2076. return ret;
  2077. }
  2078. LightmapperRD::LightmapperRD() {
  2079. }