lightmapper_rd.cpp 69 KB

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