lightmapper_rd.cpp 58 KB

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