lightmapper_rd.cpp 74 KB

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