lightmapper_rd.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  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::deg2rad(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::deg2rad(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) {
  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. for (int i = 0; i < atlas_slices; i++) {
  1012. push_constant.atlas_slice = i;
  1013. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1014. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1015. //no barrier, let them run all together
  1016. }
  1017. rd->compute_list_end(); //done
  1018. }
  1019. #ifdef DEBUG_TEXTURES
  1020. for (int i = 0; i < atlas_slices; i++) {
  1021. Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);
  1022. Ref<Image> img;
  1023. img.instantiate();
  1024. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1025. img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false);
  1026. }
  1027. #endif
  1028. /* SECONDARY (indirect) LIGHT PASS(ES) */
  1029. if (p_step_function) {
  1030. p_step_function(0.6, RTR("Integrate indirect lighting"), p_bake_userdata, true);
  1031. }
  1032. if (p_bounces > 0) {
  1033. Vector<RD::Uniform> uniforms;
  1034. {
  1035. {
  1036. RD::Uniform u;
  1037. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1038. u.binding = 0;
  1039. u.append_id(light_dest_tex);
  1040. uniforms.push_back(u);
  1041. }
  1042. {
  1043. RD::Uniform u;
  1044. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1045. u.binding = 1;
  1046. u.append_id(light_source_tex);
  1047. uniforms.push_back(u);
  1048. }
  1049. {
  1050. RD::Uniform u;
  1051. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1052. u.binding = 2;
  1053. u.append_id(position_tex);
  1054. uniforms.push_back(u);
  1055. }
  1056. {
  1057. RD::Uniform u;
  1058. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1059. u.binding = 3;
  1060. u.append_id(normal_tex);
  1061. uniforms.push_back(u);
  1062. }
  1063. {
  1064. RD::Uniform u;
  1065. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1066. u.binding = 4;
  1067. u.append_id(light_accum_tex);
  1068. uniforms.push_back(u);
  1069. }
  1070. {
  1071. RD::Uniform u;
  1072. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1073. u.binding = 5;
  1074. u.append_id(unocclude_tex); //reuse unocclude tex
  1075. uniforms.push_back(u);
  1076. }
  1077. {
  1078. RD::Uniform u;
  1079. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1080. u.binding = 6;
  1081. u.append_id(light_environment_tex);
  1082. uniforms.push_back(u);
  1083. }
  1084. }
  1085. RID secondary_uniform_set[2];
  1086. secondary_uniform_set[0] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
  1087. uniforms.write[0].set_id(0, light_source_tex);
  1088. uniforms.write[1].set_id(0, light_dest_tex);
  1089. secondary_uniform_set[1] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
  1090. int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));
  1091. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass");
  1092. int x_regions = (atlas_size.width - 1) / max_region_size + 1;
  1093. int y_regions = (atlas_size.height - 1) / max_region_size + 1;
  1094. int ray_iterations = (push_constant.ray_count - 1) / max_rays + 1;
  1095. rd->submit();
  1096. rd->sync();
  1097. for (int b = 0; b < p_bounces; b++) {
  1098. int count = 0;
  1099. if (b > 0) {
  1100. SWAP(light_source_tex, light_dest_tex);
  1101. SWAP(secondary_uniform_set[0], secondary_uniform_set[1]);
  1102. }
  1103. for (int s = 0; s < atlas_slices; s++) {
  1104. push_constant.atlas_slice = s;
  1105. for (int i = 0; i < x_regions; i++) {
  1106. for (int j = 0; j < y_regions; j++) {
  1107. int x = i * max_region_size;
  1108. int y = j * max_region_size;
  1109. int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
  1110. int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
  1111. push_constant.region_ofs[0] = x;
  1112. push_constant.region_ofs[1] = y;
  1113. group_size = Vector3i((w - 1) / 8 + 1, (h - 1) / 8 + 1, 1);
  1114. for (int k = 0; k < ray_iterations; k++) {
  1115. RD::ComputeListID compute_list = rd->compute_list_begin();
  1116. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline);
  1117. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1118. rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set[0], 1);
  1119. push_constant.ray_from = k * max_rays;
  1120. push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count));
  1121. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1122. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1123. rd->compute_list_end(); //done
  1124. rd->submit();
  1125. rd->sync();
  1126. count++;
  1127. if (p_step_function) {
  1128. int total = (atlas_slices * x_regions * y_regions * ray_iterations);
  1129. int percent = count * 100 / total;
  1130. float p = float(count) / total * 0.1;
  1131. p_step_function(0.6 + p, vformat(RTR("Bounce %d/%d: Integrate indirect lighting %d%%"), b + 1, p_bounces, percent), p_bake_userdata, false);
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. if (b == 0) {
  1138. // This disables the environment for subsequent bounces
  1139. push_constant.environment_xform[3] = -99.0f;
  1140. }
  1141. }
  1142. // Restore the correct environment transform
  1143. push_constant.environment_xform[3] = 0.0f;
  1144. }
  1145. /* LIGHTPROBES */
  1146. RID light_probe_buffer;
  1147. if (probe_positions.size()) {
  1148. light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size());
  1149. if (p_step_function) {
  1150. p_step_function(0.7, RTR("Baking lightprobes"), p_bake_userdata, true);
  1151. }
  1152. Vector<RD::Uniform> uniforms;
  1153. {
  1154. {
  1155. RD::Uniform u;
  1156. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1157. u.binding = 0;
  1158. u.append_id(light_probe_buffer);
  1159. uniforms.push_back(u);
  1160. }
  1161. {
  1162. RD::Uniform u;
  1163. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1164. u.binding = 1;
  1165. u.append_id(light_dest_tex);
  1166. uniforms.push_back(u);
  1167. }
  1168. {
  1169. RD::Uniform u;
  1170. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1171. u.binding = 2;
  1172. u.append_id(light_primary_dynamic_tex);
  1173. uniforms.push_back(u);
  1174. }
  1175. {
  1176. RD::Uniform u;
  1177. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1178. u.binding = 3;
  1179. u.append_id(light_environment_tex);
  1180. uniforms.push_back(u);
  1181. }
  1182. }
  1183. RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1);
  1184. switch (p_quality) {
  1185. case BAKE_QUALITY_LOW: {
  1186. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_probe_ray_count");
  1187. } break;
  1188. case BAKE_QUALITY_MEDIUM: {
  1189. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_probe_ray_count");
  1190. } break;
  1191. case BAKE_QUALITY_HIGH: {
  1192. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_probe_ray_count");
  1193. } break;
  1194. case BAKE_QUALITY_ULTRA: {
  1195. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count");
  1196. } break;
  1197. }
  1198. push_constant.atlas_size[0] = probe_positions.size();
  1199. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1200. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass");
  1201. int ray_iterations = (push_constant.ray_count - 1) / max_rays + 1;
  1202. for (int i = 0; i < ray_iterations; i++) {
  1203. RD::ComputeListID compute_list = rd->compute_list_begin();
  1204. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline);
  1205. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1206. rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1);
  1207. push_constant.ray_from = i * max_rays;
  1208. push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count));
  1209. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1210. rd->compute_list_dispatch(compute_list, (probe_positions.size() - 1) / 64 + 1, 1, 1);
  1211. rd->compute_list_end(); //done
  1212. rd->submit();
  1213. rd->sync();
  1214. if (p_step_function) {
  1215. int percent = i * 100 / ray_iterations;
  1216. float p = float(i) / ray_iterations * 0.1;
  1217. p_step_function(0.7 + p, vformat(RTR("Integrating light probes %d%%"), percent), p_bake_userdata, false);
  1218. }
  1219. }
  1220. push_constant.atlas_size[0] = atlas_size.x; //restore
  1221. }
  1222. #if 0
  1223. for (int i = 0; i < probe_positions.size(); i++) {
  1224. Ref<Image> img;
  1225. img.instantiate();
  1226. img->create(6, 4, false, Image::FORMAT_RGB8);
  1227. for (int j = 0; j < 6; j++) {
  1228. Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);
  1229. Ref<Image> img2;
  1230. img2.instantiate();
  1231. img2->create(2, 2, false, Image::FORMAT_RGBAF, s);
  1232. img2->convert(Image::FORMAT_RGB8);
  1233. img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2));
  1234. }
  1235. img->save_png("res://3_light_probe_" + itos(i) + ".png");
  1236. }
  1237. #endif
  1238. {
  1239. SWAP(light_accum_tex, light_accum_tex2);
  1240. 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));
  1241. if (unlikely(error != BAKE_OK)) {
  1242. return error;
  1243. }
  1244. }
  1245. /* DENOISE */
  1246. if (p_use_denoiser) {
  1247. if (p_step_function) {
  1248. p_step_function(0.8, RTR("Denoising"), p_bake_userdata, true);
  1249. }
  1250. Ref<LightmapDenoiser> denoiser = LightmapDenoiser::create();
  1251. if (denoiser.is_valid()) {
  1252. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1253. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1254. Ref<Image> img;
  1255. img.instantiate();
  1256. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1257. Ref<Image> denoised = denoiser->denoise_image(img);
  1258. if (denoised != img) {
  1259. denoised->convert(Image::FORMAT_RGBAH);
  1260. Vector<uint8_t> ds = denoised->get_data();
  1261. denoised.unref(); //avoid copy on write
  1262. { //restore alpha
  1263. uint32_t count = s.size() / 2; //uint16s
  1264. const uint16_t *src = (const uint16_t *)s.ptr();
  1265. uint16_t *dst = (uint16_t *)ds.ptrw();
  1266. for (uint32_t j = 0; j < count; j += 4) {
  1267. dst[j + 3] = src[j + 3];
  1268. }
  1269. }
  1270. rd->texture_update(light_accum_tex, i, ds);
  1271. }
  1272. }
  1273. }
  1274. {
  1275. SWAP(light_accum_tex, light_accum_tex2);
  1276. 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));
  1277. if (unlikely(error != BAKE_OK)) {
  1278. return error;
  1279. }
  1280. }
  1281. }
  1282. #ifdef DEBUG_TEXTURES
  1283. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1284. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1285. Ref<Image> img;
  1286. img.instantiate();
  1287. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1288. img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false);
  1289. }
  1290. #endif
  1291. /* BLEND SEAMS */
  1292. //shaders
  1293. Ref<RDShaderFile> blendseams_shader;
  1294. blendseams_shader.instantiate();
  1295. err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl);
  1296. if (err != OK) {
  1297. FREE_TEXTURES
  1298. FREE_BUFFERS
  1299. FREE_RASTER_RESOURCES
  1300. FREE_COMPUTE_RESOURCES
  1301. memdelete(rd);
  1302. blendseams_shader->print_errors("blendseams_shader");
  1303. }
  1304. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1305. RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines"));
  1306. ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1307. RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles"));
  1308. ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1309. #define FREE_BLENDSEAMS_RESOURCES \
  1310. rd->free(blendseams_line_raster_shader); \
  1311. rd->free(blendseams_triangle_raster_shader);
  1312. {
  1313. //pre copy
  1314. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1315. rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i);
  1316. }
  1317. Vector<RID> framebuffers;
  1318. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1319. RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0);
  1320. Vector<RID> fb;
  1321. fb.push_back(slice_tex);
  1322. fb.push_back(raster_depth_buffer);
  1323. framebuffers.push_back(rd->framebuffer_create(fb));
  1324. }
  1325. Vector<RD::Uniform> uniforms;
  1326. {
  1327. {
  1328. RD::Uniform u;
  1329. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1330. u.binding = 0;
  1331. u.append_id(light_accum_tex2);
  1332. uniforms.push_back(u);
  1333. }
  1334. }
  1335. RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1);
  1336. bool debug = false;
  1337. RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1);
  1338. bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
  1339. bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1340. RD::PipelineDepthStencilState ds;
  1341. ds.enable_depth_test = true;
  1342. ds.enable_depth_write = true;
  1343. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending
  1344. 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);
  1345. 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);
  1346. uint32_t seam_offset = 0;
  1347. uint32_t triangle_offset = 0;
  1348. Vector<Color> clear_colors;
  1349. clear_colors.push_back(Color(0, 0, 0, 1));
  1350. for (int i = 0; i < atlas_slices; i++) {
  1351. int subslices = (p_bake_sh ? 4 : 1);
  1352. if (slice_seam_count[i] == 0) {
  1353. continue;
  1354. }
  1355. for (int k = 0; k < subslices; k++) {
  1356. RasterSeamsPushConstant seams_push_constant;
  1357. seams_push_constant.slice = uint32_t(i * subslices + k);
  1358. seams_push_constant.debug = debug;
  1359. 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);
  1360. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  1361. rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1);
  1362. const int uv_offset_count = 9;
  1363. static const Vector3 uv_offsets[uv_offset_count] = {
  1364. Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards
  1365. Vector3(0, 1, 0.2),
  1366. Vector3(0, -1, 0.2),
  1367. Vector3(1, 0, 0.2),
  1368. Vector3(-1, 0, 0.2),
  1369. Vector3(-1, -1, 0.1),
  1370. Vector3(1, -1, 0.1),
  1371. Vector3(1, 1, 0.1),
  1372. Vector3(-1, 1, 0.1),
  1373. };
  1374. /* step 1 use lines to blend the edges */
  1375. {
  1376. seams_push_constant.base_index = seam_offset;
  1377. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1378. seams_push_constant.uv_offset[0] = uv_offsets[0].x / float(atlas_size.width);
  1379. seams_push_constant.uv_offset[1] = uv_offsets[0].y / float(atlas_size.height);
  1380. seams_push_constant.blend = uv_offsets[0].z;
  1381. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1382. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1383. }
  1384. /* step 2 use triangles to mask the interior */
  1385. {
  1386. seams_push_constant.base_index = triangle_offset;
  1387. rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline);
  1388. seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask
  1389. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1390. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  1391. }
  1392. /* step 3 blend around the triangle */
  1393. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1394. for (int j = 1; j < uv_offset_count; j++) {
  1395. seams_push_constant.base_index = seam_offset;
  1396. seams_push_constant.uv_offset[0] = uv_offsets[j].x / float(atlas_size.width);
  1397. seams_push_constant.uv_offset[1] = uv_offsets[j].y / float(atlas_size.height);
  1398. seams_push_constant.blend = uv_offsets[0].z;
  1399. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1400. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1401. }
  1402. rd->draw_list_end();
  1403. }
  1404. seam_offset += slice_seam_count[i];
  1405. triangle_offset += slice_triangle_count[i];
  1406. }
  1407. }
  1408. #ifdef DEBUG_TEXTURES
  1409. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1410. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1411. Ref<Image> img;
  1412. img.instantiate();
  1413. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1414. img->save_exr("res://5_blendseams" + itos(i) + ".exr", false);
  1415. }
  1416. #endif
  1417. if (p_step_function) {
  1418. p_step_function(0.9, RTR("Retrieving textures"), p_bake_userdata, true);
  1419. }
  1420. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1421. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1422. Ref<Image> img;
  1423. img.instantiate();
  1424. img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1425. img->convert(Image::FORMAT_RGBH); //remove alpha
  1426. bake_textures.push_back(img);
  1427. }
  1428. if (probe_positions.size() > 0) {
  1429. probe_values.resize(probe_positions.size() * 9);
  1430. Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer);
  1431. memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size());
  1432. rd->free(light_probe_buffer);
  1433. #ifdef DEBUG_TEXTURES
  1434. {
  1435. Ref<Image> img2;
  1436. img2.instantiate();
  1437. img2->create(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
  1438. img2->save_exr("res://6_lightprobes.exr", false);
  1439. }
  1440. #endif
  1441. }
  1442. FREE_TEXTURES
  1443. FREE_BUFFERS
  1444. FREE_RASTER_RESOURCES
  1445. FREE_COMPUTE_RESOURCES
  1446. FREE_BLENDSEAMS_RESOURCES
  1447. memdelete(rd);
  1448. return BAKE_OK;
  1449. }
  1450. int LightmapperRD::get_bake_texture_count() const {
  1451. return bake_textures.size();
  1452. }
  1453. Ref<Image> LightmapperRD::get_bake_texture(int p_index) const {
  1454. ERR_FAIL_INDEX_V(p_index, bake_textures.size(), Ref<Image>());
  1455. return bake_textures[p_index];
  1456. }
  1457. int LightmapperRD::get_bake_mesh_count() const {
  1458. return mesh_instances.size();
  1459. }
  1460. Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const {
  1461. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1462. return mesh_instances[p_index].data.userdata;
  1463. }
  1464. Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const {
  1465. ERR_FAIL_COND_V(bake_textures.size() == 0, Rect2());
  1466. Rect2 uv_ofs;
  1467. Vector2 atlas_size = Vector2(bake_textures[0]->get_width(), bake_textures[0]->get_height());
  1468. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  1469. 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;
  1470. return uv_ofs;
  1471. }
  1472. int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const {
  1473. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1474. return mesh_instances[p_index].slice;
  1475. }
  1476. int LightmapperRD::get_bake_probe_count() const {
  1477. return probe_positions.size();
  1478. }
  1479. Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const {
  1480. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant());
  1481. return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]);
  1482. }
  1483. Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const {
  1484. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>());
  1485. Vector<Color> ret;
  1486. ret.resize(9);
  1487. memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9);
  1488. return ret;
  1489. }
  1490. LightmapperRD::LightmapperRD() {
  1491. }