lightmapper_rd.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  1. /*************************************************************************/
  2. /* lightmapper_rd.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "lightmapper_rd.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/math/geometry_2d.h"
  33. #include "lm_blendseams.glsl.gen.h"
  34. #include "lm_compute.glsl.gen.h"
  35. #include "lm_raster.glsl.gen.h"
  36. #include "servers/rendering/rendering_device_binds.h"
  37. //uncomment this if you want to see textures from all the process saved
  38. //#define DEBUG_TEXTURES
  39. void LightmapperRD::add_mesh(const MeshData &p_mesh) {
  40. ERR_FAIL_COND(p_mesh.albedo_on_uv2.is_null() || p_mesh.albedo_on_uv2->is_empty());
  41. ERR_FAIL_COND(p_mesh.emission_on_uv2.is_null() || p_mesh.emission_on_uv2->is_empty());
  42. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_width() != p_mesh.emission_on_uv2->get_width());
  43. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_height() != p_mesh.emission_on_uv2->get_height());
  44. ERR_FAIL_COND(p_mesh.points.size() == 0);
  45. MeshInstance mi;
  46. mi.data = p_mesh;
  47. mesh_instances.push_back(mi);
  48. }
  49. void LightmapperRD::add_directional_light(bool p_static, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_angular_distance, float p_shadow_blur) {
  50. Light l;
  51. l.type = LIGHT_TYPE_DIRECTIONAL;
  52. l.direction[0] = p_direction.x;
  53. l.direction[1] = p_direction.y;
  54. l.direction[2] = p_direction.z;
  55. l.color[0] = p_color.r;
  56. l.color[1] = p_color.g;
  57. l.color[2] = p_color.b;
  58. l.energy = p_energy;
  59. l.static_bake = p_static;
  60. l.size = Math::tan(Math::deg_to_rad(p_angular_distance));
  61. l.shadow_blur = p_shadow_blur;
  62. lights.push_back(l);
  63. }
  64. void LightmapperRD::add_omni_light(bool p_static, const Vector3 &p_position, const Color &p_color, float p_energy, float p_range, float p_attenuation, float p_size, float p_shadow_blur) {
  65. Light l;
  66. l.type = LIGHT_TYPE_OMNI;
  67. l.position[0] = p_position.x;
  68. l.position[1] = p_position.y;
  69. l.position[2] = p_position.z;
  70. l.range = p_range;
  71. l.attenuation = p_attenuation;
  72. l.color[0] = p_color.r;
  73. l.color[1] = p_color.g;
  74. l.color[2] = p_color.b;
  75. l.energy = p_energy;
  76. l.static_bake = p_static;
  77. l.size = p_size;
  78. l.shadow_blur = p_shadow_blur;
  79. lights.push_back(l);
  80. }
  81. 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_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size, float p_shadow_blur) {
  82. Light l;
  83. l.type = LIGHT_TYPE_SPOT;
  84. l.position[0] = p_position.x;
  85. l.position[1] = p_position.y;
  86. l.position[2] = p_position.z;
  87. l.direction[0] = p_direction.x;
  88. l.direction[1] = p_direction.y;
  89. l.direction[2] = p_direction.z;
  90. l.range = p_range;
  91. l.attenuation = p_attenuation;
  92. l.cos_spot_angle = Math::cos(Math::deg_to_rad(p_spot_angle));
  93. l.inv_spot_attenuation = 1.0f / p_spot_attenuation;
  94. l.color[0] = p_color.r;
  95. l.color[1] = p_color.g;
  96. l.color[2] = p_color.b;
  97. l.energy = p_energy;
  98. l.static_bake = p_static;
  99. l.size = p_size;
  100. l.shadow_blur = p_shadow_blur;
  101. lights.push_back(l);
  102. }
  103. void LightmapperRD::add_probe(const Vector3 &p_position) {
  104. Probe probe;
  105. probe.position[0] = p_position.x;
  106. probe.position[1] = p_position.y;
  107. probe.position[2] = p_position.z;
  108. probe.position[3] = 0;
  109. probe_positions.push_back(probe);
  110. }
  111. 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> &triangles, uint32_t p_grid_size) {
  112. int half_size = p_size / 2;
  113. for (int i = 0; i < 8; i++) {
  114. AABB aabb = p_bounds;
  115. aabb.size *= 0.5;
  116. Vector3i n = p_ofs;
  117. if (i & 1) {
  118. aabb.position.x += aabb.size.x;
  119. n.x += half_size;
  120. }
  121. if (i & 2) {
  122. aabb.position.y += aabb.size.y;
  123. n.y += half_size;
  124. }
  125. if (i & 4) {
  126. aabb.position.z += aabb.size.z;
  127. n.z += half_size;
  128. }
  129. {
  130. Vector3 qsize = aabb.size * 0.5; //quarter size, for fast aabb test
  131. if (!Geometry3D::triangle_box_overlap(aabb.position + qsize, qsize, p_points)) {
  132. //does not fit in child, go on
  133. continue;
  134. }
  135. }
  136. if (half_size == 1) {
  137. //got to the end
  138. TriangleSort ts;
  139. ts.cell_index = n.x + (n.y * p_grid_size) + (n.z * p_grid_size * p_grid_size);
  140. ts.triangle_index = p_triangle_index;
  141. triangles.push_back(ts);
  142. } else {
  143. _plot_triangle_into_triangle_index_list(half_size, n, aabb, p_points, p_triangle_index, triangles, p_grid_size);
  144. }
  145. }
  146. }
  147. 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) {
  148. Vector<Size2i> sizes;
  149. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  150. MeshInstance &mi = mesh_instances.write[m_i];
  151. Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height());
  152. sizes.push_back(s);
  153. atlas_size.width = MAX(atlas_size.width, s.width + 2);
  154. atlas_size.height = MAX(atlas_size.height, s.height + 2);
  155. }
  156. int max = nearest_power_of_2_templated(atlas_size.width);
  157. max = MAX(max, nearest_power_of_2_templated(atlas_size.height));
  158. if (max > p_max_texture_size) {
  159. return BAKE_ERROR_LIGHTMAP_TOO_SMALL;
  160. }
  161. if (p_step_function) {
  162. p_step_function(0.1, RTR("Determining optimal atlas size"), p_bake_userdata, true);
  163. }
  164. atlas_size = Size2i(max, max);
  165. Size2i best_atlas_size;
  166. int best_atlas_slices = 0;
  167. int best_atlas_memory = 0x7FFFFFFF;
  168. Vector<Vector3i> best_atlas_offsets;
  169. //determine best texture array atlas size by bruteforce fitting
  170. while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) {
  171. Vector<Vector2i> source_sizes;
  172. Vector<int> source_indices;
  173. source_sizes.resize(sizes.size());
  174. source_indices.resize(sizes.size());
  175. for (int i = 0; i < source_indices.size(); i++) {
  176. source_sizes.write[i] = sizes[i] + Vector2i(2, 2); // Add padding between lightmaps
  177. source_indices.write[i] = i;
  178. }
  179. Vector<Vector3i> atlas_offsets;
  180. atlas_offsets.resize(source_sizes.size());
  181. int slices = 0;
  182. while (source_sizes.size() > 0) {
  183. Vector<Vector3i> offsets = Geometry2D::partial_pack_rects(source_sizes, atlas_size);
  184. Vector<int> new_indices;
  185. Vector<Vector2i> new_sources;
  186. for (int i = 0; i < offsets.size(); i++) {
  187. Vector3i ofs = offsets[i];
  188. int sidx = source_indices[i];
  189. if (ofs.z > 0) {
  190. //valid
  191. ofs.z = slices;
  192. atlas_offsets.write[sidx] = ofs + Vector3i(1, 1, 0); // Center lightmap in the reserved oversized region
  193. } else {
  194. new_indices.push_back(sidx);
  195. new_sources.push_back(source_sizes[i]);
  196. }
  197. }
  198. source_sizes = new_sources;
  199. source_indices = new_indices;
  200. slices++;
  201. }
  202. int mem_used = atlas_size.x * atlas_size.y * slices;
  203. if (mem_used < best_atlas_memory) {
  204. best_atlas_size = atlas_size;
  205. best_atlas_offsets = atlas_offsets;
  206. best_atlas_slices = slices;
  207. best_atlas_memory = mem_used;
  208. }
  209. if (atlas_size.width == atlas_size.height) {
  210. atlas_size.width *= 2;
  211. } else {
  212. atlas_size.height *= 2;
  213. }
  214. }
  215. atlas_size = best_atlas_size;
  216. atlas_slices = best_atlas_slices;
  217. // apply the offsets and slice to all images, and also blit albedo and emission
  218. albedo_images.resize(atlas_slices);
  219. emission_images.resize(atlas_slices);
  220. if (p_step_function) {
  221. p_step_function(0.2, RTR("Blitting albedo and emission"), p_bake_userdata, true);
  222. }
  223. for (int i = 0; i < atlas_slices; i++) {
  224. Ref<Image> albedo;
  225. albedo.instantiate();
  226. albedo->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);
  227. albedo->set_as_black();
  228. albedo_images.write[i] = albedo;
  229. Ref<Image> emission;
  230. emission.instantiate();
  231. emission->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);
  232. emission->set_as_black();
  233. emission_images.write[i] = emission;
  234. }
  235. //assign uv positions
  236. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  237. MeshInstance &mi = mesh_instances.write[m_i];
  238. mi.offset.x = best_atlas_offsets[m_i].x;
  239. mi.offset.y = best_atlas_offsets[m_i].y;
  240. mi.slice = best_atlas_offsets[m_i].z;
  241. albedo_images.write[mi.slice]->blit_rect(mi.data.albedo_on_uv2, Rect2i(Vector2i(), mi.data.albedo_on_uv2->get_size()), mi.offset);
  242. emission_images.write[mi.slice]->blit_rect(mi.data.emission_on_uv2, Rect2(Vector2i(), mi.data.emission_on_uv2->get_size()), mi.offset);
  243. }
  244. return BAKE_OK;
  245. }
  246. void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, Vector<Probe> &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 &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) {
  247. HashMap<Vertex, uint32_t, VertexHash> vertex_map;
  248. //fill triangles array and vertex array
  249. LocalVector<Triangle> triangles;
  250. LocalVector<Vertex> vertex_array;
  251. LocalVector<Seam> seams;
  252. slice_triangle_count.resize(atlas_slices);
  253. slice_seam_count.resize(atlas_slices);
  254. for (int i = 0; i < atlas_slices; i++) {
  255. slice_triangle_count.write[i] = 0;
  256. slice_seam_count.write[i] = 0;
  257. }
  258. bounds = AABB();
  259. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  260. if (p_step_function) {
  261. float p = float(m_i + 1) / mesh_instances.size() * 0.1;
  262. 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);
  263. }
  264. HashMap<Edge, EdgeUV2, EdgeHash> edges;
  265. MeshInstance &mi = mesh_instances.write[m_i];
  266. Vector2 uv_scale = Vector2(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()) / Vector2(atlas_size);
  267. Vector2 uv_offset = Vector2(mi.offset) / Vector2(atlas_size);
  268. if (m_i == 0) {
  269. bounds.position = mi.data.points[0];
  270. }
  271. for (int i = 0; i < mi.data.points.size(); i += 3) {
  272. Vector3 vtxs[3] = { mi.data.points[i + 0], mi.data.points[i + 1], mi.data.points[i + 2] };
  273. 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 };
  274. Vector3 normal[3] = { mi.data.normal[i + 0], mi.data.normal[i + 1], mi.data.normal[i + 2] };
  275. AABB taabb;
  276. Triangle t;
  277. t.slice = mi.slice;
  278. for (int k = 0; k < 3; k++) {
  279. bounds.expand_to(vtxs[k]);
  280. Vertex v;
  281. v.position[0] = vtxs[k].x;
  282. v.position[1] = vtxs[k].y;
  283. v.position[2] = vtxs[k].z;
  284. v.uv[0] = uvs[k].x;
  285. v.uv[1] = uvs[k].y;
  286. v.normal_xy[0] = normal[k].x;
  287. v.normal_xy[1] = normal[k].y;
  288. v.normal_z = normal[k].z;
  289. uint32_t *indexptr = vertex_map.getptr(v);
  290. if (indexptr) {
  291. t.indices[k] = *indexptr;
  292. } else {
  293. uint32_t new_index = vertex_map.size();
  294. t.indices[k] = new_index;
  295. vertex_map[v] = new_index;
  296. vertex_array.push_back(v);
  297. }
  298. if (k == 0) {
  299. taabb.position = vtxs[k];
  300. } else {
  301. taabb.expand_to(vtxs[k]);
  302. }
  303. }
  304. //compute seams that will need to be blended later
  305. for (int k = 0; k < 3; k++) {
  306. int n = (k + 1) % 3;
  307. Edge edge(vtxs[k], vtxs[n], normal[k], normal[n]);
  308. Vector2i edge_indices(t.indices[k], t.indices[n]);
  309. EdgeUV2 uv2(uvs[k], uvs[n], edge_indices);
  310. if (edge.b == edge.a) {
  311. continue; //degenerate, somehow
  312. }
  313. if (edge.b < edge.a) {
  314. SWAP(edge.a, edge.b);
  315. SWAP(edge.na, edge.nb);
  316. SWAP(uv2.a, uv2.b);
  317. SWAP(edge_indices.x, edge_indices.y);
  318. }
  319. EdgeUV2 *euv2 = edges.getptr(edge);
  320. if (!euv2) {
  321. edges[edge] = uv2;
  322. } else {
  323. if (*euv2 == uv2) {
  324. continue; // seam shared UV space, no need to blend
  325. }
  326. if (euv2->seam_found) {
  327. continue; //bad geometry
  328. }
  329. Seam seam;
  330. seam.a = edge_indices;
  331. seam.b = euv2->indices;
  332. seam.slice = mi.slice;
  333. seams.push_back(seam);
  334. slice_seam_count.write[mi.slice]++;
  335. euv2->seam_found = true;
  336. }
  337. }
  338. t.min_bounds[0] = taabb.position.x;
  339. t.min_bounds[1] = taabb.position.y;
  340. t.min_bounds[2] = taabb.position.z;
  341. t.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);
  342. t.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);
  343. t.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);
  344. t.pad0 = t.pad1 = 0; //make valgrind not complain
  345. triangles.push_back(t);
  346. slice_triangle_count.write[t.slice]++;
  347. }
  348. }
  349. //also consider probe positions for bounds
  350. for (int i = 0; i < probe_positions.size(); i++) {
  351. Vector3 pp(probe_positions[i].position[0], probe_positions[i].position[1], probe_positions[i].position[2]);
  352. bounds.expand_to(pp);
  353. }
  354. bounds.grow_by(0.1); //grow a bit to avoid numerical error
  355. triangles.sort(); //sort by slice
  356. seams.sort();
  357. if (p_step_function) {
  358. p_step_function(0.4, RTR("Optimizing acceleration structure"), p_bake_userdata, true);
  359. }
  360. //fill list of triangles in grid
  361. LocalVector<TriangleSort> triangle_sort;
  362. for (uint32_t i = 0; i < triangles.size(); i++) {
  363. const Triangle &t = triangles[i];
  364. Vector3 face[3] = {
  365. Vector3(vertex_array[t.indices[0]].position[0], vertex_array[t.indices[0]].position[1], vertex_array[t.indices[0]].position[2]),
  366. Vector3(vertex_array[t.indices[1]].position[0], vertex_array[t.indices[1]].position[1], vertex_array[t.indices[1]].position[2]),
  367. Vector3(vertex_array[t.indices[2]].position[0], vertex_array[t.indices[2]].position[1], vertex_array[t.indices[2]].position[2])
  368. };
  369. _plot_triangle_into_triangle_index_list(grid_size, Vector3i(), bounds, face, i, triangle_sort, grid_size);
  370. }
  371. //sort it
  372. triangle_sort.sort();
  373. Vector<uint32_t> triangle_indices;
  374. triangle_indices.resize(triangle_sort.size());
  375. Vector<uint32_t> grid_indices;
  376. grid_indices.resize(grid_size * grid_size * grid_size * 2);
  377. memset(grid_indices.ptrw(), 0, grid_indices.size() * sizeof(uint32_t));
  378. Vector<bool> solid;
  379. solid.resize(grid_size * grid_size * grid_size);
  380. memset(solid.ptrw(), 0, solid.size() * sizeof(bool));
  381. {
  382. uint32_t *tiw = triangle_indices.ptrw();
  383. uint32_t last_cell = 0xFFFFFFFF;
  384. uint32_t *giw = grid_indices.ptrw();
  385. bool *solidw = solid.ptrw();
  386. for (uint32_t i = 0; i < triangle_sort.size(); i++) {
  387. uint32_t cell = triangle_sort[i].cell_index;
  388. if (cell != last_cell) {
  389. //cell changed, update pointer to indices
  390. giw[cell * 2 + 1] = i;
  391. solidw[cell] = true;
  392. }
  393. tiw[i] = triangle_sort[i].triangle_index;
  394. giw[cell * 2]++; //update counter
  395. last_cell = cell;
  396. }
  397. }
  398. #if 0
  399. for (int i = 0; i < grid_size; i++) {
  400. for (int j = 0; j < grid_size; j++) {
  401. for (int k = 0; k < grid_size; k++) {
  402. uint32_t index = i * (grid_size * grid_size) + j * grid_size + k;
  403. grid_indices.write[index * 2] = float(i) / grid_size * 255;
  404. grid_indices.write[index * 2 + 1] = float(j) / grid_size * 255;
  405. }
  406. }
  407. }
  408. #endif
  409. #if 0
  410. for (int i = 0; i < grid_size; i++) {
  411. Vector<uint8_t> grid_usage;
  412. grid_usage.resize(grid_size * grid_size);
  413. for (int j = 0; j < grid_usage.size(); j++) {
  414. uint32_t ofs = i * grid_size * grid_size + j;
  415. uint32_t count = grid_indices[ofs * 2];
  416. grid_usage.write[j] = count > 0 ? 255 : 0;
  417. }
  418. Ref<Image> img;
  419. img.instantiate();
  420. img->create(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);
  421. img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png");
  422. }
  423. #endif
  424. /*****************************/
  425. /*** CREATE GPU STRUCTURES ***/
  426. /*****************************/
  427. lights.sort();
  428. Vector<Vector2i> seam_buffer_vec;
  429. seam_buffer_vec.resize(seams.size() * 2);
  430. for (uint32_t i = 0; i < seams.size(); i++) {
  431. seam_buffer_vec.write[i * 2 + 0] = seams[i].a;
  432. seam_buffer_vec.write[i * 2 + 1] = seams[i].b;
  433. }
  434. { //buffers
  435. Vector<uint8_t> vb = vertex_array.to_byte_array();
  436. vertex_buffer = rd->storage_buffer_create(vb.size(), vb);
  437. Vector<uint8_t> tb = triangles.to_byte_array();
  438. triangle_buffer = rd->storage_buffer_create(tb.size(), tb);
  439. Vector<uint8_t> tib = triangle_indices.to_byte_array();
  440. triangle_cell_indices_buffer = rd->storage_buffer_create(tib.size(), tib);
  441. Vector<uint8_t> lb = lights.to_byte_array();
  442. if (lb.size() == 0) {
  443. lb.resize(sizeof(Light)); //even if no lights, the buffer must exist
  444. }
  445. lights_buffer = rd->storage_buffer_create(lb.size(), lb);
  446. Vector<uint8_t> sb = seam_buffer_vec.to_byte_array();
  447. if (sb.size() == 0) {
  448. sb.resize(sizeof(Vector2i) * 2); //even if no seams, the buffer must exist
  449. }
  450. seams_buffer = rd->storage_buffer_create(sb.size(), sb);
  451. Vector<uint8_t> pb = probe_positions.to_byte_array();
  452. if (pb.size() == 0) {
  453. pb.resize(sizeof(Probe));
  454. }
  455. probe_positions_buffer = rd->storage_buffer_create(pb.size(), pb);
  456. }
  457. { //grid
  458. RD::TextureFormat tf;
  459. tf.width = grid_size;
  460. tf.height = grid_size;
  461. tf.depth = grid_size;
  462. tf.texture_type = RD::TEXTURE_TYPE_3D;
  463. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  464. Vector<Vector<uint8_t>> texdata;
  465. texdata.resize(1);
  466. //grid and indices
  467. tf.format = RD::DATA_FORMAT_R32G32_UINT;
  468. texdata.write[0] = grid_indices.to_byte_array();
  469. grid_texture = rd->texture_create(tf, RD::TextureView(), texdata);
  470. }
  471. }
  472. 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) {
  473. Vector<RID> framebuffers;
  474. for (int i = 0; i < atlas_slices; i++) {
  475. RID slice_pos_tex = rd->texture_create_shared_from_slice(RD::TextureView(), position_tex, i, 0);
  476. RID slice_unoc_tex = rd->texture_create_shared_from_slice(RD::TextureView(), unocclude_tex, i, 0);
  477. RID slice_norm_tex = rd->texture_create_shared_from_slice(RD::TextureView(), normal_tex, i, 0);
  478. Vector<RID> fb;
  479. fb.push_back(slice_pos_tex);
  480. fb.push_back(slice_norm_tex);
  481. fb.push_back(slice_unoc_tex);
  482. fb.push_back(raster_depth_buffer);
  483. framebuffers.push_back(rd->framebuffer_create(fb));
  484. }
  485. RD::PipelineDepthStencilState ds;
  486. ds.enable_depth_test = true;
  487. ds.enable_depth_write = true;
  488. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does render same pixel twice
  489. 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);
  490. RID raster_pipeline_wire;
  491. {
  492. RD::PipelineRasterizationState rw;
  493. rw.wireframe = true;
  494. 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);
  495. }
  496. uint32_t triangle_offset = 0;
  497. Vector<Color> clear_colors;
  498. clear_colors.push_back(Color(0, 0, 0, 0));
  499. clear_colors.push_back(Color(0, 0, 0, 0));
  500. clear_colors.push_back(Color(0, 0, 0, 0));
  501. for (int i = 0; i < atlas_slices; i++) {
  502. RasterPushConstant raster_push_constant;
  503. raster_push_constant.atlas_size[0] = atlas_size.x;
  504. raster_push_constant.atlas_size[1] = atlas_size.y;
  505. raster_push_constant.base_triangle = triangle_offset;
  506. raster_push_constant.to_cell_offset[0] = bounds.position.x;
  507. raster_push_constant.to_cell_offset[1] = bounds.position.y;
  508. raster_push_constant.to_cell_offset[2] = bounds.position.z;
  509. raster_push_constant.bias = p_bias;
  510. raster_push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  511. raster_push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  512. raster_push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  513. raster_push_constant.grid_size[0] = grid_size;
  514. raster_push_constant.grid_size[1] = grid_size;
  515. raster_push_constant.grid_size[2] = grid_size;
  516. raster_push_constant.uv_offset[0] = 0;
  517. raster_push_constant.uv_offset[1] = 0;
  518. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  519. //draw opaque
  520. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline);
  521. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  522. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  523. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  524. //draw wire
  525. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline_wire);
  526. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  527. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  528. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  529. rd->draw_list_end();
  530. triangle_offset += slice_triangle_count[i];
  531. }
  532. }
  533. 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) {
  534. Vector<RD::Uniform> uniforms;
  535. {
  536. {
  537. RD::Uniform u;
  538. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  539. u.binding = 0;
  540. u.append_id(dest_light_tex);
  541. uniforms.push_back(u);
  542. }
  543. {
  544. RD::Uniform u;
  545. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  546. u.binding = 1;
  547. u.append_id(source_light_tex);
  548. uniforms.push_back(u);
  549. }
  550. }
  551. RID compute_shader_dilate = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("dilate"));
  552. ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  553. RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate);
  554. RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_dilate, 1);
  555. RD::ComputeListID compute_list = rd->compute_list_begin();
  556. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_dilate_pipeline);
  557. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  558. rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
  559. push_constant.region_ofs[0] = 0;
  560. push_constant.region_ofs[1] = 0;
  561. Vector3i group_size((atlas_size.x - 1) / 8 + 1, (atlas_size.y - 1) / 8 + 1, 1); //restore group size
  562. for (int i = 0; i < atlas_slices; i++) {
  563. push_constant.atlas_slice = i;
  564. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  565. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  566. //no barrier, let them run all together
  567. }
  568. rd->compute_list_end();
  569. rd->free(compute_shader_dilate);
  570. #ifdef DEBUG_TEXTURES
  571. for (int i = 0; i < atlas_slices; i++) {
  572. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  573. Ref<Image> img;
  574. img.instantiate();
  575. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  576. img->convert(Image::FORMAT_RGBA8);
  577. img->save_png("res://5_dilated_" + itos(i) + ".png");
  578. }
  579. #endif
  580. return BAKE_OK;
  581. }
  582. LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_denoiser, int p_bounces, float p_bias, int p_max_texture_size, bool p_bake_sh, 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) {
  583. if (p_step_function) {
  584. p_step_function(0.0, RTR("Begin Bake"), p_bake_userdata, true);
  585. }
  586. bake_textures.clear();
  587. int grid_size = 128;
  588. /* STEP 1: Fetch material textures and compute the bounds */
  589. AABB bounds;
  590. Size2i atlas_size;
  591. int atlas_slices;
  592. Vector<Ref<Image>> albedo_images;
  593. Vector<Ref<Image>> emission_images;
  594. 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);
  595. if (bake_error != BAKE_OK) {
  596. return bake_error;
  597. }
  598. #ifdef DEBUG_TEXTURES
  599. for (int i = 0; i < atlas_slices; i++) {
  600. albedo_images[i]->save_png("res://0_albedo_" + itos(i) + ".png");
  601. emission_images[i]->save_png("res://0_emission_" + itos(i) + ".png");
  602. }
  603. #endif
  604. RenderingDevice *rd = RenderingDevice::get_singleton()->create_local_device();
  605. RID albedo_array_tex;
  606. RID emission_array_tex;
  607. RID normal_tex;
  608. RID position_tex;
  609. RID unocclude_tex;
  610. RID light_source_tex;
  611. RID light_dest_tex;
  612. RID light_accum_tex;
  613. RID light_accum_tex2;
  614. RID light_primary_dynamic_tex;
  615. RID light_environment_tex;
  616. #define FREE_TEXTURES \
  617. rd->free(albedo_array_tex); \
  618. rd->free(emission_array_tex); \
  619. rd->free(normal_tex); \
  620. rd->free(position_tex); \
  621. rd->free(unocclude_tex); \
  622. rd->free(light_source_tex); \
  623. rd->free(light_accum_tex2); \
  624. rd->free(light_accum_tex); \
  625. rd->free(light_primary_dynamic_tex); \
  626. rd->free(light_environment_tex);
  627. { // create all textures
  628. Vector<Vector<uint8_t>> albedo_data;
  629. Vector<Vector<uint8_t>> emission_data;
  630. for (int i = 0; i < atlas_slices; i++) {
  631. albedo_data.push_back(albedo_images[i]->get_data());
  632. emission_data.push_back(emission_images[i]->get_data());
  633. }
  634. RD::TextureFormat tf;
  635. tf.width = atlas_size.width;
  636. tf.height = atlas_size.height;
  637. tf.array_layers = atlas_slices;
  638. tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  639. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  640. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  641. albedo_array_tex = rd->texture_create(tf, RD::TextureView(), albedo_data);
  642. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  643. emission_array_tex = rd->texture_create(tf, RD::TextureView(), emission_data);
  644. //this will be rastered to
  645. 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;
  646. normal_tex = rd->texture_create(tf, RD::TextureView());
  647. tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  648. position_tex = rd->texture_create(tf, RD::TextureView());
  649. unocclude_tex = rd->texture_create(tf, RD::TextureView());
  650. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  651. 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;
  652. light_source_tex = rd->texture_create(tf, RD::TextureView());
  653. rd->texture_clear(light_source_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  654. light_primary_dynamic_tex = rd->texture_create(tf, RD::TextureView());
  655. rd->texture_clear(light_primary_dynamic_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  656. if (p_bake_sh) {
  657. tf.array_layers *= 4;
  658. }
  659. light_accum_tex = rd->texture_create(tf, RD::TextureView());
  660. rd->texture_clear(light_accum_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  661. light_dest_tex = rd->texture_create(tf, RD::TextureView());
  662. rd->texture_clear(light_dest_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  663. light_accum_tex2 = light_dest_tex;
  664. //env
  665. {
  666. Ref<Image> panorama_tex;
  667. if (p_environment_panorama.is_valid()) {
  668. panorama_tex = p_environment_panorama;
  669. panorama_tex->convert(Image::FORMAT_RGBAF);
  670. } else {
  671. panorama_tex.instantiate();
  672. panorama_tex->create(8, 8, false, Image::FORMAT_RGBAF);
  673. panorama_tex->fill(Color(0, 0, 0, 1));
  674. }
  675. RD::TextureFormat tfp;
  676. tfp.width = panorama_tex->get_width();
  677. tfp.height = panorama_tex->get_height();
  678. tfp.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  679. tfp.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  680. Vector<Vector<uint8_t>> tdata;
  681. tdata.push_back(panorama_tex->get_data());
  682. light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata);
  683. #ifdef DEBUG_TEXTURES
  684. panorama_tex->save_exr("res://0_panorama.exr", false);
  685. #endif
  686. }
  687. }
  688. /* STEP 2: create the acceleration structure for the GPU*/
  689. Vector<int> slice_triangle_count;
  690. RID vertex_buffer;
  691. RID triangle_buffer;
  692. RID lights_buffer;
  693. RID triangle_cell_indices_buffer;
  694. RID grid_texture;
  695. RID seams_buffer;
  696. RID probe_positions_buffer;
  697. Vector<int> slice_seam_count;
  698. #define FREE_BUFFERS \
  699. rd->free(vertex_buffer); \
  700. rd->free(triangle_buffer); \
  701. rd->free(lights_buffer); \
  702. rd->free(triangle_cell_indices_buffer); \
  703. rd->free(grid_texture); \
  704. rd->free(seams_buffer); \
  705. rd->free(probe_positions_buffer);
  706. _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, lights_buffer, triangle_cell_indices_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata);
  707. if (p_step_function) {
  708. p_step_function(0.47, RTR("Preparing shaders"), p_bake_userdata, true);
  709. }
  710. //shaders
  711. Ref<RDShaderFile> raster_shader;
  712. raster_shader.instantiate();
  713. Error err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl);
  714. if (err != OK) {
  715. raster_shader->print_errors("raster_shader");
  716. FREE_TEXTURES
  717. FREE_BUFFERS
  718. memdelete(rd);
  719. }
  720. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  721. RID rasterize_shader = rd->shader_create_from_spirv(raster_shader->get_spirv_stages());
  722. ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen
  723. RID sampler;
  724. {
  725. RD::SamplerState s;
  726. s.mag_filter = RD::SAMPLER_FILTER_LINEAR;
  727. s.min_filter = RD::SAMPLER_FILTER_LINEAR;
  728. s.max_lod = 0;
  729. sampler = rd->sampler_create(s);
  730. }
  731. Vector<RD::Uniform> base_uniforms;
  732. {
  733. {
  734. RD::Uniform u;
  735. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  736. u.binding = 1;
  737. u.append_id(vertex_buffer);
  738. base_uniforms.push_back(u);
  739. }
  740. {
  741. RD::Uniform u;
  742. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  743. u.binding = 2;
  744. u.append_id(triangle_buffer);
  745. base_uniforms.push_back(u);
  746. }
  747. {
  748. RD::Uniform u;
  749. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  750. u.binding = 3;
  751. u.append_id(triangle_cell_indices_buffer);
  752. base_uniforms.push_back(u);
  753. }
  754. {
  755. RD::Uniform u;
  756. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  757. u.binding = 4;
  758. u.append_id(lights_buffer);
  759. base_uniforms.push_back(u);
  760. }
  761. {
  762. RD::Uniform u;
  763. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  764. u.binding = 5;
  765. u.append_id(seams_buffer);
  766. base_uniforms.push_back(u);
  767. }
  768. {
  769. RD::Uniform u;
  770. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  771. u.binding = 6;
  772. u.append_id(probe_positions_buffer);
  773. base_uniforms.push_back(u);
  774. }
  775. {
  776. RD::Uniform u;
  777. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  778. u.binding = 7;
  779. u.append_id(grid_texture);
  780. base_uniforms.push_back(u);
  781. }
  782. {
  783. RD::Uniform u;
  784. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  785. u.binding = 8;
  786. u.append_id(albedo_array_tex);
  787. base_uniforms.push_back(u);
  788. }
  789. {
  790. RD::Uniform u;
  791. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  792. u.binding = 9;
  793. u.append_id(emission_array_tex);
  794. base_uniforms.push_back(u);
  795. }
  796. {
  797. RD::Uniform u;
  798. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  799. u.binding = 10;
  800. u.append_id(sampler);
  801. base_uniforms.push_back(u);
  802. }
  803. }
  804. RID raster_base_uniform = rd->uniform_set_create(base_uniforms, rasterize_shader, 0);
  805. RID raster_depth_buffer;
  806. {
  807. RD::TextureFormat tf;
  808. tf.width = atlas_size.width;
  809. tf.height = atlas_size.height;
  810. tf.depth = 1;
  811. tf.texture_type = RD::TEXTURE_TYPE_2D;
  812. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  813. tf.format = RD::DATA_FORMAT_D32_SFLOAT;
  814. raster_depth_buffer = rd->texture_create(tf, RD::TextureView());
  815. }
  816. rd->submit();
  817. rd->sync();
  818. /* STEP 3: Raster the geometry to UV2 coords in the atlas textures GPU*/
  819. _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);
  820. #ifdef DEBUG_TEXTURES
  821. for (int i = 0; i < atlas_slices; i++) {
  822. Vector<uint8_t> s = rd->texture_get_data(position_tex, i);
  823. Ref<Image> img;
  824. img.instantiate();
  825. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
  826. img->save_exr("res://1_position_" + itos(i) + ".exr", false);
  827. s = rd->texture_get_data(normal_tex, i);
  828. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  829. img->save_exr("res://1_normal_" + itos(i) + ".exr", false);
  830. }
  831. #endif
  832. #define FREE_RASTER_RESOURCES \
  833. rd->free(rasterize_shader); \
  834. rd->free(sampler); \
  835. rd->free(raster_depth_buffer);
  836. /* Plot direct light */
  837. Ref<RDShaderFile> compute_shader;
  838. compute_shader.instantiate();
  839. err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, p_bake_sh ? "\n#define USE_SH_LIGHTMAPS\n" : "");
  840. if (err != OK) {
  841. FREE_TEXTURES
  842. FREE_BUFFERS
  843. FREE_RASTER_RESOURCES
  844. memdelete(rd);
  845. compute_shader->print_errors("compute_shader");
  846. }
  847. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  848. // Unoccluder
  849. RID compute_shader_unocclude = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("unocclude"));
  850. ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  851. RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude);
  852. // Direct light
  853. RID compute_shader_primary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("primary"));
  854. ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  855. RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary);
  856. // Indirect light
  857. RID compute_shader_secondary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("secondary"));
  858. ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  859. RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary);
  860. // Light probes
  861. RID compute_shader_light_probes = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("light_probes"));
  862. ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  863. RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes);
  864. RID compute_base_uniform_set = rd->uniform_set_create(base_uniforms, compute_shader_primary, 0);
  865. #define FREE_COMPUTE_RESOURCES \
  866. rd->free(compute_shader_unocclude); \
  867. rd->free(compute_shader_primary); \
  868. rd->free(compute_shader_secondary); \
  869. rd->free(compute_shader_light_probes);
  870. PushConstant push_constant;
  871. {
  872. //set defaults
  873. push_constant.atlas_size[0] = atlas_size.width;
  874. push_constant.atlas_size[1] = atlas_size.height;
  875. push_constant.world_size[0] = bounds.size.x;
  876. push_constant.world_size[1] = bounds.size.y;
  877. push_constant.world_size[2] = bounds.size.z;
  878. push_constant.to_cell_offset[0] = bounds.position.x;
  879. push_constant.to_cell_offset[1] = bounds.position.y;
  880. push_constant.to_cell_offset[2] = bounds.position.z;
  881. push_constant.bias = p_bias;
  882. push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  883. push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  884. push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  885. push_constant.light_count = lights.size();
  886. push_constant.grid_size = grid_size;
  887. push_constant.atlas_slice = 0;
  888. push_constant.region_ofs[0] = 0;
  889. push_constant.region_ofs[1] = 0;
  890. push_constant.environment_xform[0] = p_environment_transform.rows[0][0];
  891. push_constant.environment_xform[1] = p_environment_transform.rows[1][0];
  892. push_constant.environment_xform[2] = p_environment_transform.rows[2][0];
  893. push_constant.environment_xform[3] = 0;
  894. push_constant.environment_xform[4] = p_environment_transform.rows[0][1];
  895. push_constant.environment_xform[5] = p_environment_transform.rows[1][1];
  896. push_constant.environment_xform[6] = p_environment_transform.rows[2][1];
  897. push_constant.environment_xform[7] = 0;
  898. push_constant.environment_xform[8] = p_environment_transform.rows[0][2];
  899. push_constant.environment_xform[9] = p_environment_transform.rows[1][2];
  900. push_constant.environment_xform[10] = p_environment_transform.rows[2][2];
  901. push_constant.environment_xform[11] = 0;
  902. }
  903. Vector3i group_size((atlas_size.x - 1) / 8 + 1, (atlas_size.y - 1) / 8 + 1, 1);
  904. rd->submit();
  905. rd->sync();
  906. if (p_step_function) {
  907. p_step_function(0.49, RTR("Un-occluding geometry"), p_bake_userdata, true);
  908. }
  909. /* UNOCCLUDE */
  910. {
  911. Vector<RD::Uniform> uniforms;
  912. {
  913. {
  914. RD::Uniform u;
  915. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  916. u.binding = 0;
  917. u.append_id(position_tex);
  918. uniforms.push_back(u);
  919. }
  920. {
  921. RD::Uniform u;
  922. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  923. u.binding = 1;
  924. u.append_id(unocclude_tex); //will be unused
  925. uniforms.push_back(u);
  926. }
  927. }
  928. RID unocclude_uniform_set = rd->uniform_set_create(uniforms, compute_shader_unocclude, 1);
  929. RD::ComputeListID compute_list = rd->compute_list_begin();
  930. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_unocclude_pipeline);
  931. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  932. rd->compute_list_bind_uniform_set(compute_list, unocclude_uniform_set, 1);
  933. for (int i = 0; i < atlas_slices; i++) {
  934. push_constant.atlas_slice = i;
  935. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  936. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  937. //no barrier, let them run all together
  938. }
  939. rd->compute_list_end(); //done
  940. }
  941. if (p_step_function) {
  942. p_step_function(0.5, RTR("Plot direct lighting"), p_bake_userdata, true);
  943. }
  944. /* PRIMARY (direct) LIGHT PASS */
  945. {
  946. Vector<RD::Uniform> uniforms;
  947. {
  948. {
  949. RD::Uniform u;
  950. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  951. u.binding = 0;
  952. u.append_id(light_source_tex);
  953. uniforms.push_back(u);
  954. }
  955. {
  956. RD::Uniform u;
  957. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  958. u.binding = 1;
  959. u.append_id(light_dest_tex); //will be unused
  960. uniforms.push_back(u);
  961. }
  962. {
  963. RD::Uniform u;
  964. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  965. u.binding = 2;
  966. u.append_id(position_tex);
  967. uniforms.push_back(u);
  968. }
  969. {
  970. RD::Uniform u;
  971. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  972. u.binding = 3;
  973. u.append_id(normal_tex);
  974. uniforms.push_back(u);
  975. }
  976. {
  977. RD::Uniform u;
  978. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  979. u.binding = 4;
  980. u.append_id(light_accum_tex);
  981. uniforms.push_back(u);
  982. }
  983. {
  984. RD::Uniform u;
  985. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  986. u.binding = 5;
  987. u.append_id(light_primary_dynamic_tex);
  988. uniforms.push_back(u);
  989. }
  990. }
  991. RID light_uniform_set = rd->uniform_set_create(uniforms, compute_shader_primary, 1);
  992. switch (p_quality) {
  993. case BAKE_QUALITY_LOW: {
  994. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_ray_count");
  995. } break;
  996. case BAKE_QUALITY_MEDIUM: {
  997. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_ray_count");
  998. } break;
  999. case BAKE_QUALITY_HIGH: {
  1000. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_ray_count");
  1001. } break;
  1002. case BAKE_QUALITY_ULTRA: {
  1003. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_ray_count");
  1004. } break;
  1005. }
  1006. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1007. RD::ComputeListID compute_list = rd->compute_list_begin();
  1008. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_primary_pipeline);
  1009. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1010. rd->compute_list_bind_uniform_set(compute_list, light_uniform_set, 1);
  1011. push_constant.environment_xform[11] = p_exposure_normalization;
  1012. for (int i = 0; i < atlas_slices; i++) {
  1013. push_constant.atlas_slice = i;
  1014. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1015. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1016. //no barrier, let them run all together
  1017. }
  1018. rd->compute_list_end(); //done
  1019. push_constant.environment_xform[11] = 0.0;
  1020. }
  1021. #ifdef DEBUG_TEXTURES
  1022. for (int i = 0; i < atlas_slices; i++) {
  1023. Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);
  1024. Ref<Image> img;
  1025. img.instantiate();
  1026. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1027. img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false);
  1028. }
  1029. #endif
  1030. /* SECONDARY (indirect) LIGHT PASS(ES) */
  1031. if (p_step_function) {
  1032. p_step_function(0.6, RTR("Integrate indirect lighting"), p_bake_userdata, true);
  1033. }
  1034. if (p_bounces > 0) {
  1035. Vector<RD::Uniform> uniforms;
  1036. {
  1037. {
  1038. RD::Uniform u;
  1039. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1040. u.binding = 0;
  1041. u.append_id(light_dest_tex);
  1042. uniforms.push_back(u);
  1043. }
  1044. {
  1045. RD::Uniform u;
  1046. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1047. u.binding = 1;
  1048. u.append_id(light_source_tex);
  1049. uniforms.push_back(u);
  1050. }
  1051. {
  1052. RD::Uniform u;
  1053. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1054. u.binding = 2;
  1055. u.append_id(position_tex);
  1056. uniforms.push_back(u);
  1057. }
  1058. {
  1059. RD::Uniform u;
  1060. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1061. u.binding = 3;
  1062. u.append_id(normal_tex);
  1063. uniforms.push_back(u);
  1064. }
  1065. {
  1066. RD::Uniform u;
  1067. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1068. u.binding = 4;
  1069. u.append_id(light_accum_tex);
  1070. uniforms.push_back(u);
  1071. }
  1072. {
  1073. RD::Uniform u;
  1074. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1075. u.binding = 5;
  1076. u.append_id(unocclude_tex); //reuse unocclude tex
  1077. uniforms.push_back(u);
  1078. }
  1079. {
  1080. RD::Uniform u;
  1081. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1082. u.binding = 6;
  1083. u.append_id(light_environment_tex);
  1084. uniforms.push_back(u);
  1085. }
  1086. }
  1087. RID secondary_uniform_set[2];
  1088. secondary_uniform_set[0] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
  1089. uniforms.write[0].set_id(0, light_source_tex);
  1090. uniforms.write[1].set_id(0, light_dest_tex);
  1091. secondary_uniform_set[1] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
  1092. int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));
  1093. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass");
  1094. int x_regions = (atlas_size.width - 1) / max_region_size + 1;
  1095. int y_regions = (atlas_size.height - 1) / max_region_size + 1;
  1096. int ray_iterations = (push_constant.ray_count - 1) / max_rays + 1;
  1097. rd->submit();
  1098. rd->sync();
  1099. for (int b = 0; b < p_bounces; b++) {
  1100. int count = 0;
  1101. if (b > 0) {
  1102. SWAP(light_source_tex, light_dest_tex);
  1103. SWAP(secondary_uniform_set[0], secondary_uniform_set[1]);
  1104. }
  1105. for (int s = 0; s < atlas_slices; s++) {
  1106. push_constant.atlas_slice = s;
  1107. for (int i = 0; i < x_regions; i++) {
  1108. for (int j = 0; j < y_regions; j++) {
  1109. int x = i * max_region_size;
  1110. int y = j * max_region_size;
  1111. int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
  1112. int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
  1113. push_constant.region_ofs[0] = x;
  1114. push_constant.region_ofs[1] = y;
  1115. group_size = Vector3i((w - 1) / 8 + 1, (h - 1) / 8 + 1, 1);
  1116. for (int k = 0; k < ray_iterations; k++) {
  1117. RD::ComputeListID compute_list = rd->compute_list_begin();
  1118. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline);
  1119. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1120. rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set[0], 1);
  1121. push_constant.ray_from = k * max_rays;
  1122. push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count));
  1123. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1124. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1125. rd->compute_list_end(); //done
  1126. rd->submit();
  1127. rd->sync();
  1128. count++;
  1129. if (p_step_function) {
  1130. int total = (atlas_slices * x_regions * y_regions * ray_iterations);
  1131. int percent = count * 100 / total;
  1132. float p = float(count) / total * 0.1;
  1133. p_step_function(0.6 + p, vformat(RTR("Bounce %d/%d: Integrate indirect lighting %d%%"), b + 1, p_bounces, percent), p_bake_userdata, false);
  1134. }
  1135. }
  1136. }
  1137. }
  1138. }
  1139. if (b == 0) {
  1140. // This disables the environment for subsequent bounces
  1141. push_constant.environment_xform[3] = -99.0f;
  1142. }
  1143. }
  1144. // Restore the correct environment transform
  1145. push_constant.environment_xform[3] = 0.0f;
  1146. }
  1147. /* LIGHTPROBES */
  1148. RID light_probe_buffer;
  1149. if (probe_positions.size()) {
  1150. light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size());
  1151. if (p_step_function) {
  1152. p_step_function(0.7, RTR("Baking lightprobes"), p_bake_userdata, true);
  1153. }
  1154. Vector<RD::Uniform> uniforms;
  1155. {
  1156. {
  1157. RD::Uniform u;
  1158. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1159. u.binding = 0;
  1160. u.append_id(light_probe_buffer);
  1161. uniforms.push_back(u);
  1162. }
  1163. {
  1164. RD::Uniform u;
  1165. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1166. u.binding = 1;
  1167. u.append_id(light_dest_tex);
  1168. uniforms.push_back(u);
  1169. }
  1170. {
  1171. RD::Uniform u;
  1172. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1173. u.binding = 2;
  1174. u.append_id(light_primary_dynamic_tex);
  1175. uniforms.push_back(u);
  1176. }
  1177. {
  1178. RD::Uniform u;
  1179. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1180. u.binding = 3;
  1181. u.append_id(light_environment_tex);
  1182. uniforms.push_back(u);
  1183. }
  1184. }
  1185. RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1);
  1186. switch (p_quality) {
  1187. case BAKE_QUALITY_LOW: {
  1188. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_probe_ray_count");
  1189. } break;
  1190. case BAKE_QUALITY_MEDIUM: {
  1191. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_probe_ray_count");
  1192. } break;
  1193. case BAKE_QUALITY_HIGH: {
  1194. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_probe_ray_count");
  1195. } break;
  1196. case BAKE_QUALITY_ULTRA: {
  1197. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count");
  1198. } break;
  1199. }
  1200. push_constant.atlas_size[0] = probe_positions.size();
  1201. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1202. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass");
  1203. int ray_iterations = (push_constant.ray_count - 1) / max_rays + 1;
  1204. for (int i = 0; i < ray_iterations; i++) {
  1205. RD::ComputeListID compute_list = rd->compute_list_begin();
  1206. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline);
  1207. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1208. rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1);
  1209. push_constant.ray_from = i * max_rays;
  1210. push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count));
  1211. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1212. rd->compute_list_dispatch(compute_list, (probe_positions.size() - 1) / 64 + 1, 1, 1);
  1213. rd->compute_list_end(); //done
  1214. rd->submit();
  1215. rd->sync();
  1216. if (p_step_function) {
  1217. int percent = i * 100 / ray_iterations;
  1218. float p = float(i) / ray_iterations * 0.1;
  1219. p_step_function(0.7 + p, vformat(RTR("Integrating light probes %d%%"), percent), p_bake_userdata, false);
  1220. }
  1221. }
  1222. push_constant.atlas_size[0] = atlas_size.x; //restore
  1223. }
  1224. #if 0
  1225. for (int i = 0; i < probe_positions.size(); i++) {
  1226. Ref<Image> img;
  1227. img.instantiate();
  1228. img->create(6, 4, false, Image::FORMAT_RGB8);
  1229. for (int j = 0; j < 6; j++) {
  1230. Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);
  1231. Ref<Image> img2;
  1232. img2.instantiate();
  1233. img2->create(2, 2, false, Image::FORMAT_RGBAF, s);
  1234. img2->convert(Image::FORMAT_RGB8);
  1235. img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2));
  1236. }
  1237. img->save_png("res://3_light_probe_" + itos(i) + ".png");
  1238. }
  1239. #endif
  1240. {
  1241. SWAP(light_accum_tex, light_accum_tex2);
  1242. 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));
  1243. if (unlikely(error != BAKE_OK)) {
  1244. return error;
  1245. }
  1246. }
  1247. /* DENOISE */
  1248. if (p_use_denoiser) {
  1249. if (p_step_function) {
  1250. p_step_function(0.8, RTR("Denoising"), p_bake_userdata, true);
  1251. }
  1252. Ref<LightmapDenoiser> denoiser = LightmapDenoiser::create();
  1253. if (denoiser.is_valid()) {
  1254. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1255. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1256. Ref<Image> img;
  1257. img.instantiate();
  1258. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1259. Ref<Image> denoised = denoiser->denoise_image(img);
  1260. if (denoised != img) {
  1261. denoised->convert(Image::FORMAT_RGBAH);
  1262. Vector<uint8_t> ds = denoised->get_data();
  1263. denoised.unref(); //avoid copy on write
  1264. { //restore alpha
  1265. uint32_t count = s.size() / 2; //uint16s
  1266. const uint16_t *src = (const uint16_t *)s.ptr();
  1267. uint16_t *dst = (uint16_t *)ds.ptrw();
  1268. for (uint32_t j = 0; j < count; j += 4) {
  1269. dst[j + 3] = src[j + 3];
  1270. }
  1271. }
  1272. rd->texture_update(light_accum_tex, i, ds);
  1273. }
  1274. }
  1275. }
  1276. {
  1277. SWAP(light_accum_tex, light_accum_tex2);
  1278. 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));
  1279. if (unlikely(error != BAKE_OK)) {
  1280. return error;
  1281. }
  1282. }
  1283. }
  1284. #ifdef DEBUG_TEXTURES
  1285. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1286. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1287. Ref<Image> img;
  1288. img.instantiate();
  1289. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1290. img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false);
  1291. }
  1292. #endif
  1293. /* BLEND SEAMS */
  1294. //shaders
  1295. Ref<RDShaderFile> blendseams_shader;
  1296. blendseams_shader.instantiate();
  1297. err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl);
  1298. if (err != OK) {
  1299. FREE_TEXTURES
  1300. FREE_BUFFERS
  1301. FREE_RASTER_RESOURCES
  1302. FREE_COMPUTE_RESOURCES
  1303. memdelete(rd);
  1304. blendseams_shader->print_errors("blendseams_shader");
  1305. }
  1306. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1307. RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines"));
  1308. ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1309. RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles"));
  1310. ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1311. #define FREE_BLENDSEAMS_RESOURCES \
  1312. rd->free(blendseams_line_raster_shader); \
  1313. rd->free(blendseams_triangle_raster_shader);
  1314. {
  1315. //pre copy
  1316. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1317. rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i);
  1318. }
  1319. Vector<RID> framebuffers;
  1320. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1321. RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0);
  1322. Vector<RID> fb;
  1323. fb.push_back(slice_tex);
  1324. fb.push_back(raster_depth_buffer);
  1325. framebuffers.push_back(rd->framebuffer_create(fb));
  1326. }
  1327. Vector<RD::Uniform> uniforms;
  1328. {
  1329. {
  1330. RD::Uniform u;
  1331. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1332. u.binding = 0;
  1333. u.append_id(light_accum_tex2);
  1334. uniforms.push_back(u);
  1335. }
  1336. }
  1337. RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1);
  1338. bool debug = false;
  1339. RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1);
  1340. bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
  1341. bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1342. RD::PipelineDepthStencilState ds;
  1343. ds.enable_depth_test = true;
  1344. ds.enable_depth_write = true;
  1345. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending
  1346. 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);
  1347. 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);
  1348. uint32_t seam_offset = 0;
  1349. uint32_t triangle_offset = 0;
  1350. Vector<Color> clear_colors;
  1351. clear_colors.push_back(Color(0, 0, 0, 1));
  1352. for (int i = 0; i < atlas_slices; i++) {
  1353. int subslices = (p_bake_sh ? 4 : 1);
  1354. if (slice_seam_count[i] == 0) {
  1355. continue;
  1356. }
  1357. for (int k = 0; k < subslices; k++) {
  1358. RasterSeamsPushConstant seams_push_constant;
  1359. seams_push_constant.slice = uint32_t(i * subslices + k);
  1360. seams_push_constant.debug = debug;
  1361. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  1362. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  1363. rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1);
  1364. const int uv_offset_count = 9;
  1365. static const Vector3 uv_offsets[uv_offset_count] = {
  1366. Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards
  1367. Vector3(0, 1, 0.2),
  1368. Vector3(0, -1, 0.2),
  1369. Vector3(1, 0, 0.2),
  1370. Vector3(-1, 0, 0.2),
  1371. Vector3(-1, -1, 0.1),
  1372. Vector3(1, -1, 0.1),
  1373. Vector3(1, 1, 0.1),
  1374. Vector3(-1, 1, 0.1),
  1375. };
  1376. /* step 1 use lines to blend the edges */
  1377. {
  1378. seams_push_constant.base_index = seam_offset;
  1379. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1380. seams_push_constant.uv_offset[0] = uv_offsets[0].x / float(atlas_size.width);
  1381. seams_push_constant.uv_offset[1] = uv_offsets[0].y / float(atlas_size.height);
  1382. seams_push_constant.blend = uv_offsets[0].z;
  1383. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1384. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1385. }
  1386. /* step 2 use triangles to mask the interior */
  1387. {
  1388. seams_push_constant.base_index = triangle_offset;
  1389. rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline);
  1390. seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask
  1391. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1392. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  1393. }
  1394. /* step 3 blend around the triangle */
  1395. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1396. for (int j = 1; j < uv_offset_count; j++) {
  1397. seams_push_constant.base_index = seam_offset;
  1398. seams_push_constant.uv_offset[0] = uv_offsets[j].x / float(atlas_size.width);
  1399. seams_push_constant.uv_offset[1] = uv_offsets[j].y / float(atlas_size.height);
  1400. seams_push_constant.blend = uv_offsets[0].z;
  1401. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1402. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1403. }
  1404. rd->draw_list_end();
  1405. }
  1406. seam_offset += slice_seam_count[i];
  1407. triangle_offset += slice_triangle_count[i];
  1408. }
  1409. }
  1410. #ifdef DEBUG_TEXTURES
  1411. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1412. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1413. Ref<Image> img;
  1414. img.instantiate();
  1415. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1416. img->save_exr("res://5_blendseams" + itos(i) + ".exr", false);
  1417. }
  1418. #endif
  1419. if (p_step_function) {
  1420. p_step_function(0.9, RTR("Retrieving textures"), p_bake_userdata, true);
  1421. }
  1422. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1423. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1424. Ref<Image> img;
  1425. img.instantiate();
  1426. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1427. img->convert(Image::FORMAT_RGBH); //remove alpha
  1428. bake_textures.push_back(img);
  1429. }
  1430. if (probe_positions.size() > 0) {
  1431. probe_values.resize(probe_positions.size() * 9);
  1432. Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer);
  1433. memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size());
  1434. rd->free(light_probe_buffer);
  1435. #ifdef DEBUG_TEXTURES
  1436. {
  1437. Ref<Image> img2;
  1438. img2.instantiate();
  1439. img2->create(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
  1440. img2->save_exr("res://6_lightprobes.exr", false);
  1441. }
  1442. #endif
  1443. }
  1444. FREE_TEXTURES
  1445. FREE_BUFFERS
  1446. FREE_RASTER_RESOURCES
  1447. FREE_COMPUTE_RESOURCES
  1448. FREE_BLENDSEAMS_RESOURCES
  1449. memdelete(rd);
  1450. return BAKE_OK;
  1451. }
  1452. int LightmapperRD::get_bake_texture_count() const {
  1453. return bake_textures.size();
  1454. }
  1455. Ref<Image> LightmapperRD::get_bake_texture(int p_index) const {
  1456. ERR_FAIL_INDEX_V(p_index, bake_textures.size(), Ref<Image>());
  1457. return bake_textures[p_index];
  1458. }
  1459. int LightmapperRD::get_bake_mesh_count() const {
  1460. return mesh_instances.size();
  1461. }
  1462. Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const {
  1463. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1464. return mesh_instances[p_index].data.userdata;
  1465. }
  1466. Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const {
  1467. ERR_FAIL_COND_V(bake_textures.size() == 0, Rect2());
  1468. Rect2 uv_ofs;
  1469. Vector2 atlas_size = Vector2(bake_textures[0]->get_width(), bake_textures[0]->get_height());
  1470. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  1471. 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;
  1472. return uv_ofs;
  1473. }
  1474. int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const {
  1475. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1476. return mesh_instances[p_index].slice;
  1477. }
  1478. int LightmapperRD::get_bake_probe_count() const {
  1479. return probe_positions.size();
  1480. }
  1481. Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const {
  1482. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant());
  1483. return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]);
  1484. }
  1485. Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const {
  1486. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>());
  1487. Vector<Color> ret;
  1488. ret.resize(9);
  1489. memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9);
  1490. return ret;
  1491. }
  1492. LightmapperRD::LightmapperRD() {
  1493. }