lightmapper_rd.cpp 74 KB

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