lightmapper_rd.cpp 86 KB

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