lightmapper_rd.cpp 60 KB

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