lightmapper_rd.cpp 60 KB

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