lightmapper_rd.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356
  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/string/print_string.h"
  32. #include "lm_blendseams.glsl.gen.h"
  33. #include "lm_compute.glsl.gen.h"
  34. #include "lm_raster.glsl.gen.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/io/dir_access.h"
  37. #include "core/math/geometry_2d.h"
  38. #include "editor/editor_paths.h"
  39. #include "editor/editor_settings.h"
  40. #include "servers/rendering/rendering_device_binds.h"
  41. #include "servers/rendering/rendering_server_globals.h"
  42. #if defined(VULKAN_ENABLED)
  43. #include "drivers/vulkan/rendering_context_driver_vulkan.h"
  44. #endif
  45. #if defined(METAL_ENABLED)
  46. #include "drivers/metal/rendering_context_driver_metal.h"
  47. #endif
  48. //uncomment this if you want to see textures from all the process saved
  49. //#define DEBUG_TEXTURES
  50. void LightmapperRD::add_mesh(const MeshData &p_mesh) {
  51. ERR_FAIL_COND(p_mesh.albedo_on_uv2.is_null() || p_mesh.albedo_on_uv2->is_empty());
  52. ERR_FAIL_COND(p_mesh.emission_on_uv2.is_null() || p_mesh.emission_on_uv2->is_empty());
  53. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_width() != p_mesh.emission_on_uv2->get_width());
  54. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_height() != p_mesh.emission_on_uv2->get_height());
  55. ERR_FAIL_COND(p_mesh.points.is_empty());
  56. MeshInstance mi;
  57. mi.data = p_mesh;
  58. mesh_instances.push_back(mi);
  59. }
  60. void LightmapperRD::add_directional_light(const String &p_name, bool p_static, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_angular_distance, float p_shadow_blur) {
  61. Light l;
  62. l.type = LIGHT_TYPE_DIRECTIONAL;
  63. l.direction[0] = p_direction.x;
  64. l.direction[1] = p_direction.y;
  65. l.direction[2] = p_direction.z;
  66. l.color[0] = p_color.r;
  67. l.color[1] = p_color.g;
  68. l.color[2] = p_color.b;
  69. l.energy = p_energy;
  70. l.indirect_energy = p_indirect_energy;
  71. l.static_bake = p_static;
  72. l.size = Math::tan(Math::deg_to_rad(p_angular_distance));
  73. l.shadow_blur = p_shadow_blur;
  74. lights.push_back(l);
  75. light_names.push_back(p_name);
  76. }
  77. void LightmapperRD::add_omni_light(const String &p_name, bool p_static, const Vector3 &p_position, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_size, float p_shadow_blur) {
  78. Light l;
  79. l.type = LIGHT_TYPE_OMNI;
  80. l.position[0] = p_position.x;
  81. l.position[1] = p_position.y;
  82. l.position[2] = p_position.z;
  83. l.range = p_range;
  84. l.attenuation = p_attenuation;
  85. l.color[0] = p_color.r;
  86. l.color[1] = p_color.g;
  87. l.color[2] = p_color.b;
  88. l.energy = p_energy;
  89. l.indirect_energy = p_indirect_energy;
  90. l.static_bake = p_static;
  91. l.size = p_size;
  92. l.shadow_blur = p_shadow_blur;
  93. lights.push_back(l);
  94. light_names.push_back(p_name);
  95. }
  96. void LightmapperRD::add_spot_light(const String &p_name, bool p_static, const Vector3 &p_position, const Vector3 p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size, float p_shadow_blur) {
  97. Light l;
  98. l.type = LIGHT_TYPE_SPOT;
  99. l.position[0] = p_position.x;
  100. l.position[1] = p_position.y;
  101. l.position[2] = p_position.z;
  102. l.direction[0] = p_direction.x;
  103. l.direction[1] = p_direction.y;
  104. l.direction[2] = p_direction.z;
  105. l.range = p_range;
  106. l.attenuation = p_attenuation;
  107. l.cos_spot_angle = Math::cos(Math::deg_to_rad(p_spot_angle));
  108. l.inv_spot_attenuation = 1.0f / p_spot_attenuation;
  109. l.color[0] = p_color.r;
  110. l.color[1] = p_color.g;
  111. l.color[2] = p_color.b;
  112. l.energy = p_energy;
  113. l.indirect_energy = p_indirect_energy;
  114. l.static_bake = p_static;
  115. l.size = p_size;
  116. l.shadow_blur = p_shadow_blur;
  117. lights.push_back(l);
  118. light_names.push_back(p_name);
  119. }
  120. void LightmapperRD::add_probe(const Vector3 &p_position) {
  121. Probe probe;
  122. probe.position[0] = p_position.x;
  123. probe.position[1] = p_position.y;
  124. probe.position[2] = p_position.z;
  125. probe.position[3] = 0;
  126. probe_positions.push_back(probe);
  127. }
  128. 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> &p_triangles_sort, uint32_t p_grid_size) {
  129. int half_size = p_size / 2;
  130. for (int i = 0; i < 8; i++) {
  131. AABB aabb = p_bounds;
  132. aabb.size *= 0.5;
  133. Vector3i n = p_ofs;
  134. if (i & 1) {
  135. aabb.position.x += aabb.size.x;
  136. n.x += half_size;
  137. }
  138. if (i & 2) {
  139. aabb.position.y += aabb.size.y;
  140. n.y += half_size;
  141. }
  142. if (i & 4) {
  143. aabb.position.z += aabb.size.z;
  144. n.z += half_size;
  145. }
  146. {
  147. Vector3 qsize = aabb.size * 0.5; //quarter size, for fast aabb test
  148. if (!Geometry3D::triangle_box_overlap(aabb.position + qsize, qsize, p_points)) {
  149. //does not fit in child, go on
  150. continue;
  151. }
  152. }
  153. if (half_size == 1) {
  154. //got to the end
  155. TriangleSort ts;
  156. ts.cell_index = n.x + (n.y * p_grid_size) + (n.z * p_grid_size * p_grid_size);
  157. ts.triangle_index = p_triangle_index;
  158. ts.triangle_aabb.position = p_points[0];
  159. ts.triangle_aabb.size = Vector3();
  160. ts.triangle_aabb.expand_to(p_points[1]);
  161. ts.triangle_aabb.expand_to(p_points[2]);
  162. p_triangles_sort.push_back(ts);
  163. } else {
  164. _plot_triangle_into_triangle_index_list(half_size, n, aabb, p_points, p_triangle_index, p_triangles_sort, p_grid_size);
  165. }
  166. }
  167. }
  168. void LightmapperRD::_sort_triangle_clusters(uint32_t p_cluster_size, uint32_t p_cluster_index, uint32_t p_index_start, uint32_t p_count, LocalVector<TriangleSort> &p_triangle_sort, LocalVector<ClusterAABB> &p_cluster_aabb) {
  169. if (p_count == 0) {
  170. return;
  171. }
  172. // Compute AABB for all triangles in the range.
  173. SortArray<TriangleSort, TriangleSortAxis<0>> triangle_sorter_x;
  174. SortArray<TriangleSort, TriangleSortAxis<1>> triangle_sorter_y;
  175. SortArray<TriangleSort, TriangleSortAxis<2>> triangle_sorter_z;
  176. AABB cluster_aabb = p_triangle_sort[p_index_start].triangle_aabb;
  177. for (uint32_t i = 1; i < p_count; i++) {
  178. cluster_aabb.merge_with(p_triangle_sort[p_index_start + i].triangle_aabb);
  179. }
  180. if (p_count > p_cluster_size) {
  181. int longest_axis_index = cluster_aabb.get_longest_axis_index();
  182. switch (longest_axis_index) {
  183. case 0:
  184. triangle_sorter_x.sort(&p_triangle_sort[p_index_start], p_count);
  185. break;
  186. case 1:
  187. triangle_sorter_y.sort(&p_triangle_sort[p_index_start], p_count);
  188. break;
  189. case 2:
  190. triangle_sorter_z.sort(&p_triangle_sort[p_index_start], p_count);
  191. break;
  192. default:
  193. DEV_ASSERT(false && "Invalid axis returned by AABB.");
  194. break;
  195. }
  196. uint32_t left_cluster_count = next_power_of_2(p_count / 2);
  197. left_cluster_count = MAX(left_cluster_count, p_cluster_size);
  198. left_cluster_count = MIN(left_cluster_count, p_count);
  199. _sort_triangle_clusters(p_cluster_size, p_cluster_index, p_index_start, left_cluster_count, p_triangle_sort, p_cluster_aabb);
  200. if (left_cluster_count < p_count) {
  201. uint32_t cluster_index_right = p_cluster_index + (left_cluster_count / p_cluster_size);
  202. _sort_triangle_clusters(p_cluster_size, cluster_index_right, p_index_start + left_cluster_count, p_count - left_cluster_count, p_triangle_sort, p_cluster_aabb);
  203. }
  204. } else {
  205. ClusterAABB &aabb = p_cluster_aabb[p_cluster_index];
  206. Vector3 aabb_end = cluster_aabb.get_end();
  207. aabb.min_bounds[0] = cluster_aabb.position.x;
  208. aabb.min_bounds[1] = cluster_aabb.position.y;
  209. aabb.min_bounds[2] = cluster_aabb.position.z;
  210. aabb.max_bounds[0] = aabb_end.x;
  211. aabb.max_bounds[1] = aabb_end.y;
  212. aabb.max_bounds[2] = aabb_end.z;
  213. }
  214. }
  215. Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_size, int p_denoiser_range, Vector<Ref<Image>> &albedo_images, Vector<Ref<Image>> &emission_images, AABB &bounds, Size2i &atlas_size, int &atlas_slices, float p_supersampling_factor, BakeStepFunc p_step_function, void *p_bake_userdata) {
  216. Vector<Size2i> sizes;
  217. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  218. MeshInstance &mi = mesh_instances.write[m_i];
  219. Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height());
  220. sizes.push_back(s);
  221. atlas_size = atlas_size.max(s + Size2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor);
  222. }
  223. int max = nearest_power_of_2_templated(atlas_size.width);
  224. max = MAX(max, nearest_power_of_2_templated(atlas_size.height));
  225. if (max > p_max_texture_size) {
  226. return BAKE_ERROR_TEXTURE_EXCEEDS_MAX_SIZE;
  227. }
  228. if (p_step_function) {
  229. if (p_step_function(0.1, RTR("Determining optimal atlas size"), p_bake_userdata, true)) {
  230. return BAKE_ERROR_USER_ABORTED;
  231. }
  232. }
  233. atlas_size = Size2i(max, max);
  234. Size2i best_atlas_size;
  235. int best_atlas_slices = 0;
  236. int best_atlas_memory = 0x7FFFFFFF;
  237. Vector<Vector3i> best_atlas_offsets;
  238. // Determine best texture array atlas size by bruteforce fitting.
  239. while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) {
  240. Vector<Vector2i> source_sizes;
  241. Vector<int> source_indices;
  242. source_sizes.resize(sizes.size());
  243. source_indices.resize(sizes.size());
  244. for (int i = 0; i < source_indices.size(); i++) {
  245. // Add padding between lightmaps.
  246. // Scale the padding if the lightmap will be downsampled at the end of the baking process
  247. // Otherwise the padding would be insufficient.
  248. source_sizes.write[i] = sizes[i] + Vector2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor;
  249. source_indices.write[i] = i;
  250. }
  251. Vector<Vector3i> atlas_offsets;
  252. atlas_offsets.resize(source_sizes.size());
  253. // Ensure the sizes can all fit into a single atlas layer.
  254. // This should always happen, and this check is only in place to prevent an infinite loop.
  255. for (int i = 0; i < source_sizes.size(); i++) {
  256. if (source_sizes[i] > atlas_size) {
  257. return BAKE_ERROR_ATLAS_TOO_SMALL;
  258. }
  259. }
  260. int slices = 0;
  261. while (source_sizes.size() > 0) {
  262. Vector<Vector3i> offsets = Geometry2D::partial_pack_rects(source_sizes, atlas_size);
  263. Vector<int> new_indices;
  264. Vector<Vector2i> new_sources;
  265. for (int i = 0; i < offsets.size(); i++) {
  266. Vector3i ofs = offsets[i];
  267. int sidx = source_indices[i];
  268. if (ofs.z > 0) {
  269. //valid
  270. ofs.z = slices;
  271. atlas_offsets.write[sidx] = ofs + Vector3i(1, 1, 0); // Center lightmap in the reserved oversized region
  272. } else {
  273. new_indices.push_back(sidx);
  274. new_sources.push_back(source_sizes[i]);
  275. }
  276. }
  277. source_sizes = new_sources;
  278. source_indices = new_indices;
  279. slices++;
  280. }
  281. int mem_used = atlas_size.x * atlas_size.y * slices;
  282. if (mem_used < best_atlas_memory) {
  283. best_atlas_size = atlas_size;
  284. best_atlas_offsets = atlas_offsets;
  285. best_atlas_slices = slices;
  286. best_atlas_memory = mem_used;
  287. }
  288. if (atlas_size.width == atlas_size.height) {
  289. atlas_size.width *= 2;
  290. } else {
  291. atlas_size.height *= 2;
  292. }
  293. }
  294. atlas_size = best_atlas_size;
  295. atlas_slices = best_atlas_slices;
  296. // apply the offsets and slice to all images, and also blit albedo and emission
  297. albedo_images.resize(atlas_slices);
  298. emission_images.resize(atlas_slices);
  299. if (p_step_function) {
  300. if (p_step_function(0.2, RTR("Blitting albedo and emission"), p_bake_userdata, true)) {
  301. return BAKE_ERROR_USER_ABORTED;
  302. }
  303. }
  304. for (int i = 0; i < atlas_slices; i++) {
  305. Ref<Image> albedo = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);
  306. albedo->set_as_black();
  307. albedo_images.write[i] = albedo;
  308. Ref<Image> emission = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);
  309. emission->set_as_black();
  310. emission_images.write[i] = emission;
  311. }
  312. //assign uv positions
  313. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  314. MeshInstance &mi = mesh_instances.write[m_i];
  315. mi.offset.x = best_atlas_offsets[m_i].x;
  316. mi.offset.y = best_atlas_offsets[m_i].y;
  317. mi.slice = best_atlas_offsets[m_i].z;
  318. albedo_images.write[mi.slice]->blit_rect(mi.data.albedo_on_uv2, Rect2i(Vector2i(), mi.data.albedo_on_uv2->get_size()), mi.offset);
  319. emission_images.write[mi.slice]->blit_rect(mi.data.emission_on_uv2, Rect2(Vector2i(), mi.data.emission_on_uv2->get_size()), mi.offset);
  320. }
  321. return BAKE_OK;
  322. }
  323. void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, uint32_t p_cluster_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 &r_triangle_indices_buffer, RID &r_cluster_indices_buffer, RID &r_cluster_aabbs_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) {
  324. HashMap<Vertex, uint32_t, VertexHash> vertex_map;
  325. //fill triangles array and vertex array
  326. LocalVector<Triangle> triangles;
  327. LocalVector<Vertex> vertex_array;
  328. LocalVector<Seam> seams;
  329. slice_triangle_count.resize(atlas_slices);
  330. slice_seam_count.resize(atlas_slices);
  331. for (int i = 0; i < atlas_slices; i++) {
  332. slice_triangle_count.write[i] = 0;
  333. slice_seam_count.write[i] = 0;
  334. }
  335. bounds = AABB();
  336. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  337. if (p_step_function) {
  338. float p = float(m_i + 1) / MAX(1, mesh_instances.size()) * 0.1;
  339. 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);
  340. }
  341. HashMap<Edge, EdgeUV2, EdgeHash> edges;
  342. MeshInstance &mi = mesh_instances.write[m_i];
  343. Vector2 uv_scale = Vector2(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()) / Vector2(atlas_size);
  344. Vector2 uv_offset = Vector2(mi.offset) / Vector2(atlas_size);
  345. if (m_i == 0) {
  346. bounds.position = mi.data.points[0];
  347. }
  348. for (int i = 0; i < mi.data.points.size(); i += 3) {
  349. Vector3 vtxs[3] = { mi.data.points[i + 0], mi.data.points[i + 1], mi.data.points[i + 2] };
  350. 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 };
  351. Vector3 normal[3] = { mi.data.normal[i + 0], mi.data.normal[i + 1], mi.data.normal[i + 2] };
  352. AABB taabb;
  353. Triangle t;
  354. t.slice = mi.slice;
  355. for (int k = 0; k < 3; k++) {
  356. bounds.expand_to(vtxs[k]);
  357. Vertex v;
  358. v.position[0] = vtxs[k].x;
  359. v.position[1] = vtxs[k].y;
  360. v.position[2] = vtxs[k].z;
  361. v.uv[0] = uvs[k].x;
  362. v.uv[1] = uvs[k].y;
  363. v.normal_xy[0] = normal[k].x;
  364. v.normal_xy[1] = normal[k].y;
  365. v.normal_z = normal[k].z;
  366. uint32_t *indexptr = vertex_map.getptr(v);
  367. if (indexptr) {
  368. t.indices[k] = *indexptr;
  369. } else {
  370. uint32_t new_index = vertex_map.size();
  371. t.indices[k] = new_index;
  372. vertex_map[v] = new_index;
  373. vertex_array.push_back(v);
  374. }
  375. if (k == 0) {
  376. taabb.position = vtxs[k];
  377. } else {
  378. taabb.expand_to(vtxs[k]);
  379. }
  380. }
  381. //compute seams that will need to be blended later
  382. for (int k = 0; k < 3; k++) {
  383. int n = (k + 1) % 3;
  384. Edge edge(vtxs[k], vtxs[n], normal[k], normal[n]);
  385. Vector2i edge_indices(t.indices[k], t.indices[n]);
  386. EdgeUV2 uv2(uvs[k], uvs[n], edge_indices);
  387. if (edge.b == edge.a) {
  388. continue; //degenerate, somehow
  389. }
  390. if (edge.b < edge.a) {
  391. SWAP(edge.a, edge.b);
  392. SWAP(edge.na, edge.nb);
  393. SWAP(uv2.a, uv2.b);
  394. SWAP(uv2.indices.x, uv2.indices.y);
  395. SWAP(edge_indices.x, edge_indices.y);
  396. }
  397. EdgeUV2 *euv2 = edges.getptr(edge);
  398. if (!euv2) {
  399. edges[edge] = uv2;
  400. } else {
  401. if (*euv2 == uv2) {
  402. continue; // seam shared UV space, no need to blend
  403. }
  404. if (euv2->seam_found) {
  405. continue; //bad geometry
  406. }
  407. Seam seam;
  408. seam.a = edge_indices;
  409. seam.b = euv2->indices;
  410. seam.slice = mi.slice;
  411. seams.push_back(seam);
  412. slice_seam_count.write[mi.slice]++;
  413. euv2->seam_found = true;
  414. }
  415. }
  416. t.min_bounds[0] = taabb.position.x;
  417. t.min_bounds[1] = taabb.position.y;
  418. t.min_bounds[2] = taabb.position.z;
  419. t.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);
  420. t.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);
  421. t.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);
  422. t.cull_mode = RS::CULL_MODE_BACK;
  423. RID material = mi.data.material[i];
  424. if (material.is_valid()) {
  425. t.cull_mode = RSG::material_storage->material_get_cull_mode(material);
  426. }
  427. t.pad1 = 0; //make valgrind not complain
  428. triangles.push_back(t);
  429. slice_triangle_count.write[t.slice]++;
  430. }
  431. }
  432. //also consider probe positions for bounds
  433. for (int i = 0; i < p_probe_positions.size(); i++) {
  434. Vector3 pp(p_probe_positions[i].position[0], p_probe_positions[i].position[1], p_probe_positions[i].position[2]);
  435. bounds.expand_to(pp);
  436. }
  437. bounds.grow_by(0.1); //grow a bit to avoid numerical error
  438. triangles.sort(); //sort by slice
  439. seams.sort();
  440. if (p_step_function) {
  441. p_step_function(0.4, RTR("Optimizing acceleration structure"), p_bake_userdata, true);
  442. }
  443. //fill list of triangles in grid
  444. LocalVector<TriangleSort> triangle_sort;
  445. for (uint32_t i = 0; i < triangles.size(); i++) {
  446. const Triangle &t = triangles[i];
  447. Vector3 face[3] = {
  448. Vector3(vertex_array[t.indices[0]].position[0], vertex_array[t.indices[0]].position[1], vertex_array[t.indices[0]].position[2]),
  449. Vector3(vertex_array[t.indices[1]].position[0], vertex_array[t.indices[1]].position[1], vertex_array[t.indices[1]].position[2]),
  450. Vector3(vertex_array[t.indices[2]].position[0], vertex_array[t.indices[2]].position[1], vertex_array[t.indices[2]].position[2])
  451. };
  452. _plot_triangle_into_triangle_index_list(grid_size, Vector3i(), bounds, face, i, triangle_sort, grid_size);
  453. }
  454. //sort it
  455. triangle_sort.sort();
  456. LocalVector<uint32_t> cluster_indices;
  457. LocalVector<ClusterAABB> cluster_aabbs;
  458. Vector<uint32_t> triangle_indices;
  459. triangle_indices.resize(triangle_sort.size());
  460. Vector<uint32_t> grid_indices;
  461. grid_indices.resize(grid_size * grid_size * grid_size * 2);
  462. memset(grid_indices.ptrw(), 0, grid_indices.size() * sizeof(uint32_t));
  463. {
  464. // Fill grid with cell indices.
  465. uint32_t last_cell = 0xFFFFFFFF;
  466. uint32_t *giw = grid_indices.ptrw();
  467. uint32_t cluster_count = 0;
  468. uint32_t solid_cell_count = 0;
  469. for (uint32_t i = 0; i < triangle_sort.size(); i++) {
  470. uint32_t cell = triangle_sort[i].cell_index;
  471. if (cell != last_cell) {
  472. giw[cell * 2 + 1] = solid_cell_count;
  473. solid_cell_count++;
  474. }
  475. if ((giw[cell * 2] % p_cluster_size) == 0) {
  476. // Add an extra cluster every time the triangle counter reaches a multiple of the cluster size.
  477. cluster_count++;
  478. }
  479. giw[cell * 2]++;
  480. last_cell = cell;
  481. }
  482. // Build fixed-size triangle clusters for all the cells to speed up the traversal. A cell can hold multiple clusters that each contain a fixed
  483. // amount of triangles and an AABB. The tracer will check against the AABBs first to know whether it needs to visit the cell's triangles.
  484. //
  485. // The building algorithm will divide the triangles recursively contained inside each cell, sorting by the longest axis of the AABB on each step.
  486. //
  487. // - If the amount of triangles is less or equal to the cluster size, the AABB will be stored and the algorithm stops.
  488. //
  489. // - The division by two is increased to the next power of two of half the amount of triangles (with cluster size as the minimum value) to
  490. // ensure the first half always fills the cluster.
  491. cluster_indices.resize(solid_cell_count * 2);
  492. cluster_aabbs.resize(cluster_count);
  493. uint32_t i = 0;
  494. uint32_t cluster_index = 0;
  495. uint32_t solid_cell_index = 0;
  496. uint32_t *tiw = triangle_indices.ptrw();
  497. while (i < triangle_sort.size()) {
  498. cluster_indices[solid_cell_index * 2] = cluster_index;
  499. cluster_indices[solid_cell_index * 2 + 1] = i;
  500. uint32_t cell = triangle_sort[i].cell_index;
  501. uint32_t triangle_count = giw[cell * 2];
  502. uint32_t cell_cluster_count = (triangle_count + p_cluster_size - 1) / p_cluster_size;
  503. _sort_triangle_clusters(p_cluster_size, cluster_index, i, triangle_count, triangle_sort, cluster_aabbs);
  504. for (uint32_t j = 0; j < triangle_count; j++) {
  505. tiw[i + j] = triangle_sort[i + j].triangle_index;
  506. }
  507. i += triangle_count;
  508. cluster_index += cell_cluster_count;
  509. solid_cell_index++;
  510. }
  511. }
  512. #if 0
  513. for (int i = 0; i < grid_size; i++) {
  514. for (int j = 0; j < grid_size; j++) {
  515. for (int k = 0; k < grid_size; k++) {
  516. uint32_t index = i * (grid_size * grid_size) + j * grid_size + k;
  517. grid_indices.write[index * 2] = float(i) / grid_size * 255;
  518. grid_indices.write[index * 2 + 1] = float(j) / grid_size * 255;
  519. }
  520. }
  521. }
  522. #endif
  523. #if 0
  524. for (int i = 0; i < grid_size; i++) {
  525. Vector<uint8_t> grid_usage;
  526. grid_usage.resize(grid_size * grid_size);
  527. for (int j = 0; j < grid_usage.size(); j++) {
  528. uint32_t ofs = i * grid_size * grid_size + j;
  529. uint32_t count = grid_indices[ofs * 2];
  530. grid_usage.write[j] = count > 0 ? 255 : 0;
  531. }
  532. Ref<Image> img = Image::create_from_data(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);
  533. img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png");
  534. }
  535. #endif
  536. /*****************************/
  537. /*** CREATE GPU STRUCTURES ***/
  538. /*****************************/
  539. lights.sort();
  540. Vector<Vector2i> seam_buffer_vec;
  541. seam_buffer_vec.resize(seams.size() * 2);
  542. for (uint32_t i = 0; i < seams.size(); i++) {
  543. seam_buffer_vec.write[i * 2 + 0] = seams[i].a;
  544. seam_buffer_vec.write[i * 2 + 1] = seams[i].b;
  545. }
  546. { //buffers
  547. Vector<uint8_t> vb = vertex_array.to_byte_array();
  548. vertex_buffer = rd->storage_buffer_create(vb.size(), vb);
  549. Vector<uint8_t> tb = triangles.to_byte_array();
  550. triangle_buffer = rd->storage_buffer_create(tb.size(), tb);
  551. Vector<uint8_t> tib = triangle_indices.to_byte_array();
  552. r_triangle_indices_buffer = rd->storage_buffer_create(tib.size(), tib);
  553. Vector<uint8_t> cib = cluster_indices.to_byte_array();
  554. r_cluster_indices_buffer = rd->storage_buffer_create(cib.size(), cib);
  555. Vector<uint8_t> cab = cluster_aabbs.to_byte_array();
  556. r_cluster_aabbs_buffer = rd->storage_buffer_create(cab.size(), cab);
  557. Vector<uint8_t> lb = lights.to_byte_array();
  558. if (lb.size() == 0) {
  559. lb.resize(sizeof(Light)); //even if no lights, the buffer must exist
  560. }
  561. lights_buffer = rd->storage_buffer_create(lb.size(), lb);
  562. Vector<uint8_t> sb = seam_buffer_vec.to_byte_array();
  563. if (sb.size() == 0) {
  564. sb.resize(sizeof(Vector2i) * 2); //even if no seams, the buffer must exist
  565. }
  566. seams_buffer = rd->storage_buffer_create(sb.size(), sb);
  567. Vector<uint8_t> pb = p_probe_positions.to_byte_array();
  568. if (pb.size() == 0) {
  569. pb.resize(sizeof(Probe));
  570. }
  571. probe_positions_buffer = rd->storage_buffer_create(pb.size(), pb);
  572. }
  573. { //grid
  574. RD::TextureFormat tf;
  575. tf.width = grid_size;
  576. tf.height = grid_size;
  577. tf.depth = grid_size;
  578. tf.texture_type = RD::TEXTURE_TYPE_3D;
  579. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  580. Vector<Vector<uint8_t>> texdata;
  581. texdata.resize(1);
  582. //grid and indices
  583. tf.format = RD::DATA_FORMAT_R32G32_UINT;
  584. texdata.write[0] = grid_indices.to_byte_array();
  585. grid_texture = rd->texture_create(tf, RD::TextureView(), texdata);
  586. }
  587. }
  588. 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) {
  589. Vector<RID> framebuffers;
  590. for (int i = 0; i < atlas_slices; i++) {
  591. RID slice_pos_tex = rd->texture_create_shared_from_slice(RD::TextureView(), position_tex, i, 0);
  592. RID slice_unoc_tex = rd->texture_create_shared_from_slice(RD::TextureView(), unocclude_tex, i, 0);
  593. RID slice_norm_tex = rd->texture_create_shared_from_slice(RD::TextureView(), normal_tex, i, 0);
  594. Vector<RID> fb;
  595. fb.push_back(slice_pos_tex);
  596. fb.push_back(slice_norm_tex);
  597. fb.push_back(slice_unoc_tex);
  598. fb.push_back(raster_depth_buffer);
  599. framebuffers.push_back(rd->framebuffer_create(fb));
  600. }
  601. RD::PipelineDepthStencilState ds;
  602. ds.enable_depth_test = true;
  603. ds.enable_depth_write = true;
  604. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does render same pixel twice
  605. 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);
  606. RID raster_pipeline_wire;
  607. {
  608. RD::PipelineRasterizationState rw;
  609. rw.wireframe = true;
  610. 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);
  611. }
  612. uint32_t triangle_offset = 0;
  613. Vector<Color> clear_colors;
  614. clear_colors.push_back(Color(0, 0, 0, 0));
  615. clear_colors.push_back(Color(0, 0, 0, 0));
  616. clear_colors.push_back(Color(0, 0, 0, 0));
  617. for (int i = 0; i < atlas_slices; i++) {
  618. RasterPushConstant raster_push_constant;
  619. raster_push_constant.atlas_size[0] = atlas_size.x;
  620. raster_push_constant.atlas_size[1] = atlas_size.y;
  621. raster_push_constant.base_triangle = triangle_offset;
  622. raster_push_constant.to_cell_offset[0] = bounds.position.x;
  623. raster_push_constant.to_cell_offset[1] = bounds.position.y;
  624. raster_push_constant.to_cell_offset[2] = bounds.position.z;
  625. raster_push_constant.bias = p_bias;
  626. raster_push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  627. raster_push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  628. raster_push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  629. raster_push_constant.grid_size[0] = grid_size;
  630. raster_push_constant.grid_size[1] = grid_size;
  631. raster_push_constant.grid_size[2] = grid_size;
  632. // Half pixel offset is required so the rasterizer doesn't output face edges directly aligned into pixels.
  633. // This fixes artifacts where the pixel would be traced from the edge of a face, causing half the rays to
  634. // be outside of the boundaries of the geometry. See <https://github.com/godotengine/godot/issues/69126>.
  635. raster_push_constant.uv_offset[0] = -0.5f / float(atlas_size.x);
  636. raster_push_constant.uv_offset[1] = -0.5f / float(atlas_size.y);
  637. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::DRAW_CLEAR_ALL, clear_colors, 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::LIGHTMAPPER_PASS);
  638. //draw opaque
  639. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline);
  640. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  641. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  642. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  643. //draw wire
  644. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline_wire);
  645. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  646. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  647. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  648. rd->draw_list_end();
  649. triangle_offset += slice_triangle_count[i];
  650. }
  651. }
  652. static Vector<RD::Uniform> dilate_or_denoise_common_uniforms(RID &p_source_light_tex, RID &p_dest_light_tex) {
  653. Vector<RD::Uniform> uniforms;
  654. {
  655. RD::Uniform u;
  656. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  657. u.binding = 0;
  658. u.append_id(p_dest_light_tex);
  659. uniforms.push_back(u);
  660. }
  661. {
  662. RD::Uniform u;
  663. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  664. u.binding = 1;
  665. u.append_id(p_source_light_tex);
  666. uniforms.push_back(u);
  667. }
  668. return uniforms;
  669. }
  670. 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) {
  671. Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex);
  672. RID compute_shader_dilate = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("dilate"));
  673. ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  674. RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate);
  675. RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_dilate, 1);
  676. RD::ComputeListID compute_list = rd->compute_list_begin();
  677. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_dilate_pipeline);
  678. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  679. rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
  680. push_constant.region_ofs[0] = 0;
  681. push_constant.region_ofs[1] = 0;
  682. Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size
  683. for (int i = 0; i < atlas_slices; i++) {
  684. push_constant.atlas_slice = i;
  685. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  686. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  687. //no barrier, let them run all together
  688. }
  689. rd->compute_list_end();
  690. rd->free(compute_shader_dilate);
  691. #ifdef DEBUG_TEXTURES
  692. for (int i = 0; i < atlas_slices; i++) {
  693. Vector<uint8_t> s = rd->texture_get_data(source_light_tex, i);
  694. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  695. img->convert(Image::FORMAT_RGBA8);
  696. img->save_png("res://5_dilated_" + itos(i) + ".png");
  697. }
  698. #endif
  699. return BAKE_OK;
  700. }
  701. LightmapperRD::BakeError LightmapperRD::_pack_l1(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) {
  702. Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex);
  703. RID compute_shader_pack = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("pack_coeffs"));
  704. ERR_FAIL_COND_V(compute_shader_pack.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  705. RID compute_shader_pack_pipeline = rd->compute_pipeline_create(compute_shader_pack);
  706. RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_pack, 1);
  707. RD::ComputeListID compute_list = rd->compute_list_begin();
  708. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_pack_pipeline);
  709. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  710. rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
  711. push_constant.region_ofs[0] = 0;
  712. push_constant.region_ofs[1] = 0;
  713. Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size
  714. for (int i = 0; i < atlas_slices; i++) {
  715. push_constant.atlas_slice = i;
  716. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  717. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  718. //no barrier, let them run all together
  719. }
  720. rd->compute_list_end();
  721. rd->free(compute_shader_pack);
  722. return BAKE_OK;
  723. }
  724. Error LightmapperRD::_store_pfm(RenderingDevice *p_rd, RID p_atlas_tex, int p_index, const Size2i &p_atlas_size, const String &p_name, bool p_shadowmask) {
  725. Vector<uint8_t> data = p_rd->texture_get_data(p_atlas_tex, p_index);
  726. Ref<Image> img = Image::create_from_data(p_atlas_size.width, p_atlas_size.height, false, p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH, data);
  727. img->convert(Image::FORMAT_RGBF);
  728. Vector<uint8_t> data_float = img->get_data();
  729. Error err = OK;
  730. Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::WRITE, &err);
  731. ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save PFN at path: '%s'.", p_name));
  732. file->store_line("PF");
  733. file->store_line(vformat("%d %d", img->get_width(), img->get_height()));
  734. #ifdef BIG_ENDIAN_ENABLED
  735. file->store_line("1.0");
  736. #else
  737. file->store_line("-1.0");
  738. #endif
  739. file->store_buffer(data_float);
  740. file->close();
  741. return OK;
  742. }
  743. Ref<Image> LightmapperRD::_read_pfm(const String &p_name, bool p_shadowmask) {
  744. Error err = OK;
  745. Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::READ, &err);
  746. ERR_FAIL_COND_V_MSG(err, Ref<Image>(), vformat("Can't load PFM at path: '%s'.", p_name));
  747. ERR_FAIL_COND_V(file->get_line() != "PF", Ref<Image>());
  748. Vector<String> new_size = file->get_line().split(" ");
  749. ERR_FAIL_COND_V(new_size.size() != 2, Ref<Image>());
  750. int new_width = new_size[0].to_int();
  751. int new_height = new_size[1].to_int();
  752. float endian = file->get_line().to_float();
  753. Vector<uint8_t> new_data = file->get_buffer(file->get_length() - file->get_position());
  754. file->close();
  755. #ifdef BIG_ENDIAN_ENABLED
  756. if (unlikely(endian < 0.0)) {
  757. uint32_t count = new_data.size() / 4;
  758. uint16_t *dst = (uint16_t *)new_data.ptrw();
  759. for (uint32_t j = 0; j < count; j++) {
  760. dst[j * 4] = BSWAP32(dst[j * 4]);
  761. }
  762. }
  763. #else
  764. if (unlikely(endian > 0.0)) {
  765. uint32_t count = new_data.size() / 4;
  766. uint16_t *dst = (uint16_t *)new_data.ptrw();
  767. for (uint32_t j = 0; j < count; j++) {
  768. dst[j * 4] = BSWAP32(dst[j * 4]);
  769. }
  770. }
  771. #endif
  772. Ref<Image> img = Image::create_from_data(new_width, new_height, false, Image::FORMAT_RGBF, new_data);
  773. img->convert(p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH);
  774. return img;
  775. }
  776. 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, bool p_shadowmask, const String &p_exe) {
  777. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  778. for (int i = 0; i < p_atlas_slices; i++) {
  779. String fname_norm_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_norm_%d.pfm", i));
  780. _store_pfm(p_rd, p_source_normal_tex, i, p_atlas_size, fname_norm_in, false);
  781. for (int j = 0; j < (p_bake_sh ? 4 : 1); j++) {
  782. int index = i * (p_bake_sh ? 4 : 1) + j;
  783. String fname_light_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_light_%d.pfm", index));
  784. String fname_out = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_denoised_%d.pfm", index));
  785. _store_pfm(p_rd, p_source_light_tex, index, p_atlas_size, fname_light_in, p_shadowmask);
  786. List<String> args;
  787. args.push_back("--device");
  788. args.push_back("default");
  789. args.push_back("--filter");
  790. args.push_back("RTLightmap");
  791. args.push_back(p_shadowmask ? "--ldr" : "--hdr");
  792. args.push_back(fname_light_in);
  793. args.push_back("--nrm");
  794. args.push_back(fname_norm_in);
  795. args.push_back("--output");
  796. args.push_back(fname_out);
  797. String str;
  798. int exitcode = 0;
  799. Error err = OS::get_singleton()->execute(p_exe, args, &str, &exitcode, true);
  800. da->remove(fname_light_in);
  801. if (err != OK || exitcode != 0) {
  802. da->remove(fname_out);
  803. print_verbose(str);
  804. ERR_FAIL_V_MSG(BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, vformat("OIDN denoiser failed, return code: %d", exitcode));
  805. }
  806. Ref<Image> img = _read_pfm(fname_out, p_shadowmask);
  807. da->remove(fname_out);
  808. ERR_FAIL_COND_V(img.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  809. Vector<uint8_t> old_data = p_rd->texture_get_data(p_source_light_tex, index);
  810. Vector<uint8_t> new_data = img->get_data();
  811. img.unref(); // Avoid copy on write.
  812. uint32_t count = old_data.size() / 2;
  813. const uint16_t *src = (const uint16_t *)old_data.ptr();
  814. uint16_t *dst = (uint16_t *)new_data.ptrw();
  815. for (uint32_t k = 0; k < count; k += 4) {
  816. dst[k + 3] = src[k + 3];
  817. }
  818. p_rd->texture_update(p_dest_light_tex, index, new_data);
  819. }
  820. da->remove(fname_norm_in);
  821. }
  822. return BAKE_OK;
  823. }
  824. 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, int p_denoiser_range, const Size2i &p_atlas_size, int p_atlas_slices, bool p_bake_sh, BakeStepFunc p_step_function, void *p_bake_userdata) {
  825. RID denoise_params_buffer = p_rd->uniform_buffer_create(sizeof(DenoiseParams));
  826. DenoiseParams denoise_params;
  827. denoise_params.spatial_bandwidth = 5.0f;
  828. denoise_params.light_bandwidth = p_denoiser_strength;
  829. denoise_params.albedo_bandwidth = 1.0f;
  830. denoise_params.normal_bandwidth = 0.1f;
  831. denoise_params.filter_strength = 10.0f;
  832. denoise_params.half_search_window = p_denoiser_range;
  833. p_rd->buffer_update(denoise_params_buffer, 0, sizeof(DenoiseParams), &denoise_params);
  834. Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(p_source_light_tex, p_dest_light_tex);
  835. {
  836. RD::Uniform u;
  837. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  838. u.binding = 2;
  839. u.append_id(p_source_normal_tex);
  840. uniforms.push_back(u);
  841. }
  842. {
  843. RD::Uniform u;
  844. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  845. u.binding = 3;
  846. u.append_id(denoise_params_buffer);
  847. uniforms.push_back(u);
  848. }
  849. RID compute_shader_denoise = p_rd->shader_create_from_spirv(p_compute_shader->get_spirv_stages("denoise"));
  850. ERR_FAIL_COND_V(compute_shader_denoise.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  851. RID compute_shader_denoise_pipeline = p_rd->compute_pipeline_create(compute_shader_denoise);
  852. RID denoise_uniform_set = p_rd->uniform_set_create(uniforms, compute_shader_denoise, 1);
  853. // We denoise in fixed size regions and synchronize execution to avoid GPU timeouts.
  854. // We use a region with 1/4 the amount of pixels if we're denoising SH lightmaps, as
  855. // all four of them are denoised in the shader in one dispatch.
  856. const int max_region_size = p_bake_sh ? 512 : 1024;
  857. int x_regions = Math::division_round_up(p_atlas_size.width, max_region_size);
  858. int y_regions = Math::division_round_up(p_atlas_size.height, max_region_size);
  859. for (int s = 0; s < p_atlas_slices; s++) {
  860. p_push_constant.atlas_slice = s;
  861. for (int i = 0; i < x_regions; i++) {
  862. for (int j = 0; j < y_regions; j++) {
  863. int x = i * max_region_size;
  864. int y = j * max_region_size;
  865. int w = MIN((i + 1) * max_region_size, p_atlas_size.width) - x;
  866. int h = MIN((j + 1) * max_region_size, p_atlas_size.height) - y;
  867. p_push_constant.region_ofs[0] = x;
  868. p_push_constant.region_ofs[1] = y;
  869. RD::ComputeListID compute_list = p_rd->compute_list_begin();
  870. p_rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_denoise_pipeline);
  871. p_rd->compute_list_bind_uniform_set(compute_list, p_compute_base_uniform_set, 0);
  872. p_rd->compute_list_bind_uniform_set(compute_list, denoise_uniform_set, 1);
  873. p_rd->compute_list_set_push_constant(compute_list, &p_push_constant, sizeof(PushConstant));
  874. p_rd->compute_list_dispatch(compute_list, Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
  875. p_rd->compute_list_end();
  876. p_rd->submit();
  877. p_rd->sync();
  878. }
  879. }
  880. if (p_step_function) {
  881. int percent = (s + 1) * 100 / p_atlas_slices;
  882. float p = float(s) / p_atlas_slices * 0.1;
  883. if (p_step_function(0.8 + p, vformat(RTR("Denoising %d%%"), percent), p_bake_userdata, false)) {
  884. return BAKE_ERROR_USER_ABORTED;
  885. }
  886. }
  887. }
  888. p_rd->free(compute_shader_denoise);
  889. p_rd->free(denoise_params_buffer);
  890. return BAKE_OK;
  891. }
  892. LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_denoiser, float p_denoiser_strength, int p_denoiser_range, int p_bounces, float p_bounce_indirect_energy, float p_bias, int p_max_texture_size, bool p_bake_sh, bool p_bake_shadowmask, bool p_texture_for_bounces, 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, float p_supersampling_factor) {
  893. int denoiser = GLOBAL_GET("rendering/lightmapping/denoising/denoiser");
  894. String oidn_path = EDITOR_GET("filesystem/tools/oidn/oidn_denoise_path");
  895. if (p_use_denoiser && denoiser == 1) {
  896. // OIDN (external).
  897. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  898. if (da->dir_exists(oidn_path)) {
  899. if (OS::get_singleton()->get_name() == "Windows") {
  900. oidn_path = oidn_path.path_join("oidnDenoise.exe");
  901. } else {
  902. oidn_path = oidn_path.path_join("oidnDenoise");
  903. }
  904. }
  905. ERR_FAIL_COND_V_MSG(oidn_path.is_empty() || !da->file_exists(oidn_path), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, "OIDN denoiser is selected in the project settings, but no or invalid OIDN executable path is configured in the editor settings.");
  906. }
  907. if (p_step_function) {
  908. p_step_function(0.0, RTR("Begin Bake"), p_bake_userdata, true);
  909. }
  910. lightmap_textures.clear();
  911. shadowmask_textures.clear();
  912. int grid_size = 128;
  913. /* STEP 1: Fetch material textures and compute the bounds */
  914. AABB bounds;
  915. Size2i atlas_size;
  916. int atlas_slices;
  917. Vector<Ref<Image>> albedo_images;
  918. Vector<Ref<Image>> emission_images;
  919. BakeError bake_error = _blit_meshes_into_atlas(p_max_texture_size, p_denoiser_range, albedo_images, emission_images, bounds, atlas_size, atlas_slices, p_supersampling_factor, p_step_function, p_bake_userdata);
  920. if (bake_error != BAKE_OK) {
  921. return bake_error;
  922. }
  923. // The index of the directional light used for shadowmasking.
  924. int shadowmask_light_idx = -1;
  925. // If there are no valid directional lights for shadowmasking, the entire
  926. // scene would be shadowed and this saves baking time.
  927. if (p_bake_shadowmask) {
  928. int shadowmask_lights_count = 0;
  929. for (int i = 0; i < lights.size(); i++) {
  930. if (lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL && !lights[i].static_bake) {
  931. if (shadowmask_light_idx < 0) {
  932. shadowmask_light_idx = i;
  933. }
  934. shadowmask_lights_count += 1;
  935. }
  936. }
  937. if (shadowmask_light_idx < 0) {
  938. p_bake_shadowmask = false;
  939. WARN_PRINT("Shadowmask disabled: no directional light with their bake mode set to dynamic exists.");
  940. } else if (shadowmask_lights_count > 1) {
  941. WARN_PRINT(
  942. vformat("%d directional lights detected for shadowmask baking. Only %s will be used.",
  943. shadowmask_lights_count, light_names[shadowmask_light_idx]));
  944. }
  945. }
  946. #ifdef DEBUG_TEXTURES
  947. for (int i = 0; i < atlas_slices; i++) {
  948. albedo_images[i]->save_png("res://0_albedo_" + itos(i) + ".png");
  949. emission_images[i]->save_png("res://0_emission_" + itos(i) + ".png");
  950. }
  951. #endif
  952. // Attempt to create a local device by requesting it from rendering server first.
  953. // If that fails because the current renderer is not implemented on top of RD, we fall back to creating
  954. // a local rendering device manually depending on the current platform.
  955. Error err;
  956. RenderingContextDriver *rcd = nullptr;
  957. RenderingDevice *rd = RenderingServer::get_singleton()->create_local_rendering_device();
  958. if (rd == nullptr) {
  959. #if defined(RD_ENABLED)
  960. #if defined(METAL_ENABLED)
  961. rcd = memnew(RenderingContextDriverMetal);
  962. rd = memnew(RenderingDevice);
  963. #endif
  964. #if defined(VULKAN_ENABLED)
  965. if (rcd == nullptr) {
  966. rcd = memnew(RenderingContextDriverVulkan);
  967. rd = memnew(RenderingDevice);
  968. }
  969. #endif
  970. #endif
  971. if (rcd != nullptr && rd != nullptr) {
  972. err = rcd->initialize();
  973. if (err == OK) {
  974. err = rd->initialize(rcd);
  975. }
  976. if (err != OK) {
  977. memdelete(rd);
  978. memdelete(rcd);
  979. rd = nullptr;
  980. rcd = nullptr;
  981. }
  982. }
  983. }
  984. ERR_FAIL_NULL_V(rd, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  985. RID albedo_array_tex;
  986. RID emission_array_tex;
  987. RID normal_tex;
  988. RID position_tex;
  989. RID unocclude_tex;
  990. RID light_source_tex;
  991. RID light_dest_tex;
  992. RID light_accum_tex;
  993. RID light_accum_tex2;
  994. RID light_environment_tex;
  995. RID shadowmask_tex;
  996. RID shadowmask_tex2;
  997. #define FREE_TEXTURES \
  998. rd->free(albedo_array_tex); \
  999. rd->free(emission_array_tex); \
  1000. rd->free(normal_tex); \
  1001. rd->free(position_tex); \
  1002. rd->free(unocclude_tex); \
  1003. rd->free(light_source_tex); \
  1004. rd->free(light_accum_tex2); \
  1005. rd->free(light_accum_tex); \
  1006. rd->free(light_environment_tex); \
  1007. if (p_bake_shadowmask) { \
  1008. rd->free(shadowmask_tex); \
  1009. rd->free(shadowmask_tex2); \
  1010. }
  1011. { // create all textures
  1012. Vector<Vector<uint8_t>> albedo_data;
  1013. Vector<Vector<uint8_t>> emission_data;
  1014. for (int i = 0; i < atlas_slices; i++) {
  1015. albedo_data.push_back(albedo_images[i]->get_data());
  1016. emission_data.push_back(emission_images[i]->get_data());
  1017. }
  1018. RD::TextureFormat tf;
  1019. tf.width = atlas_size.width;
  1020. tf.height = atlas_size.height;
  1021. tf.array_layers = atlas_slices;
  1022. tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  1023. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  1024. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  1025. albedo_array_tex = rd->texture_create(tf, RD::TextureView(), albedo_data);
  1026. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1027. emission_array_tex = rd->texture_create(tf, RD::TextureView(), emission_data);
  1028. //this will be rastered to
  1029. 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;
  1030. normal_tex = rd->texture_create(tf, RD::TextureView());
  1031. tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  1032. position_tex = rd->texture_create(tf, RD::TextureView());
  1033. unocclude_tex = rd->texture_create(tf, RD::TextureView());
  1034. 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;
  1035. // shadowmask
  1036. if (p_bake_shadowmask) {
  1037. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  1038. shadowmask_tex = rd->texture_create(tf, RD::TextureView());
  1039. rd->texture_clear(shadowmask_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  1040. shadowmask_tex2 = rd->texture_create(tf, RD::TextureView());
  1041. rd->texture_clear(shadowmask_tex2, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  1042. }
  1043. // lightmap
  1044. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1045. light_source_tex = rd->texture_create(tf, RD::TextureView());
  1046. rd->texture_clear(light_source_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  1047. if (p_bake_sh) {
  1048. tf.array_layers *= 4;
  1049. }
  1050. light_accum_tex = rd->texture_create(tf, RD::TextureView());
  1051. rd->texture_clear(light_accum_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  1052. light_dest_tex = rd->texture_create(tf, RD::TextureView());
  1053. rd->texture_clear(light_dest_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  1054. light_accum_tex2 = light_dest_tex;
  1055. //env
  1056. {
  1057. Ref<Image> panorama_tex;
  1058. if (p_environment_panorama.is_valid()) {
  1059. panorama_tex = p_environment_panorama;
  1060. panorama_tex->convert(Image::FORMAT_RGBAF);
  1061. } else {
  1062. panorama_tex.instantiate();
  1063. panorama_tex->initialize_data(8, 8, false, Image::FORMAT_RGBAF);
  1064. panorama_tex->fill(Color(0, 0, 0, 1));
  1065. }
  1066. RD::TextureFormat tfp;
  1067. tfp.width = panorama_tex->get_width();
  1068. tfp.height = panorama_tex->get_height();
  1069. tfp.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  1070. tfp.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  1071. Vector<Vector<uint8_t>> tdata;
  1072. tdata.push_back(panorama_tex->get_data());
  1073. light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata);
  1074. #ifdef DEBUG_TEXTURES
  1075. panorama_tex->save_exr("res://0_panorama.exr", false);
  1076. #endif
  1077. }
  1078. }
  1079. /* STEP 2: create the acceleration structure for the GPU*/
  1080. Vector<int> slice_triangle_count;
  1081. RID bake_parameters_buffer;
  1082. RID vertex_buffer;
  1083. RID triangle_buffer;
  1084. RID lights_buffer;
  1085. RID triangle_indices_buffer;
  1086. RID cluster_indices_buffer;
  1087. RID cluster_aabbs_buffer;
  1088. RID grid_texture;
  1089. RID seams_buffer;
  1090. RID probe_positions_buffer;
  1091. Vector<int> slice_seam_count;
  1092. #define FREE_BUFFERS \
  1093. rd->free(bake_parameters_buffer); \
  1094. rd->free(vertex_buffer); \
  1095. rd->free(triangle_buffer); \
  1096. rd->free(lights_buffer); \
  1097. rd->free(triangle_indices_buffer); \
  1098. rd->free(cluster_indices_buffer); \
  1099. rd->free(cluster_aabbs_buffer); \
  1100. rd->free(grid_texture); \
  1101. rd->free(seams_buffer); \
  1102. rd->free(probe_positions_buffer);
  1103. const uint32_t cluster_size = 16;
  1104. _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, cluster_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, lights_buffer, triangle_indices_buffer, cluster_indices_buffer, cluster_aabbs_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata);
  1105. // Create global bake parameters buffer.
  1106. BakeParameters bake_parameters;
  1107. bake_parameters.world_size[0] = bounds.size.x;
  1108. bake_parameters.world_size[1] = bounds.size.y;
  1109. bake_parameters.world_size[2] = bounds.size.z;
  1110. bake_parameters.bias = p_bias;
  1111. bake_parameters.to_cell_offset[0] = bounds.position.x;
  1112. bake_parameters.to_cell_offset[1] = bounds.position.y;
  1113. bake_parameters.to_cell_offset[2] = bounds.position.z;
  1114. bake_parameters.grid_size = grid_size;
  1115. bake_parameters.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  1116. bake_parameters.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  1117. bake_parameters.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  1118. bake_parameters.light_count = lights.size();
  1119. bake_parameters.env_transform[0] = p_environment_transform.rows[0][0];
  1120. bake_parameters.env_transform[1] = p_environment_transform.rows[1][0];
  1121. bake_parameters.env_transform[2] = p_environment_transform.rows[2][0];
  1122. bake_parameters.env_transform[3] = 0.0f;
  1123. bake_parameters.env_transform[4] = p_environment_transform.rows[0][1];
  1124. bake_parameters.env_transform[5] = p_environment_transform.rows[1][1];
  1125. bake_parameters.env_transform[6] = p_environment_transform.rows[2][1];
  1126. bake_parameters.env_transform[7] = 0.0f;
  1127. bake_parameters.env_transform[8] = p_environment_transform.rows[0][2];
  1128. bake_parameters.env_transform[9] = p_environment_transform.rows[1][2];
  1129. bake_parameters.env_transform[10] = p_environment_transform.rows[2][2];
  1130. bake_parameters.env_transform[11] = 0.0f;
  1131. bake_parameters.atlas_size[0] = atlas_size.width;
  1132. bake_parameters.atlas_size[1] = atlas_size.height;
  1133. bake_parameters.exposure_normalization = p_exposure_normalization;
  1134. bake_parameters.bounces = p_bounces;
  1135. bake_parameters.bounce_indirect_energy = p_bounce_indirect_energy;
  1136. bake_parameters.shadowmask_light_idx = shadowmask_light_idx;
  1137. // Same number of rays for transparency regardless of quality (it's more of a retry rather than shooting new ones).
  1138. bake_parameters.transparency_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_transparency_rays");
  1139. bake_parameters.supersampling_factor = p_supersampling_factor;
  1140. bake_parameters_buffer = rd->uniform_buffer_create(sizeof(BakeParameters));
  1141. rd->buffer_update(bake_parameters_buffer, 0, sizeof(BakeParameters), &bake_parameters);
  1142. if (p_step_function) {
  1143. if (p_step_function(0.47, RTR("Preparing shaders"), p_bake_userdata, true)) {
  1144. FREE_TEXTURES
  1145. FREE_BUFFERS
  1146. memdelete(rd);
  1147. if (rcd != nullptr) {
  1148. memdelete(rcd);
  1149. }
  1150. return BAKE_ERROR_USER_ABORTED;
  1151. }
  1152. }
  1153. //shaders
  1154. Ref<RDShaderFile> raster_shader;
  1155. raster_shader.instantiate();
  1156. err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl);
  1157. if (err != OK) {
  1158. raster_shader->print_errors("raster_shader");
  1159. FREE_TEXTURES
  1160. FREE_BUFFERS
  1161. memdelete(rd);
  1162. if (rcd != nullptr) {
  1163. memdelete(rcd);
  1164. }
  1165. }
  1166. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1167. RID rasterize_shader = rd->shader_create_from_spirv(raster_shader->get_spirv_stages());
  1168. ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen
  1169. RID sampler;
  1170. {
  1171. RD::SamplerState s;
  1172. s.mag_filter = RD::SAMPLER_FILTER_LINEAR;
  1173. s.min_filter = RD::SAMPLER_FILTER_LINEAR;
  1174. s.max_lod = 0;
  1175. sampler = rd->sampler_create(s);
  1176. }
  1177. Vector<RD::Uniform> base_uniforms;
  1178. {
  1179. {
  1180. RD::Uniform u;
  1181. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  1182. u.binding = 0;
  1183. u.append_id(bake_parameters_buffer);
  1184. base_uniforms.push_back(u);
  1185. }
  1186. {
  1187. RD::Uniform u;
  1188. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1189. u.binding = 1;
  1190. u.append_id(vertex_buffer);
  1191. base_uniforms.push_back(u);
  1192. }
  1193. {
  1194. RD::Uniform u;
  1195. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1196. u.binding = 2;
  1197. u.append_id(triangle_buffer);
  1198. base_uniforms.push_back(u);
  1199. }
  1200. {
  1201. RD::Uniform u;
  1202. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1203. u.binding = 3;
  1204. u.append_id(triangle_indices_buffer);
  1205. base_uniforms.push_back(u);
  1206. }
  1207. {
  1208. RD::Uniform u;
  1209. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1210. u.binding = 4;
  1211. u.append_id(lights_buffer);
  1212. base_uniforms.push_back(u);
  1213. }
  1214. {
  1215. RD::Uniform u;
  1216. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1217. u.binding = 5;
  1218. u.append_id(seams_buffer);
  1219. base_uniforms.push_back(u);
  1220. }
  1221. {
  1222. RD::Uniform u;
  1223. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1224. u.binding = 6;
  1225. u.append_id(probe_positions_buffer);
  1226. base_uniforms.push_back(u);
  1227. }
  1228. {
  1229. RD::Uniform u;
  1230. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1231. u.binding = 7;
  1232. u.append_id(grid_texture);
  1233. base_uniforms.push_back(u);
  1234. }
  1235. {
  1236. RD::Uniform u;
  1237. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1238. u.binding = 8;
  1239. u.append_id(albedo_array_tex);
  1240. base_uniforms.push_back(u);
  1241. }
  1242. {
  1243. RD::Uniform u;
  1244. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1245. u.binding = 9;
  1246. u.append_id(emission_array_tex);
  1247. base_uniforms.push_back(u);
  1248. }
  1249. {
  1250. RD::Uniform u;
  1251. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  1252. u.binding = 10;
  1253. u.append_id(sampler);
  1254. base_uniforms.push_back(u);
  1255. }
  1256. {
  1257. RD::Uniform u;
  1258. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1259. u.binding = 11;
  1260. u.append_id(cluster_indices_buffer);
  1261. base_uniforms.push_back(u);
  1262. }
  1263. {
  1264. RD::Uniform u;
  1265. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1266. u.binding = 12;
  1267. u.append_id(cluster_aabbs_buffer);
  1268. base_uniforms.push_back(u);
  1269. }
  1270. }
  1271. RID raster_base_uniform = rd->uniform_set_create(base_uniforms, rasterize_shader, 0);
  1272. RID raster_depth_buffer;
  1273. {
  1274. RD::TextureFormat tf;
  1275. tf.width = atlas_size.width;
  1276. tf.height = atlas_size.height;
  1277. tf.depth = 1;
  1278. tf.texture_type = RD::TEXTURE_TYPE_2D;
  1279. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1280. tf.format = RD::DATA_FORMAT_D32_SFLOAT;
  1281. tf.is_discardable = true;
  1282. raster_depth_buffer = rd->texture_create(tf, RD::TextureView());
  1283. }
  1284. rd->submit();
  1285. rd->sync();
  1286. /* STEP 3: Raster the geometry to UV2 coords in the atlas textures GPU*/
  1287. _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);
  1288. #ifdef DEBUG_TEXTURES
  1289. for (int i = 0; i < atlas_slices; i++) {
  1290. Vector<uint8_t> s = rd->texture_get_data(position_tex, i);
  1291. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
  1292. img->save_exr("res://1_position_" + itos(i) + ".exr", false);
  1293. s = rd->texture_get_data(normal_tex, i);
  1294. img->set_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1295. img->save_exr("res://1_normal_" + itos(i) + ".exr", false);
  1296. }
  1297. #endif
  1298. #define FREE_RASTER_RESOURCES \
  1299. rd->free(rasterize_shader); \
  1300. rd->free(sampler); \
  1301. rd->free(raster_depth_buffer);
  1302. /* Plot direct light */
  1303. Ref<RDShaderFile> compute_shader;
  1304. String defines = "";
  1305. defines += "\n#define CLUSTER_SIZE " + uitos(cluster_size) + "\n";
  1306. if (p_bake_sh) {
  1307. defines += "\n#define USE_SH_LIGHTMAPS\n";
  1308. }
  1309. if (p_texture_for_bounces) {
  1310. defines += "\n#define USE_LIGHT_TEXTURE_FOR_BOUNCES\n";
  1311. }
  1312. if (p_bake_shadowmask) {
  1313. defines += "\n#define USE_SHADOWMASK\n";
  1314. }
  1315. compute_shader.instantiate();
  1316. err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, defines);
  1317. if (err != OK) {
  1318. FREE_TEXTURES
  1319. FREE_BUFFERS
  1320. FREE_RASTER_RESOURCES
  1321. memdelete(rd);
  1322. if (rcd != nullptr) {
  1323. memdelete(rcd);
  1324. }
  1325. compute_shader->print_errors("compute_shader");
  1326. }
  1327. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1328. // Unoccluder
  1329. RID compute_shader_unocclude = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("unocclude"));
  1330. ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  1331. RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude);
  1332. // Direct light
  1333. RID compute_shader_primary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("primary"));
  1334. ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  1335. RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary);
  1336. // Indirect light
  1337. RID compute_shader_secondary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("secondary"));
  1338. ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  1339. RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary);
  1340. // Light probes
  1341. RID compute_shader_light_probes = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("light_probes"));
  1342. ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  1343. RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes);
  1344. RID compute_base_uniform_set = rd->uniform_set_create(base_uniforms, compute_shader_primary, 0);
  1345. #define FREE_COMPUTE_RESOURCES \
  1346. rd->free(compute_shader_unocclude); \
  1347. rd->free(compute_shader_primary); \
  1348. rd->free(compute_shader_secondary); \
  1349. rd->free(compute_shader_light_probes);
  1350. Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1);
  1351. rd->submit();
  1352. rd->sync();
  1353. if (p_step_function) {
  1354. if (p_step_function(0.49, RTR("Un-occluding geometry"), p_bake_userdata, true)) {
  1355. FREE_TEXTURES
  1356. FREE_BUFFERS
  1357. FREE_RASTER_RESOURCES
  1358. FREE_COMPUTE_RESOURCES
  1359. memdelete(rd);
  1360. if (rcd != nullptr) {
  1361. memdelete(rcd);
  1362. }
  1363. return BAKE_ERROR_USER_ABORTED;
  1364. }
  1365. }
  1366. PushConstant push_constant;
  1367. /* UNOCCLUDE */
  1368. {
  1369. Vector<RD::Uniform> uniforms;
  1370. {
  1371. {
  1372. RD::Uniform u;
  1373. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1374. u.binding = 0;
  1375. u.append_id(position_tex);
  1376. uniforms.push_back(u);
  1377. }
  1378. {
  1379. RD::Uniform u;
  1380. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1381. u.binding = 1;
  1382. u.append_id(unocclude_tex); //will be unused
  1383. uniforms.push_back(u);
  1384. }
  1385. }
  1386. RID unocclude_uniform_set = rd->uniform_set_create(uniforms, compute_shader_unocclude, 1);
  1387. RD::ComputeListID compute_list = rd->compute_list_begin();
  1388. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_unocclude_pipeline);
  1389. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1390. rd->compute_list_bind_uniform_set(compute_list, unocclude_uniform_set, 1);
  1391. for (int i = 0; i < atlas_slices; i++) {
  1392. push_constant.atlas_slice = i;
  1393. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1394. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1395. //no barrier, let them run all together
  1396. }
  1397. rd->compute_list_end(); //done
  1398. }
  1399. if (p_step_function) {
  1400. if (p_step_function(0.5, RTR("Plot direct lighting"), p_bake_userdata, true)) {
  1401. FREE_TEXTURES
  1402. FREE_BUFFERS
  1403. FREE_RASTER_RESOURCES
  1404. FREE_COMPUTE_RESOURCES
  1405. memdelete(rd);
  1406. if (rcd != nullptr) {
  1407. memdelete(rcd);
  1408. }
  1409. return BAKE_ERROR_USER_ABORTED;
  1410. }
  1411. }
  1412. // Set ray count to the quality used for direct light and bounces.
  1413. switch (p_quality) {
  1414. case BAKE_QUALITY_LOW: {
  1415. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_ray_count");
  1416. } break;
  1417. case BAKE_QUALITY_MEDIUM: {
  1418. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_ray_count");
  1419. } break;
  1420. case BAKE_QUALITY_HIGH: {
  1421. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_ray_count");
  1422. } break;
  1423. case BAKE_QUALITY_ULTRA: {
  1424. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_ray_count");
  1425. } break;
  1426. }
  1427. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1428. /* PRIMARY (direct) LIGHT PASS */
  1429. {
  1430. Vector<RD::Uniform> uniforms;
  1431. {
  1432. {
  1433. RD::Uniform u;
  1434. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1435. u.binding = 0;
  1436. u.append_id(light_source_tex);
  1437. uniforms.push_back(u);
  1438. }
  1439. {
  1440. RD::Uniform u;
  1441. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1442. u.binding = 1;
  1443. u.append_id(light_dest_tex); //will be unused
  1444. uniforms.push_back(u);
  1445. }
  1446. {
  1447. RD::Uniform u;
  1448. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1449. u.binding = 2;
  1450. u.append_id(position_tex);
  1451. uniforms.push_back(u);
  1452. }
  1453. {
  1454. RD::Uniform u;
  1455. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1456. u.binding = 3;
  1457. u.append_id(normal_tex);
  1458. uniforms.push_back(u);
  1459. }
  1460. {
  1461. RD::Uniform u;
  1462. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1463. u.binding = 4;
  1464. u.append_id(light_accum_tex);
  1465. uniforms.push_back(u);
  1466. }
  1467. if (p_bake_shadowmask) {
  1468. RD::Uniform u;
  1469. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1470. u.binding = 5;
  1471. u.append_id(shadowmask_tex);
  1472. uniforms.push_back(u);
  1473. }
  1474. }
  1475. RID light_uniform_set = rd->uniform_set_create(uniforms, compute_shader_primary, 1);
  1476. RD::ComputeListID compute_list = rd->compute_list_begin();
  1477. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_primary_pipeline);
  1478. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1479. rd->compute_list_bind_uniform_set(compute_list, light_uniform_set, 1);
  1480. for (int i = 0; i < atlas_slices; i++) {
  1481. push_constant.atlas_slice = i;
  1482. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1483. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1484. //no barrier, let them run all together
  1485. }
  1486. rd->compute_list_end(); //done
  1487. }
  1488. #ifdef DEBUG_TEXTURES
  1489. for (int i = 0; i < atlas_slices; i++) {
  1490. Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);
  1491. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1492. img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false);
  1493. }
  1494. if (p_bake_sh) {
  1495. for (int i = 0; i < atlas_slices * 4; i++) {
  1496. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1497. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1498. img->save_exr("res://2_light_primary_accum_" + itos(i) + ".exr", false);
  1499. }
  1500. }
  1501. #endif
  1502. /* SECONDARY (indirect) LIGHT PASS(ES) */
  1503. if (p_bounces > 0) {
  1504. Vector<RD::Uniform> uniforms;
  1505. {
  1506. {
  1507. // Unused.
  1508. RD::Uniform u;
  1509. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1510. u.binding = 0;
  1511. u.append_id(light_dest_tex);
  1512. uniforms.push_back(u);
  1513. }
  1514. {
  1515. RD::Uniform u;
  1516. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1517. u.binding = 1;
  1518. u.append_id(light_source_tex);
  1519. uniforms.push_back(u);
  1520. }
  1521. {
  1522. RD::Uniform u;
  1523. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1524. u.binding = 2;
  1525. u.append_id(position_tex);
  1526. uniforms.push_back(u);
  1527. }
  1528. {
  1529. RD::Uniform u;
  1530. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1531. u.binding = 3;
  1532. u.append_id(normal_tex);
  1533. uniforms.push_back(u);
  1534. }
  1535. {
  1536. RD::Uniform u;
  1537. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1538. u.binding = 4;
  1539. u.append_id(light_accum_tex);
  1540. uniforms.push_back(u);
  1541. }
  1542. {
  1543. RD::Uniform u;
  1544. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1545. u.binding = 5;
  1546. u.append_id(light_environment_tex);
  1547. uniforms.push_back(u);
  1548. }
  1549. }
  1550. RID secondary_uniform_set;
  1551. secondary_uniform_set = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
  1552. int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));
  1553. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass");
  1554. int x_regions = Math::division_round_up(atlas_size.width, max_region_size);
  1555. int y_regions = Math::division_round_up(atlas_size.height, max_region_size);
  1556. int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);
  1557. rd->submit();
  1558. rd->sync();
  1559. if (p_step_function) {
  1560. if (p_step_function(0.6, RTR("Integrate indirect lighting"), p_bake_userdata, true)) {
  1561. FREE_TEXTURES
  1562. FREE_BUFFERS
  1563. FREE_RASTER_RESOURCES
  1564. FREE_COMPUTE_RESOURCES
  1565. memdelete(rd);
  1566. if (rcd != nullptr) {
  1567. memdelete(rcd);
  1568. }
  1569. return BAKE_ERROR_USER_ABORTED;
  1570. }
  1571. }
  1572. int count = 0;
  1573. for (int s = 0; s < atlas_slices; s++) {
  1574. push_constant.atlas_slice = s;
  1575. for (int i = 0; i < x_regions; i++) {
  1576. for (int j = 0; j < y_regions; j++) {
  1577. int x = i * max_region_size;
  1578. int y = j * max_region_size;
  1579. int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
  1580. int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
  1581. push_constant.region_ofs[0] = x;
  1582. push_constant.region_ofs[1] = y;
  1583. group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
  1584. for (int k = 0; k < ray_iterations; k++) {
  1585. RD::ComputeListID compute_list = rd->compute_list_begin();
  1586. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline);
  1587. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1588. rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set, 1);
  1589. push_constant.ray_from = k * max_rays;
  1590. push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count));
  1591. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1592. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1593. rd->compute_list_end();
  1594. rd->submit();
  1595. rd->sync();
  1596. count++;
  1597. if (p_step_function) {
  1598. int total = (atlas_slices * x_regions * y_regions * ray_iterations);
  1599. int percent = count * 100 / total;
  1600. float p = float(count) / total * 0.1;
  1601. if (p_step_function(0.6 + p, vformat(RTR("Integrate indirect lighting %d%%"), percent), p_bake_userdata, false)) {
  1602. FREE_TEXTURES
  1603. FREE_BUFFERS
  1604. FREE_RASTER_RESOURCES
  1605. FREE_COMPUTE_RESOURCES
  1606. memdelete(rd);
  1607. if (rcd != nullptr) {
  1608. memdelete(rcd);
  1609. }
  1610. return BAKE_ERROR_USER_ABORTED;
  1611. }
  1612. }
  1613. }
  1614. }
  1615. }
  1616. }
  1617. }
  1618. /* LIGHTPROBES */
  1619. RID light_probe_buffer;
  1620. if (probe_positions.size()) {
  1621. light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size());
  1622. if (p_step_function) {
  1623. if (p_step_function(0.7, RTR("Baking light probes"), p_bake_userdata, true)) {
  1624. FREE_TEXTURES
  1625. FREE_BUFFERS
  1626. FREE_RASTER_RESOURCES
  1627. FREE_COMPUTE_RESOURCES
  1628. if (probe_positions.size() > 0) {
  1629. rd->free(light_probe_buffer);
  1630. }
  1631. memdelete(rd);
  1632. if (rcd != nullptr) {
  1633. memdelete(rcd);
  1634. }
  1635. return BAKE_ERROR_USER_ABORTED;
  1636. }
  1637. }
  1638. Vector<RD::Uniform> uniforms;
  1639. {
  1640. {
  1641. RD::Uniform u;
  1642. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1643. u.binding = 0;
  1644. u.append_id(light_probe_buffer);
  1645. uniforms.push_back(u);
  1646. }
  1647. {
  1648. RD::Uniform u;
  1649. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1650. u.binding = 1;
  1651. u.append_id(light_source_tex);
  1652. uniforms.push_back(u);
  1653. }
  1654. {
  1655. RD::Uniform u;
  1656. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1657. u.binding = 2;
  1658. u.append_id(light_environment_tex);
  1659. uniforms.push_back(u);
  1660. }
  1661. }
  1662. RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1);
  1663. switch (p_quality) {
  1664. case BAKE_QUALITY_LOW: {
  1665. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_probe_ray_count");
  1666. } break;
  1667. case BAKE_QUALITY_MEDIUM: {
  1668. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_probe_ray_count");
  1669. } break;
  1670. case BAKE_QUALITY_HIGH: {
  1671. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_probe_ray_count");
  1672. } break;
  1673. case BAKE_QUALITY_ULTRA: {
  1674. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count");
  1675. } break;
  1676. }
  1677. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1678. push_constant.probe_count = probe_positions.size();
  1679. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass");
  1680. int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);
  1681. for (int i = 0; i < ray_iterations; i++) {
  1682. RD::ComputeListID compute_list = rd->compute_list_begin();
  1683. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline);
  1684. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1685. rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1);
  1686. push_constant.ray_from = i * max_rays;
  1687. push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count));
  1688. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1689. rd->compute_list_dispatch(compute_list, Math::division_round_up((int)probe_positions.size(), 64), 1, 1);
  1690. rd->compute_list_end(); //done
  1691. rd->submit();
  1692. rd->sync();
  1693. if (p_step_function) {
  1694. int percent = i * 100 / ray_iterations;
  1695. float p = float(i) / ray_iterations * 0.1;
  1696. if (p_step_function(0.7 + p, vformat(RTR("Integrating light probes %d%%"), percent), p_bake_userdata, false)) {
  1697. FREE_TEXTURES
  1698. FREE_BUFFERS
  1699. FREE_RASTER_RESOURCES
  1700. FREE_COMPUTE_RESOURCES
  1701. if (probe_positions.size() > 0) {
  1702. rd->free(light_probe_buffer);
  1703. }
  1704. memdelete(rd);
  1705. if (rcd != nullptr) {
  1706. memdelete(rcd);
  1707. }
  1708. return BAKE_ERROR_USER_ABORTED;
  1709. }
  1710. }
  1711. }
  1712. }
  1713. #if 0
  1714. for (int i = 0; i < probe_positions.size(); i++) {
  1715. Ref<Image> img = Image::create_empty(6, 4, false, Image::FORMAT_RGB8);
  1716. for (int j = 0; j < 6; j++) {
  1717. Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);
  1718. Ref<Image> img2 = Image::create_from_data(2, 2, false, Image::FORMAT_RGBAF, s);
  1719. img2->convert(Image::FORMAT_RGB8);
  1720. img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2));
  1721. }
  1722. img->save_png("res://3_light_probe_" + itos(i) + ".png");
  1723. }
  1724. #endif
  1725. /* DENOISE */
  1726. if (p_use_denoiser) {
  1727. if (p_step_function) {
  1728. if (p_step_function(0.8, RTR("Denoising"), p_bake_userdata, true)) {
  1729. FREE_TEXTURES
  1730. FREE_BUFFERS
  1731. FREE_RASTER_RESOURCES
  1732. FREE_COMPUTE_RESOURCES
  1733. if (probe_positions.size() > 0) {
  1734. rd->free(light_probe_buffer);
  1735. }
  1736. memdelete(rd);
  1737. if (rcd != nullptr) {
  1738. memdelete(rcd);
  1739. }
  1740. return BAKE_ERROR_USER_ABORTED;
  1741. }
  1742. }
  1743. {
  1744. BakeError error;
  1745. if (denoiser == 1) {
  1746. // OIDN (external).
  1747. error = _denoise_oidn(rd, light_accum_tex, normal_tex, light_accum_tex, atlas_size, atlas_slices, p_bake_sh, false, oidn_path);
  1748. } else {
  1749. // JNLM (built-in).
  1750. SWAP(light_accum_tex, light_accum_tex2);
  1751. error = _denoise(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, normal_tex, light_accum_tex, p_denoiser_strength, p_denoiser_range, atlas_size, atlas_slices, p_bake_sh, p_step_function, p_bake_userdata);
  1752. }
  1753. if (unlikely(error != BAKE_OK)) {
  1754. return error;
  1755. }
  1756. }
  1757. if (p_bake_shadowmask) {
  1758. BakeError error;
  1759. if (denoiser == 1) {
  1760. // OIDN (external).
  1761. error = _denoise_oidn(rd, shadowmask_tex, normal_tex, shadowmask_tex, atlas_size, atlas_slices, false, true, oidn_path);
  1762. } else {
  1763. // JNLM (built-in).
  1764. SWAP(shadowmask_tex, shadowmask_tex2);
  1765. error = _denoise(rd, compute_shader, compute_base_uniform_set, push_constant, shadowmask_tex2, normal_tex, shadowmask_tex, p_denoiser_strength, p_denoiser_range, atlas_size, atlas_slices, false, p_step_function, p_bake_userdata);
  1766. }
  1767. if (unlikely(error != BAKE_OK)) {
  1768. return error;
  1769. }
  1770. }
  1771. }
  1772. /* DILATE */
  1773. {
  1774. SWAP(light_accum_tex, light_accum_tex2);
  1775. 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));
  1776. if (unlikely(error != BAKE_OK)) {
  1777. return error;
  1778. }
  1779. if (p_bake_shadowmask) {
  1780. SWAP(shadowmask_tex, shadowmask_tex2);
  1781. error = _dilate(rd, compute_shader, compute_base_uniform_set, push_constant, shadowmask_tex2, shadowmask_tex, atlas_size, atlas_slices);
  1782. if (unlikely(error != BAKE_OK)) {
  1783. return error;
  1784. }
  1785. }
  1786. }
  1787. #ifdef DEBUG_TEXTURES
  1788. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1789. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1790. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1791. img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false);
  1792. }
  1793. #endif
  1794. /* BLEND SEAMS */
  1795. //shaders
  1796. Ref<RDShaderFile> blendseams_shader;
  1797. blendseams_shader.instantiate();
  1798. err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl);
  1799. if (err != OK) {
  1800. FREE_TEXTURES
  1801. FREE_BUFFERS
  1802. FREE_RASTER_RESOURCES
  1803. FREE_COMPUTE_RESOURCES
  1804. memdelete(rd);
  1805. if (rcd != nullptr) {
  1806. memdelete(rcd);
  1807. }
  1808. blendseams_shader->print_errors("blendseams_shader");
  1809. }
  1810. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1811. RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines"));
  1812. ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1813. RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles"));
  1814. ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1815. #define FREE_BLENDSEAMS_RESOURCES \
  1816. rd->free(blendseams_line_raster_shader); \
  1817. rd->free(blendseams_triangle_raster_shader);
  1818. {
  1819. //pre copy
  1820. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1821. rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i);
  1822. }
  1823. Vector<RID> framebuffers;
  1824. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1825. RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0);
  1826. Vector<RID> fb;
  1827. fb.push_back(slice_tex);
  1828. fb.push_back(raster_depth_buffer);
  1829. framebuffers.push_back(rd->framebuffer_create(fb));
  1830. }
  1831. Vector<RD::Uniform> uniforms;
  1832. {
  1833. {
  1834. RD::Uniform u;
  1835. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1836. u.binding = 0;
  1837. u.append_id(light_accum_tex2);
  1838. uniforms.push_back(u);
  1839. }
  1840. }
  1841. RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1);
  1842. bool debug = false;
  1843. RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1);
  1844. bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
  1845. bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1846. RD::PipelineDepthStencilState ds;
  1847. ds.enable_depth_test = true;
  1848. ds.enable_depth_write = true;
  1849. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending
  1850. 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);
  1851. 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);
  1852. uint32_t seam_offset = 0;
  1853. uint32_t triangle_offset = 0;
  1854. for (int i = 0; i < atlas_slices; i++) {
  1855. int subslices = (p_bake_sh ? 4 : 1);
  1856. if (slice_seam_count[i] == 0) {
  1857. continue;
  1858. }
  1859. for (int k = 0; k < subslices; k++) {
  1860. RasterSeamsPushConstant seams_push_constant;
  1861. seams_push_constant.slice = uint32_t(i * subslices + k);
  1862. seams_push_constant.debug = debug;
  1863. // Store the current subslice in the breadcrumb.
  1864. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i * subslices + k], RD::DRAW_CLEAR_DEPTH, Vector<Color>(), 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::LIGHTMAPPER_PASS | seams_push_constant.slice);
  1865. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  1866. rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1);
  1867. const int uv_offset_count = 9;
  1868. static const Vector3 uv_offsets[uv_offset_count] = {
  1869. Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards
  1870. Vector3(0, 1, 0.2),
  1871. Vector3(0, -1, 0.2),
  1872. Vector3(1, 0, 0.2),
  1873. Vector3(-1, 0, 0.2),
  1874. Vector3(-1, -1, 0.1),
  1875. Vector3(1, -1, 0.1),
  1876. Vector3(1, 1, 0.1),
  1877. Vector3(-1, 1, 0.1),
  1878. };
  1879. /* step 1 use lines to blend the edges */
  1880. {
  1881. seams_push_constant.base_index = seam_offset;
  1882. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1883. seams_push_constant.uv_offset[0] = (uv_offsets[0].x - 0.5f) / float(atlas_size.width);
  1884. seams_push_constant.uv_offset[1] = (uv_offsets[0].y - 0.5f) / float(atlas_size.height);
  1885. seams_push_constant.blend = uv_offsets[0].z;
  1886. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1887. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1888. }
  1889. /* step 2 use triangles to mask the interior */
  1890. {
  1891. seams_push_constant.base_index = triangle_offset;
  1892. rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline);
  1893. seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask
  1894. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1895. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  1896. }
  1897. /* step 3 blend around the triangle */
  1898. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1899. for (int j = 1; j < uv_offset_count; j++) {
  1900. seams_push_constant.base_index = seam_offset;
  1901. seams_push_constant.uv_offset[0] = (uv_offsets[j].x - 0.5f) / float(atlas_size.width);
  1902. seams_push_constant.uv_offset[1] = (uv_offsets[j].y - 0.5f) / float(atlas_size.height);
  1903. seams_push_constant.blend = uv_offsets[0].z;
  1904. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1905. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1906. }
  1907. rd->draw_list_end();
  1908. }
  1909. seam_offset += slice_seam_count[i];
  1910. triangle_offset += slice_triangle_count[i];
  1911. }
  1912. }
  1913. if (p_bake_sh) {
  1914. SWAP(light_accum_tex, light_accum_tex2);
  1915. BakeError error = _pack_l1(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, light_accum_tex, atlas_size, atlas_slices);
  1916. if (unlikely(error != BAKE_OK)) {
  1917. return error;
  1918. }
  1919. }
  1920. #ifdef DEBUG_TEXTURES
  1921. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1922. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1923. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1924. img->save_exr("res://5_blendseams" + itos(i) + ".exr", false);
  1925. }
  1926. #endif
  1927. if (p_step_function) {
  1928. p_step_function(0.9, RTR("Retrieving textures"), p_bake_userdata, true);
  1929. }
  1930. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1931. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1932. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1933. img->convert(Image::FORMAT_RGBH); //remove alpha
  1934. lightmap_textures.push_back(img);
  1935. }
  1936. if (p_bake_shadowmask) {
  1937. for (int i = 0; i < atlas_slices; i++) {
  1938. Vector<uint8_t> s = rd->texture_get_data(shadowmask_tex, i);
  1939. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8, s);
  1940. img->convert(Image::FORMAT_R8);
  1941. shadowmask_textures.push_back(img);
  1942. }
  1943. }
  1944. if (probe_positions.size() > 0) {
  1945. probe_values.resize(probe_positions.size() * 9);
  1946. Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer);
  1947. memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size());
  1948. rd->free(light_probe_buffer);
  1949. #ifdef DEBUG_TEXTURES
  1950. {
  1951. Ref<Image> img2 = Image::create_from_data(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
  1952. img2->save_exr("res://6_lightprobes.exr", false);
  1953. }
  1954. #endif
  1955. }
  1956. FREE_TEXTURES
  1957. FREE_BUFFERS
  1958. FREE_RASTER_RESOURCES
  1959. FREE_COMPUTE_RESOURCES
  1960. FREE_BLENDSEAMS_RESOURCES
  1961. memdelete(rd);
  1962. if (rcd != nullptr) {
  1963. memdelete(rcd);
  1964. }
  1965. return BAKE_OK;
  1966. }
  1967. int LightmapperRD::get_bake_texture_count() const {
  1968. return lightmap_textures.size();
  1969. }
  1970. Ref<Image> LightmapperRD::get_bake_texture(int p_index) const {
  1971. ERR_FAIL_INDEX_V(p_index, lightmap_textures.size(), Ref<Image>());
  1972. return lightmap_textures[p_index];
  1973. }
  1974. int LightmapperRD::get_shadowmask_texture_count() const {
  1975. return shadowmask_textures.size();
  1976. }
  1977. Ref<Image> LightmapperRD::get_shadowmask_texture(int p_index) const {
  1978. ERR_FAIL_INDEX_V(p_index, shadowmask_textures.size(), Ref<Image>());
  1979. return shadowmask_textures[p_index];
  1980. }
  1981. int LightmapperRD::get_bake_mesh_count() const {
  1982. return mesh_instances.size();
  1983. }
  1984. Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const {
  1985. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1986. return mesh_instances[p_index].data.userdata;
  1987. }
  1988. Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const {
  1989. ERR_FAIL_COND_V(lightmap_textures.is_empty(), Rect2());
  1990. Rect2 uv_ofs;
  1991. Vector2 atlas_size = Vector2(lightmap_textures[0]->get_width(), lightmap_textures[0]->get_height());
  1992. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  1993. 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;
  1994. return uv_ofs;
  1995. }
  1996. int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const {
  1997. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1998. return mesh_instances[p_index].slice;
  1999. }
  2000. int LightmapperRD::get_bake_probe_count() const {
  2001. return probe_positions.size();
  2002. }
  2003. Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const {
  2004. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant());
  2005. return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]);
  2006. }
  2007. Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const {
  2008. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>());
  2009. Vector<Color> ret;
  2010. ret.resize(9);
  2011. memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9);
  2012. return ret;
  2013. }
  2014. LightmapperRD::LightmapperRD() {
  2015. }