lightmapper_cpu.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  1. /**************************************************************************/
  2. /* lightmapper_cpu.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_cpu.h"
  31. #include "core/math/geometry.h"
  32. #include "core/os/os.h"
  33. #include "core/os/threaded_array_processor.h"
  34. #include "core/project_settings.h"
  35. #include "modules/raycast/lightmap_raycaster.h"
  36. #ifdef TOOLS_ENABLED
  37. #include "editor/editor_settings.h"
  38. #endif
  39. Error LightmapperCPU::_layout_atlas(int p_max_size, Vector2i *r_atlas_size, int *r_atlas_slices) {
  40. Vector2i atlas_size;
  41. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  42. if (mesh_instances[i].generate_lightmap) {
  43. Vector2i size = mesh_instances[i].size;
  44. atlas_size.width = MAX(atlas_size.width, size.width + 2);
  45. atlas_size.height = MAX(atlas_size.height, size.height + 2);
  46. }
  47. }
  48. int max = nearest_power_of_2_templated(atlas_size.width);
  49. max = MAX(max, nearest_power_of_2_templated(atlas_size.height));
  50. if (max > p_max_size) {
  51. return ERR_INVALID_DATA;
  52. }
  53. Vector2i best_atlas_size;
  54. int best_atlas_slices = 0;
  55. int best_atlas_memory = 0x7FFFFFFF;
  56. float best_atlas_mem_utilization = 0;
  57. Vector<AtlasOffset> best_atlas_offsets;
  58. Vector<Vector2i> best_scaled_sizes;
  59. int first_try_mem_occupied = 0;
  60. int first_try_mem_used = 0;
  61. for (int recovery_percent = 0; recovery_percent <= 100; recovery_percent += 10) {
  62. // These only make sense from the second round of the loop
  63. float recovery_scale = 1;
  64. int target_mem_occupied = 0;
  65. if (recovery_percent != 0) {
  66. target_mem_occupied = first_try_mem_occupied + (first_try_mem_used - first_try_mem_occupied) * recovery_percent * 0.01f;
  67. float new_squared_recovery_scale = static_cast<float>(target_mem_occupied) / first_try_mem_occupied;
  68. if (new_squared_recovery_scale > 1.0f) {
  69. recovery_scale = Math::sqrt(new_squared_recovery_scale);
  70. }
  71. }
  72. atlas_size = Vector2i(max, max);
  73. while (atlas_size.x <= p_max_size && atlas_size.y <= p_max_size) {
  74. if (recovery_percent != 0) {
  75. // Find out how much memory is not recoverable (because of lightmaps that can't grow),
  76. // to compute a greater recovery scale for those that can.
  77. int mem_unrecoverable = 0;
  78. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  79. if (mesh_instances[i].generate_lightmap) {
  80. Vector2i scaled_size = Vector2i(
  81. static_cast<int>(recovery_scale * mesh_instances[i].size.x),
  82. static_cast<int>(recovery_scale * mesh_instances[i].size.y));
  83. if (scaled_size.x + 2 > atlas_size.x || scaled_size.y + 2 > atlas_size.y) {
  84. mem_unrecoverable += scaled_size.x * scaled_size.y - mesh_instances[i].size.x * mesh_instances[i].size.y;
  85. }
  86. }
  87. }
  88. float new_squared_recovery_scale = static_cast<float>(target_mem_occupied - mem_unrecoverable) / (first_try_mem_occupied - mem_unrecoverable);
  89. if (new_squared_recovery_scale > 1.0f) {
  90. recovery_scale = Math::sqrt(new_squared_recovery_scale);
  91. }
  92. }
  93. Vector<Vector2i> scaled_sizes;
  94. scaled_sizes.resize(mesh_instances.size());
  95. {
  96. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  97. if (mesh_instances[i].generate_lightmap) {
  98. if (recovery_percent == 0) {
  99. scaled_sizes.write[i] = mesh_instances[i].size;
  100. } else {
  101. Vector2i scaled_size = Vector2i(
  102. static_cast<int>(recovery_scale * mesh_instances[i].size.x),
  103. static_cast<int>(recovery_scale * mesh_instances[i].size.y));
  104. if (scaled_size.x + 2 <= atlas_size.x && scaled_size.y + 2 <= atlas_size.y) {
  105. scaled_sizes.write[i] = scaled_size;
  106. } else {
  107. scaled_sizes.write[i] = mesh_instances[i].size;
  108. }
  109. }
  110. } else {
  111. // Don't consider meshes with no generated lightmap here; will compensate later
  112. scaled_sizes.write[i] = Vector2i();
  113. }
  114. }
  115. }
  116. Vector<Vector2i> source_sizes;
  117. source_sizes.resize(scaled_sizes.size());
  118. Vector<int> source_indices;
  119. source_indices.resize(scaled_sizes.size());
  120. for (int i = 0; i < source_sizes.size(); i++) {
  121. source_sizes.write[i] = scaled_sizes[i] + Vector2i(2, 2); // Add padding between lightmaps
  122. source_indices.write[i] = i;
  123. }
  124. Vector<AtlasOffset> curr_atlas_offsets;
  125. curr_atlas_offsets.resize(source_sizes.size());
  126. int slices = 0;
  127. while (source_sizes.size() > 0) {
  128. Vector<Geometry::PackRectsResult> offsets = Geometry::partial_pack_rects(source_sizes, atlas_size);
  129. Vector<int> new_indices;
  130. Vector<Vector2i> new_sources;
  131. for (int i = 0; i < offsets.size(); i++) {
  132. Geometry::PackRectsResult ofs = offsets[i];
  133. int sidx = source_indices[i];
  134. if (ofs.packed) {
  135. curr_atlas_offsets.write[sidx] = { slices, ofs.x + 1, ofs.y + 1 };
  136. } else {
  137. new_indices.push_back(sidx);
  138. new_sources.push_back(source_sizes[i]);
  139. }
  140. }
  141. source_sizes = new_sources;
  142. source_indices = new_indices;
  143. slices++;
  144. }
  145. int mem_used = atlas_size.x * atlas_size.y * slices;
  146. int mem_occupied = 0;
  147. for (int i = 0; i < curr_atlas_offsets.size(); i++) {
  148. mem_occupied += scaled_sizes[i].x * scaled_sizes[i].y;
  149. }
  150. float mem_utilization = static_cast<float>(mem_occupied) / mem_used;
  151. if (mem_used < best_atlas_memory || (mem_used == best_atlas_memory && mem_utilization > best_atlas_mem_utilization)) {
  152. best_atlas_size = atlas_size;
  153. best_atlas_offsets = curr_atlas_offsets;
  154. best_atlas_slices = slices;
  155. best_atlas_memory = mem_used;
  156. best_atlas_mem_utilization = mem_utilization;
  157. best_scaled_sizes = scaled_sizes;
  158. }
  159. if (recovery_percent == 0) {
  160. first_try_mem_occupied = mem_occupied;
  161. first_try_mem_used = mem_used;
  162. }
  163. if (atlas_size.width == atlas_size.height) {
  164. atlas_size.width *= 2;
  165. } else {
  166. atlas_size.height *= 2;
  167. }
  168. }
  169. }
  170. if (best_atlas_size == Vector2i()) {
  171. return ERR_INVALID_DATA;
  172. }
  173. *r_atlas_size = best_atlas_size;
  174. *r_atlas_slices = best_atlas_slices;
  175. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  176. if (best_scaled_sizes[i] != Vector2i()) {
  177. mesh_instances[i].size = best_scaled_sizes[i];
  178. mesh_instances[i].offset = Vector2i(best_atlas_offsets[i].x, best_atlas_offsets[i].y);
  179. mesh_instances[i].slice = best_atlas_offsets[i].slice;
  180. }
  181. }
  182. return OK;
  183. }
  184. void LightmapperCPU::_thread_func_callback(void *p_thread_data) {
  185. ThreadData *thread_data = reinterpret_cast<ThreadData *>(p_thread_data);
  186. #ifdef TOOLS_ENABLED
  187. const int num_threads = EDITOR_GET("editors/3d/lightmap_baking_number_of_cpu_threads");
  188. #else
  189. const int num_threads = 0;
  190. #endif
  191. thread_process_array(thread_data->count, thread_data->instance, &LightmapperCPU::_thread_func_wrapper, thread_data, num_threads);
  192. }
  193. void LightmapperCPU::_thread_func_wrapper(uint32_t p_idx, ThreadData *p_thread_data) {
  194. if (thread_cancelled) {
  195. return;
  196. }
  197. (p_thread_data->instance->*p_thread_data->thread_func)(p_idx, p_thread_data->userdata);
  198. thread_progress++;
  199. }
  200. bool LightmapperCPU::_parallel_run(int p_count, const String &p_description, BakeThreadFunc p_thread_func, void *p_userdata, BakeStepFunc p_substep_func) {
  201. bool cancelled = false;
  202. if (p_substep_func) {
  203. cancelled = p_substep_func(0.0f, vformat("%s (%d/%d)", p_description, 0, p_count), nullptr, false);
  204. }
  205. thread_progress = 0;
  206. thread_cancelled = false;
  207. #ifdef NO_THREAD
  208. for (int i = 0; !cancelled && i < p_count; i++) {
  209. (this->*p_thread_func)(i, p_userdata);
  210. float p = float(i) / p_count;
  211. if (p_substep_func) {
  212. cancelled = p_substep_func(p, vformat("%s (%d/%d)", p_description, i + 1, p_count), nullptr, false);
  213. }
  214. }
  215. #else
  216. if (p_count == 0) {
  217. return cancelled;
  218. }
  219. ThreadData td;
  220. td.instance = this;
  221. td.count = p_count;
  222. td.thread_func = p_thread_func;
  223. td.userdata = p_userdata;
  224. Thread runner_thread;
  225. runner_thread.start(_thread_func_callback, &td);
  226. int progress = thread_progress;
  227. while (!cancelled && progress < p_count) {
  228. float p = float(progress) / p_count;
  229. if (p_substep_func) {
  230. cancelled = p_substep_func(p, vformat("%s (%d/%d)", p_description, progress + 1, p_count), nullptr, false);
  231. }
  232. progress = thread_progress;
  233. }
  234. thread_cancelled = cancelled;
  235. runner_thread.wait_to_finish();
  236. #endif
  237. thread_cancelled = false;
  238. return cancelled;
  239. }
  240. void LightmapperCPU::_generate_buffer(uint32_t p_idx, void *p_unused) {
  241. const Size2i &size = mesh_instances[p_idx].size;
  242. int buffer_size = size.x * size.y;
  243. LocalVector<LightmapTexel> &lightmap = scene_lightmaps[p_idx];
  244. LocalVector<int> &lightmap_indices = scene_lightmap_indices[p_idx];
  245. lightmap_indices.resize(buffer_size);
  246. for (unsigned int i = 0; i < lightmap_indices.size(); i++) {
  247. lightmap_indices[i] = -1;
  248. }
  249. MeshData &md = mesh_instances[p_idx].data;
  250. LocalVector<Ref<Image>> albedo_images;
  251. LocalVector<Ref<Image>> emission_images;
  252. for (int surface_id = 0; surface_id < md.albedo.size(); surface_id++) {
  253. albedo_images.push_back(_init_bake_texture(md.albedo[surface_id], albedo_textures, Image::FORMAT_RGBA8));
  254. emission_images.push_back(_init_bake_texture(md.emission[surface_id], emission_textures, Image::FORMAT_RGBH));
  255. }
  256. int surface_id = 0;
  257. int surface_facecount = 0;
  258. const Vector3 *points_ptr = md.points.ptr();
  259. const Vector3 *normals_ptr = md.normal.ptr();
  260. const Vector2 *uvs_ptr = md.uv.empty() ? nullptr : md.uv.ptr();
  261. const Vector2 *uv2s_ptr = md.uv2.ptr();
  262. for (int i = 0; i < md.points.size() / 3; i++) {
  263. Ref<Image> albedo = albedo_images[surface_id];
  264. Ref<Image> emission = emission_images[surface_id];
  265. albedo->lock();
  266. emission->lock();
  267. _plot_triangle(&(uv2s_ptr[i * 3]), &(points_ptr[i * 3]), &(normals_ptr[i * 3]), uvs_ptr ? &(uvs_ptr[i * 3]) : nullptr, albedo, emission, size, lightmap, lightmap_indices);
  268. albedo->unlock();
  269. emission->unlock();
  270. surface_facecount++;
  271. if (surface_facecount == md.surface_facecounts[surface_id]) {
  272. surface_id++;
  273. surface_facecount = 0;
  274. }
  275. }
  276. }
  277. Ref<Image> LightmapperCPU::_init_bake_texture(const MeshData::TextureDef &p_texture_def, const Map<RID, Ref<Image>> &p_tex_cache, Image::Format p_default_format) {
  278. Ref<Image> ret;
  279. if (p_texture_def.tex_rid.is_valid()) {
  280. ret = p_tex_cache[p_texture_def.tex_rid]->duplicate();
  281. ret->lock();
  282. for (int j = 0; j < ret->get_height(); j++) {
  283. for (int i = 0; i < ret->get_width(); i++) {
  284. ret->set_pixel(i, j, ret->get_pixel(i, j) * p_texture_def.mul + p_texture_def.add);
  285. }
  286. }
  287. ret->unlock();
  288. } else {
  289. ret.instance();
  290. ret->create(8, 8, false, p_default_format);
  291. ret->fill(p_texture_def.add * p_texture_def.mul);
  292. }
  293. return ret;
  294. }
  295. Color LightmapperCPU::_bilinear_sample(const Ref<Image> &p_img, const Vector2 &p_uv, bool p_clamp_x, bool p_clamp_y) {
  296. int width = p_img->get_width();
  297. int height = p_img->get_height();
  298. Vector2 uv;
  299. uv.x = p_clamp_x ? p_uv.x : Math::fposmod(p_uv.x, 1.0f);
  300. uv.y = p_clamp_y ? p_uv.y : Math::fposmod(p_uv.y, 1.0f);
  301. float xf = uv.x * width;
  302. float yf = uv.y * height;
  303. int xi = (int)xf;
  304. int yi = (int)yf;
  305. Color texels[4];
  306. for (int i = 0; i < 4; i++) {
  307. int sample_x = xi + i % 2;
  308. int sample_y = yi + i / 2;
  309. sample_x = CLAMP(sample_x, 0, width - 1);
  310. sample_y = CLAMP(sample_y, 0, height - 1);
  311. texels[i] = p_img->get_pixel(sample_x, sample_y);
  312. }
  313. float tx = xf - xi;
  314. float ty = yf - yi;
  315. Color c = Color(0, 0, 0, 0);
  316. for (int i = 0; i < 4; i++) {
  317. c[i] = Math::lerp(Math::lerp(texels[0][i], texels[1][i], tx), Math::lerp(texels[2][i], texels[3][i], tx), ty);
  318. }
  319. return c;
  320. }
  321. Vector3 LightmapperCPU::_fix_sample_position(const Vector3 &p_position, const Vector3 &p_texel_center, const Vector3 &p_normal, const Vector3 &p_tangent, const Vector3 &p_bitangent, const Vector2 &p_texel_size) {
  322. Basis tangent_basis(p_tangent, p_bitangent, p_normal);
  323. tangent_basis.orthonormalize();
  324. Vector2 half_size = p_texel_size / 2.0f;
  325. Vector3 corrected = p_position;
  326. for (int i = -1; i <= 1; i += 1) {
  327. for (int j = -1; j <= 1; j += 1) {
  328. if (i == 0 && j == 0) {
  329. continue;
  330. }
  331. Vector3 offset = Vector3(half_size.x * i, half_size.y * j, 0.0);
  332. Vector3 rotated_offset = tangent_basis.xform_inv(offset);
  333. Vector3 target = p_texel_center + rotated_offset;
  334. Vector3 ray_vector = target - corrected;
  335. Vector3 ray_back_offset = -ray_vector.normalized() * parameters.bias / 2.0;
  336. Vector3 ray_origin = corrected + ray_back_offset;
  337. ray_vector = target - ray_origin;
  338. float ray_length = ray_vector.length();
  339. LightmapRaycaster::Ray ray(ray_origin + p_normal * parameters.bias, ray_vector.normalized(), 0.0f, ray_length + parameters.bias / 2.0);
  340. bool hit = raycaster->intersect(ray);
  341. if (hit) {
  342. ray.normal.normalize();
  343. if (ray.normal.dot(ray_vector.normalized()) > 0.0f) {
  344. corrected = ray_origin + ray.dir * ray.tfar + ray.normal * (parameters.bias * 2.0f);
  345. }
  346. }
  347. }
  348. }
  349. return corrected;
  350. }
  351. void LightmapperCPU::_plot_triangle(const Vector2 *p_vertices, const Vector3 *p_positions, const Vector3 *p_normals, const Vector2 *p_uvs, const Ref<Image> &p_albedo, const Ref<Image> &p_emission, Vector2i p_size, LocalVector<LightmapTexel> &r_lightmap, LocalVector<int> &r_lightmap_indices) {
  352. Vector2 pv0 = p_vertices[0];
  353. Vector2 pv1 = p_vertices[1];
  354. Vector2 pv2 = p_vertices[2];
  355. Vector2 v0 = pv0 * p_size;
  356. Vector2 v1 = pv1 * p_size;
  357. Vector2 v2 = pv2 * p_size;
  358. Vector3 p0 = p_positions[0];
  359. Vector3 p1 = p_positions[1];
  360. Vector3 p2 = p_positions[2];
  361. Vector3 n0 = p_normals[0];
  362. Vector3 n1 = p_normals[1];
  363. Vector3 n2 = p_normals[2];
  364. Vector2 uv0 = p_uvs == nullptr ? Vector2(0.5f, 0.5f) : p_uvs[0];
  365. Vector2 uv1 = p_uvs == nullptr ? Vector2(0.5f, 0.5f) : p_uvs[1];
  366. Vector2 uv2 = p_uvs == nullptr ? Vector2(0.5f, 0.5f) : p_uvs[2];
  367. #define edgeFunction(a, b, c) ((c)[0] - (a)[0]) * ((b)[1] - (a)[1]) - ((c)[1] - (a)[1]) * ((b)[0] - (a)[0])
  368. if (edgeFunction(v0, v1, v2) < 0.0) {
  369. SWAP(pv1, pv2);
  370. SWAP(v1, v2);
  371. SWAP(p1, p2);
  372. SWAP(n1, n2);
  373. SWAP(uv1, uv2);
  374. }
  375. Vector3 edge1 = p1 - p0;
  376. Vector3 edge2 = p2 - p0;
  377. Vector2 uv_edge1 = pv1 - pv0;
  378. Vector2 uv_edge2 = pv2 - pv0;
  379. float r = 1.0f / (uv_edge1.x * uv_edge2.y - uv_edge1.y * uv_edge2.x);
  380. Vector3 tangent = (edge1 * uv_edge2.y - edge2 * uv_edge1.y) * r;
  381. Vector3 bitangent = (edge2 * uv_edge1.x - edge1 * uv_edge2.x) * r;
  382. tangent.normalize();
  383. bitangent.normalize();
  384. // Compute triangle bounding box
  385. Vector2 bbox_min = Vector2(MIN(v0.x, MIN(v1.x, v2.x)), MIN(v0.y, MIN(v1.y, v2.y)));
  386. Vector2 bbox_max = Vector2(MAX(v0.x, MAX(v1.x, v2.x)), MAX(v0.y, MAX(v1.y, v2.y)));
  387. bbox_min = bbox_min.floor();
  388. bbox_max = bbox_max.ceil();
  389. uint32_t min_x = MAX(bbox_min.x - 2, 0);
  390. uint32_t min_y = MAX(bbox_min.y - 2, 0);
  391. uint32_t max_x = MIN(bbox_max.x, p_size.x - 1);
  392. uint32_t max_y = MIN(bbox_max.y, p_size.y - 1);
  393. Vector2 texel_size;
  394. Vector2 centroid = (v0 + v1 + v2) / 3.0f;
  395. Vector3 centroid_pos = (p0 + p1 + p2) / 3.0f;
  396. for (int i = 0; i < 2; i++) {
  397. Vector2 p = centroid;
  398. p[i] += 1;
  399. Vector3 bary = Geometry::barycentric_coordinates_2d(p, v0, v1, v2);
  400. if (bary.length() <= 1.0) {
  401. Vector3 pos = p0 * bary[0] + p1 * bary[1] + p2 * bary[2];
  402. texel_size[i] = centroid_pos.distance_to(pos);
  403. }
  404. }
  405. Vector<Vector2> pixel_polygon;
  406. pixel_polygon.resize(4);
  407. static const Vector2 corners[4] = { Vector2(0, 0), Vector2(0, 1), Vector2(1, 1), Vector2(1, 0) };
  408. Vector<Vector2> triangle_polygon;
  409. triangle_polygon.push_back(v0);
  410. triangle_polygon.push_back(v1);
  411. triangle_polygon.push_back(v2);
  412. for (uint32_t j = min_y; j <= max_y; ++j) {
  413. for (uint32_t i = min_x; i <= max_x; i++) {
  414. int ofs = j * p_size.x + i;
  415. int texel_idx = r_lightmap_indices[ofs];
  416. if (texel_idx >= 0 && r_lightmap[texel_idx].area_coverage >= 0.5f) {
  417. continue;
  418. }
  419. Vector3 barycentric_coords;
  420. float area_coverage = 0.0f;
  421. bool intersected = false;
  422. for (int k = 0; k < 4; k++) {
  423. pixel_polygon.write[k] = Vector2(i, j) + corners[k];
  424. }
  425. const float max_dist = 0.05;
  426. bool v0eqv1 = v0.distance_squared_to(v1) < max_dist;
  427. bool v1eqv2 = v1.distance_squared_to(v2) < max_dist;
  428. bool v2eqv0 = v2.distance_squared_to(v0) < max_dist;
  429. if (v0eqv1 && v1eqv2 && v2eqv0) {
  430. intersected = true;
  431. barycentric_coords = Vector3(1, 0, 0);
  432. } else if (v0eqv1 || v1eqv2 || v2eqv0) {
  433. Vector<Vector2> segment;
  434. segment.resize(2);
  435. if (v0eqv1) {
  436. segment.write[0] = v0;
  437. segment.write[1] = v2;
  438. } else if (v1eqv2) {
  439. segment.write[0] = v1;
  440. segment.write[1] = v0;
  441. } else {
  442. segment.write[0] = v0;
  443. segment.write[1] = v1;
  444. }
  445. Vector<Vector<Vector2>> intersected_segments = Geometry::intersect_polyline_with_polygon_2d(segment, pixel_polygon);
  446. ERR_FAIL_COND_MSG(intersected_segments.size() > 1, "[Lightmapper] Itersecting a segment and a convex polygon should give at most one segment.");
  447. if (!intersected_segments.empty()) {
  448. const Vector<Vector2> &intersected_segment = intersected_segments[0];
  449. ERR_FAIL_COND_MSG(intersected_segment.size() != 2, "[Lightmapper] Itersecting a segment and a convex polygon should give at most one segment.");
  450. Vector2 sample_pos = (intersected_segment[0] + intersected_segment[1]) / 2.0f;
  451. float u = (segment[0].distance_to(sample_pos)) / (segment[0].distance_to(segment[1]));
  452. float v = (1.0f - u) / 2.0f;
  453. intersected = true;
  454. if (v0eqv1) {
  455. barycentric_coords = Vector3(v, v, u);
  456. } else if (v1eqv2) {
  457. barycentric_coords = Vector3(u, v, v);
  458. } else {
  459. barycentric_coords = Vector3(v, u, v);
  460. }
  461. }
  462. } else if (edgeFunction(v0, v1, v2) < 0.005) {
  463. Vector2 direction = v0 - v1;
  464. Vector2 perpendicular = Vector2(direction.y, -direction.x);
  465. Vector<Vector2> line;
  466. int middle_vertex;
  467. if (SGN(edgeFunction(v0, v0 + perpendicular, v1)) != SGN(edgeFunction(v0, v0 + perpendicular, v2))) {
  468. line.push_back(v1);
  469. line.push_back(v2);
  470. middle_vertex = 0;
  471. } else if (SGN(edgeFunction(v1, v1 + perpendicular, v0)) != SGN(edgeFunction(v1, v1 + perpendicular, v2))) {
  472. line.push_back(v0);
  473. line.push_back(v2);
  474. middle_vertex = 1;
  475. } else {
  476. line.push_back(v0);
  477. line.push_back(v1);
  478. middle_vertex = 2;
  479. }
  480. Vector<Vector<Vector2>> intersected_lines = Geometry::intersect_polyline_with_polygon_2d(line, pixel_polygon);
  481. ERR_FAIL_COND_MSG(intersected_lines.size() > 1, "[Lightmapper] Itersecting a line and a convex polygon should give at most one line.");
  482. if (!intersected_lines.empty()) {
  483. intersected = true;
  484. const Vector<Vector2> &intersected_line = intersected_lines[0];
  485. Vector2 sample_pos = (intersected_line[0] + intersected_line[1]) / 2.0f;
  486. float line_length = line[0].distance_to(line[1]);
  487. float norm = line[0].distance_to(sample_pos) / line_length;
  488. if (middle_vertex == 0) {
  489. barycentric_coords = Vector3(0.0f, 1.0f - norm, norm);
  490. } else if (middle_vertex == 1) {
  491. barycentric_coords = Vector3(1.0f - norm, 0.0f, norm);
  492. } else {
  493. barycentric_coords = Vector3(1.0f - norm, norm, 0.0f);
  494. }
  495. }
  496. } else {
  497. Vector<Vector<Vector2>> intersected_polygons = Geometry::intersect_polygons_2d(pixel_polygon, triangle_polygon);
  498. ERR_FAIL_COND_MSG(intersected_polygons.size() > 1, "[Lightmapper] Itersecting two convex polygons should give at most one polygon.");
  499. if (!intersected_polygons.empty()) {
  500. const Vector<Vector2> &intersected_polygon = intersected_polygons[0];
  501. // do centroid sampling
  502. Vector2 sample_pos = intersected_polygon[0];
  503. Vector2 area_center = Vector2(i, j) + Vector2(0.5f, 0.5f);
  504. float intersected_area = (intersected_polygon[0] - area_center).cross(intersected_polygon[intersected_polygon.size() - 1] - area_center);
  505. for (int k = 1; k < intersected_polygon.size(); k++) {
  506. sample_pos += intersected_polygon[k];
  507. intersected_area += (intersected_polygon[k] - area_center).cross(intersected_polygon[k - 1] - area_center);
  508. }
  509. if (intersected_area != 0.0f) {
  510. sample_pos /= intersected_polygon.size();
  511. barycentric_coords = Geometry::barycentric_coordinates_2d(sample_pos, v0, v1, v2);
  512. intersected = true;
  513. area_coverage = ABS(intersected_area) / 2.0f;
  514. }
  515. }
  516. if (!intersected) {
  517. for (int k = 0; k < 4; ++k) {
  518. for (int l = 0; l < 3; ++l) {
  519. Vector2 intersection_point;
  520. if (Geometry::segment_intersects_segment_2d(pixel_polygon[k], pixel_polygon[(k + 1) % 4], triangle_polygon[l], triangle_polygon[(l + 1) % 3], &intersection_point)) {
  521. intersected = true;
  522. barycentric_coords = Geometry::barycentric_coordinates_2d(intersection_point, v0, v1, v2);
  523. break;
  524. }
  525. }
  526. if (intersected) {
  527. break;
  528. }
  529. }
  530. }
  531. }
  532. if (texel_idx >= 0 && area_coverage < r_lightmap[texel_idx].area_coverage) {
  533. continue; // A previous triangle gives better pixel coverage
  534. }
  535. Vector2 pixel = Vector2(i, j);
  536. if (!intersected && v0.floor() == pixel) {
  537. intersected = true;
  538. barycentric_coords = Vector3(1, 0, 0);
  539. }
  540. if (!intersected && v1.floor() == pixel) {
  541. intersected = true;
  542. barycentric_coords = Vector3(0, 1, 0);
  543. }
  544. if (!intersected && v2.floor() == pixel) {
  545. intersected = true;
  546. barycentric_coords = Vector3(0, 0, 1);
  547. }
  548. if (!intersected) {
  549. continue;
  550. }
  551. if (Math::is_nan(barycentric_coords.x) || Math::is_nan(barycentric_coords.y) || Math::is_nan(barycentric_coords.z)) {
  552. continue;
  553. }
  554. if (Math::is_inf(barycentric_coords.x) || Math::is_inf(barycentric_coords.y) || Math::is_inf(barycentric_coords.z)) {
  555. continue;
  556. }
  557. r_lightmap_indices[ofs] = r_lightmap.size();
  558. Vector3 pos = p0 * barycentric_coords[0] + p1 * barycentric_coords[1] + p2 * barycentric_coords[2];
  559. Vector3 normal = n0 * barycentric_coords[0] + n1 * barycentric_coords[1] + n2 * barycentric_coords[2];
  560. Vector2 uv = uv0 * barycentric_coords[0] + uv1 * barycentric_coords[1] + uv2 * barycentric_coords[2];
  561. Color c = _bilinear_sample(p_albedo, uv);
  562. Color e = _bilinear_sample(p_emission, uv);
  563. Vector2 texel_center = Vector2(i, j) + Vector2(0.5f, 0.5f);
  564. Vector3 texel_center_bary = Geometry::barycentric_coordinates_2d(texel_center, v0, v1, v2);
  565. if (texel_center_bary.length_squared() <= 1.3 && !Math::is_nan(texel_center_bary.x) && !Math::is_nan(texel_center_bary.y) && !Math::is_nan(texel_center_bary.z) && !Math::is_inf(texel_center_bary.x) && !Math::is_inf(texel_center_bary.y) && !Math::is_inf(texel_center_bary.z)) {
  566. Vector3 texel_center_pos = p0 * texel_center_bary[0] + p1 * texel_center_bary[1] + p2 * texel_center_bary[2];
  567. pos = _fix_sample_position(pos, texel_center_pos, normal, tangent, bitangent, texel_size);
  568. }
  569. LightmapTexel texel;
  570. texel.normal = normal.normalized();
  571. texel.pos = pos;
  572. texel.albedo = Vector3(c.r, c.g, c.b);
  573. texel.alpha = c.a;
  574. texel.emission = Vector3(e.r, e.g, e.b);
  575. texel.area_coverage = area_coverage;
  576. r_lightmap.push_back(texel);
  577. }
  578. }
  579. }
  580. _ALWAYS_INLINE_ float uniform_rand() {
  581. /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
  582. static thread_local uint32_t state = Math::rand();
  583. state ^= state << 13;
  584. state ^= state >> 17;
  585. state ^= state << 5;
  586. /* implicit conversion from 'unsigned int' to 'float' changes value from 4294967295 to 4294967296 */
  587. return float(state) / float(UINT32_MAX);
  588. }
  589. float LightmapperCPU::_get_omni_attenuation(float distance, float inv_range, float decay) const {
  590. float nd = distance * inv_range;
  591. nd *= nd;
  592. nd *= nd; // nd^4
  593. nd = MAX(1.0 - nd, 0.0);
  594. nd *= nd; // nd^2
  595. return nd * powf(MAX(distance, 0.0001f), -decay);
  596. }
  597. void LightmapperCPU::_compute_direct_light(uint32_t p_idx, void *r_lightmap) {
  598. LightmapTexel *lightmap = (LightmapTexel *)r_lightmap;
  599. for (unsigned int i = 0; i < lights.size(); ++i) {
  600. const Light &light = lights[i];
  601. Vector3 normal = lightmap[p_idx].normal;
  602. Vector3 position = lightmap[p_idx].pos;
  603. Color c = light.color;
  604. Vector3 light_energy = Vector3(c.r, c.g, c.b) * light.energy;
  605. Vector3 light_to_point = light.direction;
  606. if (light.type == LIGHT_TYPE_OMNI || light.type == LIGHT_TYPE_SPOT) {
  607. light_to_point = (position - light.position).normalized();
  608. }
  609. if (normal.dot(light_to_point) >= 0.0) {
  610. continue;
  611. }
  612. float dist;
  613. float attenuation;
  614. float soft_shadowing_disk_size;
  615. if (light.type == LIGHT_TYPE_OMNI || light.type == LIGHT_TYPE_SPOT) {
  616. dist = position.distance_to(light.position);
  617. if (dist > light.range) {
  618. continue;
  619. }
  620. soft_shadowing_disk_size = light.size / dist;
  621. if (light.type == LIGHT_TYPE_OMNI) {
  622. if (parameters.use_physical_light_attenuation) {
  623. attenuation = _get_omni_attenuation(dist, 1.0f / light.range, light.attenuation);
  624. } else {
  625. attenuation = powf(1.0 - dist / light.range, light.attenuation);
  626. }
  627. } else /* (light.type == LIGHT_TYPE_SPOT) */ {
  628. float angle = Math::acos(light.direction.dot(light_to_point));
  629. if (angle > light.spot_angle) {
  630. continue;
  631. }
  632. float normalized_dist = dist * (1.0f / MAX(0.001f, light.range));
  633. float norm_light_attenuation;
  634. if (parameters.use_physical_light_attenuation) {
  635. norm_light_attenuation = _get_omni_attenuation(dist, 1.0f / light.range, light.attenuation);
  636. } else {
  637. norm_light_attenuation = Math::pow(MAX(1.0f - normalized_dist, 0.001f), light.attenuation);
  638. }
  639. float spot_cutoff = Math::cos(light.spot_angle);
  640. float scos = MAX(light_to_point.dot(light.direction), spot_cutoff);
  641. float spot_rim = (1.0f - scos) / (1.0f - spot_cutoff);
  642. attenuation = norm_light_attenuation * (1.0f - pow(MAX(spot_rim, 0.001f), light.spot_attenuation));
  643. }
  644. } else /*if (light.type == LIGHT_TYPE_DIRECTIONAL)*/ {
  645. dist = INFINITY;
  646. attenuation = 1.0f;
  647. soft_shadowing_disk_size = light.size;
  648. }
  649. float penumbra = 0.0f;
  650. if (light.size > 0.0) {
  651. Vector3 light_to_point_tan;
  652. Vector3 light_to_point_bitan;
  653. if (light.type == LIGHT_TYPE_OMNI || light.type == LIGHT_TYPE_SPOT) {
  654. light_to_point = (position - light.position).normalized();
  655. Vector3 aux = light_to_point.y < 0.777 ? Vector3(0, 1, 0) : Vector3(1, 0, 0);
  656. light_to_point_tan = light_to_point.cross(aux).normalized();
  657. light_to_point_bitan = light_to_point.cross(light_to_point_tan).normalized();
  658. } else /*if (light.type == LIGHT_TYPE_DIRECTIONAL)*/ {
  659. Vector3 aux = light_to_point.y < 0.777 ? Vector3(0, 1, 0) : Vector3(1, 0, 0);
  660. light_to_point_tan = light_to_point.cross(aux).normalized();
  661. light_to_point_bitan = light_to_point.cross(light_to_point_tan).normalized();
  662. }
  663. const static int shadowing_rays_check_penumbra_denom = 2;
  664. int shadowing_ray_count = parameters.samples;
  665. int hits = 0;
  666. Vector3 light_disk_to_point = light_to_point;
  667. for (int j = 0; j < shadowing_ray_count; j++) {
  668. // Optimization:
  669. // Once already casted an important proportion of rays, if all are hits or misses,
  670. // assume we're not in the penumbra so we can infer the rest would have the same result
  671. if (j == shadowing_ray_count / shadowing_rays_check_penumbra_denom) {
  672. if (hits == j) {
  673. // Assume totally lit
  674. hits = shadowing_ray_count;
  675. break;
  676. } else if (hits == 0) {
  677. // Assume totally dark
  678. hits = 0;
  679. break;
  680. }
  681. }
  682. float r = uniform_rand();
  683. float a = uniform_rand() * Math_TAU;
  684. Vector2 disk_sample = (r * Vector2(Math::cos(a), Math::sin(a))) * soft_shadowing_disk_size;
  685. light_disk_to_point = (light_to_point + disk_sample.x * light_to_point_tan + disk_sample.y * light_to_point_bitan).normalized();
  686. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position, -light_disk_to_point, parameters.bias, dist);
  687. if (raycaster->intersect(ray)) {
  688. continue;
  689. }
  690. hits++;
  691. }
  692. penumbra = (float)hits / shadowing_ray_count;
  693. } else {
  694. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position, -light_to_point, parameters.bias, dist);
  695. if (!raycaster->intersect(ray)) {
  696. penumbra = 1.0f;
  697. }
  698. }
  699. Vector3 final_energy = attenuation * penumbra * light_energy * MAX(0, normal.dot(-light_to_point));
  700. lightmap[p_idx].direct_light += final_energy * light.indirect_multiplier;
  701. if (light.bake_direct) {
  702. lightmap[p_idx].output_light += final_energy;
  703. }
  704. }
  705. }
  706. void LightmapperCPU::_compute_indirect_light(uint32_t p_idx, void *r_lightmap) {
  707. LightmapTexel *lightmap = (LightmapTexel *)r_lightmap;
  708. LightmapTexel &texel = lightmap[p_idx];
  709. Vector3 accum;
  710. const Vector3 const_forward = Vector3(0, 0, 1);
  711. const Vector3 const_up = Vector3(0, 1, 0);
  712. for (int i = 0; i < parameters.samples; i++) {
  713. Vector3 color;
  714. Vector3 throughput = Vector3(1.0f, 1.0f, 1.0f);
  715. Vector3 position = texel.pos;
  716. Vector3 normal = texel.normal;
  717. Vector3 direction;
  718. for (int depth = 0; depth < parameters.bounces; depth++) {
  719. Vector3 tangent = const_forward.cross(normal);
  720. if (unlikely(tangent.length_squared() < 0.005f)) {
  721. tangent = const_up.cross(normal);
  722. }
  723. tangent.normalize();
  724. Vector3 bitangent = tangent.cross(normal);
  725. bitangent.normalize();
  726. Basis normal_xform = Basis(tangent, bitangent, normal);
  727. normal_xform.transpose();
  728. float u1 = uniform_rand();
  729. float u2 = uniform_rand();
  730. float radius = Math::sqrt(u1);
  731. float theta = Math_TAU * u2;
  732. Vector3 axis = Vector3(radius * Math::cos(theta), radius * Math::sin(theta), Math::sqrt(MAX(0.0f, 1.0f - u1)));
  733. direction = normal_xform.xform(axis);
  734. // We can skip multiplying throughput by cos(theta) because de sampling PDF is also cos(theta) and they cancel each other
  735. //float pdf = normal.dot(direction);
  736. //throughput *= normal.dot(direction)/pdf;
  737. LightmapRaycaster::Ray ray(position, direction, parameters.bias);
  738. bool hit = raycaster->intersect(ray);
  739. if (!hit) {
  740. if (parameters.environment_panorama.is_valid()) {
  741. direction = parameters.environment_transform.xform_inv(direction);
  742. Vector2 st = Vector2(Math::atan2(direction.z, direction.x), Math::acos(direction.y));
  743. if (Math::is_nan(st.y)) {
  744. st.y = direction.y > 0.0 ? 0.0 : Math_PI;
  745. }
  746. st.x += Math_PI;
  747. st /= Vector2(Math_TAU, Math_PI);
  748. st.x = Math::fmod(st.x + 0.75, 1.0);
  749. Color c = _bilinear_sample(parameters.environment_panorama, st, false, true);
  750. color += throughput * Vector3(c.r, c.g, c.b) * c.a;
  751. }
  752. break;
  753. }
  754. unsigned int hit_mesh_id = ray.geomID;
  755. const Vector2i &size = mesh_instances[hit_mesh_id].size;
  756. int x = CLAMP(ray.u * size.x, 0, size.x - 1);
  757. int y = CLAMP(ray.v * size.y, 0, size.y - 1);
  758. const int idx = scene_lightmap_indices[hit_mesh_id][y * size.x + x];
  759. if (idx < 0) {
  760. break;
  761. }
  762. const LightmapTexel &sample = scene_lightmaps[hit_mesh_id][idx];
  763. if (sample.normal.dot(ray.dir) > 0.0 && !no_shadow_meshes.has(hit_mesh_id)) {
  764. // We hit a back-face
  765. break;
  766. }
  767. color += throughput * sample.emission;
  768. throughput *= sample.albedo;
  769. color += throughput * sample.direct_light * parameters.bounce_indirect_energy;
  770. // Russian Roulette
  771. // https://computergraphics.stackexchange.com/questions/2316/is-russian-roulette-really-the-answer
  772. const float p = throughput[throughput.max_axis()];
  773. if (uniform_rand() > p) {
  774. break;
  775. }
  776. throughput *= 1.0f / p;
  777. position = sample.pos;
  778. normal = sample.normal;
  779. }
  780. accum += color;
  781. }
  782. texel.output_light += accum / parameters.samples;
  783. }
  784. void LightmapperCPU::_post_process(uint32_t p_idx, void *r_output) {
  785. const MeshInstance &mesh = mesh_instances[p_idx];
  786. if (!mesh.generate_lightmap) {
  787. return;
  788. }
  789. LocalVector<int> &indices = scene_lightmap_indices[p_idx];
  790. LocalVector<LightmapTexel> &lightmap = scene_lightmaps[p_idx];
  791. Vector3 *output = ((LocalVector<Vector3> *)r_output)[p_idx].ptr();
  792. Vector2i size = mesh.size;
  793. // Blit texels to buffer
  794. const int margin = 4;
  795. for (int i = 0; i < size.y; i++) {
  796. for (int j = 0; j < size.x; j++) {
  797. int idx = indices[i * size.x + j];
  798. if (idx >= 0) {
  799. output[i * size.x + j] = lightmap[idx].output_light;
  800. continue; // filled, skip
  801. }
  802. int closest_idx = -1;
  803. float closest_dist = 1e20;
  804. for (int y = i - margin; y <= i + margin; y++) {
  805. for (int x = j - margin; x <= j + margin; x++) {
  806. if (x == j && y == i) {
  807. continue;
  808. }
  809. if (x < 0 || x >= size.x) {
  810. continue;
  811. }
  812. if (y < 0 || y >= size.y) {
  813. continue;
  814. }
  815. int cell_idx = indices[y * size.x + x];
  816. if (cell_idx < 0) {
  817. continue; //also ensures that blitted stuff is not reused
  818. }
  819. float dist = Vector2(i - y, j - x).length_squared();
  820. if (dist < closest_dist) {
  821. closest_dist = dist;
  822. closest_idx = cell_idx;
  823. }
  824. }
  825. }
  826. if (closest_idx != -1) {
  827. output[i * size.x + j] = lightmap[closest_idx].output_light;
  828. }
  829. }
  830. }
  831. lightmap.clear();
  832. LocalVector<UVSeam> seams;
  833. _compute_seams(mesh, seams);
  834. _fix_seams(seams, output, size);
  835. _dilate_lightmap(output, indices, size, margin);
  836. if (parameters.use_denoiser) {
  837. Ref<LightmapDenoiser> denoiser = LightmapDenoiser::create();
  838. if (denoiser.is_valid()) {
  839. int data_size = size.x * size.y * sizeof(Vector3);
  840. Ref<Image> current_image;
  841. current_image.instance();
  842. {
  843. PoolByteArray data;
  844. data.resize(data_size);
  845. PoolByteArray::Write w = data.write();
  846. memcpy(w.ptr(), output, data_size);
  847. current_image->create(size.x, size.y, false, Image::FORMAT_RGBF, data);
  848. }
  849. Ref<Image> denoised_image = denoiser->denoise_image(current_image);
  850. PoolByteArray denoised_data = denoised_image->get_data();
  851. denoised_image.unref();
  852. PoolByteArray::Read r = denoised_data.read();
  853. memcpy(output, r.ptr(), data_size);
  854. }
  855. }
  856. _dilate_lightmap(output, indices, size, margin);
  857. _fix_seams(seams, output, size);
  858. _dilate_lightmap(output, indices, size, margin);
  859. indices.clear();
  860. }
  861. void LightmapperCPU::_compute_seams(const MeshInstance &p_mesh, LocalVector<UVSeam> &r_seams) {
  862. float max_uv_distance = 1.0f / MAX(p_mesh.size.x, p_mesh.size.y);
  863. max_uv_distance *= max_uv_distance; // We use distance_to_squared(), so we need to square the max distance as well
  864. float max_pos_distance = 0.00025f;
  865. float max_normal_distance = 0.05f;
  866. const Vector<Vector3> &points = p_mesh.data.points;
  867. const Vector<Vector2> &uv2s = p_mesh.data.uv2;
  868. const Vector<Vector3> &normals = p_mesh.data.normal;
  869. LocalVector<SeamEdge> edges;
  870. edges.resize(points.size()); // One edge per vertex
  871. for (int i = 0; i < points.size(); i += 3) {
  872. Vector3 triangle_vtxs[3] = { points[i + 0], points[i + 1], points[i + 2] };
  873. Vector2 triangle_uvs[3] = { uv2s[i + 0], uv2s[i + 1], uv2s[i + 2] };
  874. Vector3 triangle_normals[3] = { normals[i + 0], normals[i + 1], normals[i + 2] };
  875. for (int k = 0; k < 3; k++) {
  876. int idx[2];
  877. idx[0] = k;
  878. idx[1] = (k + 1) % 3;
  879. if (triangle_vtxs[idx[1]] < triangle_vtxs[idx[0]]) {
  880. SWAP(idx[0], idx[1]);
  881. }
  882. SeamEdge e;
  883. for (int l = 0; l < 2; ++l) {
  884. e.pos[l] = triangle_vtxs[idx[l]];
  885. e.uv[l] = triangle_uvs[idx[l]];
  886. e.normal[l] = triangle_normals[idx[l]];
  887. }
  888. edges[i + k] = e;
  889. }
  890. }
  891. edges.sort();
  892. for (unsigned int j = 0; j < edges.size(); j++) {
  893. const SeamEdge &edge0 = edges[j];
  894. if (edge0.uv[0].distance_squared_to(edge0.uv[1]) < 0.001) {
  895. continue;
  896. }
  897. if (edge0.pos[0].distance_squared_to(edge0.pos[1]) < 0.001) {
  898. continue;
  899. }
  900. for (unsigned int k = j + 1; k < edges.size() && edges[k].pos[0].x < (edge0.pos[0].x + max_pos_distance * 1.1f); k++) {
  901. const SeamEdge &edge1 = edges[k];
  902. if (edge1.uv[0].distance_squared_to(edge1.uv[1]) < 0.001) {
  903. continue;
  904. }
  905. if (edge1.pos[0].distance_squared_to(edge1.pos[1]) < 0.001) {
  906. continue;
  907. }
  908. if (edge0.uv[0].distance_squared_to(edge1.uv[0]) < max_uv_distance && edge0.uv[1].distance_squared_to(edge1.uv[1]) < max_uv_distance) {
  909. continue;
  910. }
  911. if (edge0.pos[0].distance_squared_to(edge1.pos[0]) > max_pos_distance || edge0.pos[1].distance_squared_to(edge1.pos[1]) > max_pos_distance) {
  912. continue;
  913. }
  914. if (edge0.normal[0].distance_squared_to(edge1.normal[0]) > max_normal_distance || edge0.normal[1].distance_squared_to(edge1.normal[1]) > max_normal_distance) {
  915. continue;
  916. }
  917. UVSeam s;
  918. s.edge0[0] = edge0.uv[0];
  919. s.edge0[1] = edge0.uv[1];
  920. s.edge1[0] = edge1.uv[0];
  921. s.edge1[1] = edge1.uv[1];
  922. r_seams.push_back(s);
  923. }
  924. }
  925. }
  926. void LightmapperCPU::_fix_seams(const LocalVector<UVSeam> &p_seams, Vector3 *r_lightmap, Vector2i p_size) {
  927. LocalVector<Vector3> extra_buffer;
  928. extra_buffer.resize(p_size.x * p_size.y);
  929. memcpy(extra_buffer.ptr(), r_lightmap, p_size.x * p_size.y * sizeof(Vector3));
  930. Vector3 *read_ptr = extra_buffer.ptr();
  931. Vector3 *write_ptr = r_lightmap;
  932. for (int i = 0; i < 5; i++) {
  933. for (unsigned int j = 0; j < p_seams.size(); j++) {
  934. _fix_seam(p_seams[j].edge0[0], p_seams[j].edge0[1], p_seams[j].edge1[0], p_seams[j].edge1[1], read_ptr, write_ptr, p_size);
  935. _fix_seam(p_seams[j].edge1[0], p_seams[j].edge1[1], p_seams[j].edge0[0], p_seams[j].edge0[1], read_ptr, write_ptr, p_size);
  936. }
  937. memcpy(read_ptr, write_ptr, p_size.x * p_size.y * sizeof(Vector3));
  938. }
  939. }
  940. void LightmapperCPU::_fix_seam(const Vector2 &p_pos0, const Vector2 &p_pos1, const Vector2 &p_uv0, const Vector2 &p_uv1, const Vector3 *p_read_buffer, Vector3 *r_write_buffer, const Vector2i &p_size) {
  941. Vector2 line[2];
  942. line[0] = p_pos0 * p_size;
  943. line[1] = p_pos1 * p_size;
  944. const Vector2i start_pixel = line[0].floor();
  945. const Vector2i end_pixel = line[1].floor();
  946. Vector2 seam_dir = (line[1] - line[0]).normalized();
  947. Vector2 t_delta = Vector2(1.0f / Math::abs(seam_dir.x), 1.0f / Math::abs(seam_dir.y));
  948. Vector2i step = Vector2(seam_dir.x > 0 ? 1 : (seam_dir.x < 0 ? -1 : 0), seam_dir.y > 0 ? 1 : (seam_dir.y < 0 ? -1 : 0));
  949. Vector2 t_next = Vector2(Math::fmod(line[0].x, 1.0f), Math::fmod(line[0].y, 1.0f));
  950. if (step.x == 1) {
  951. t_next.x = 1.0f - t_next.x;
  952. }
  953. if (step.y == 1) {
  954. t_next.y = 1.0f - t_next.y;
  955. }
  956. t_next.x /= Math::abs(seam_dir.x);
  957. t_next.y /= Math::abs(seam_dir.y);
  958. if (Math::is_nan(t_next.x)) {
  959. t_next.x = 1e20f;
  960. }
  961. if (Math::is_nan(t_next.y)) {
  962. t_next.y = 1e20f;
  963. }
  964. Vector2i pixel = start_pixel;
  965. Vector2 start_p = start_pixel;
  966. float line_length = line[0].distance_to(line[1]);
  967. if (line_length == 0.0f) {
  968. return;
  969. }
  970. while (start_p.distance_to(pixel) < line_length + 1.0f) {
  971. Vector2 current_point = Vector2(pixel) + Vector2(0.5f, 0.5f);
  972. current_point = Geometry::get_closest_point_to_segment_2d(current_point, line);
  973. float t = line[0].distance_to(current_point) / line_length;
  974. Vector2 current_uv = p_uv0 * (1.0 - t) + p_uv1 * t;
  975. Vector2i sampled_point = (current_uv * p_size).floor();
  976. Vector3 current_color = r_write_buffer[pixel.y * p_size.x + pixel.x];
  977. Vector3 sampled_color = p_read_buffer[sampled_point.y * p_size.x + sampled_point.x];
  978. r_write_buffer[pixel.y * p_size.x + pixel.x] = current_color * 0.6f + sampled_color * 0.4f;
  979. if (pixel == end_pixel) {
  980. break;
  981. }
  982. if (t_next.x < t_next.y) {
  983. pixel.x += step.x;
  984. t_next.x += t_delta.x;
  985. } else {
  986. pixel.y += step.y;
  987. t_next.y += t_delta.y;
  988. }
  989. }
  990. }
  991. void LightmapperCPU::_dilate_lightmap(Vector3 *r_lightmap, const LocalVector<int> p_indices, Vector2i p_size, int margin) {
  992. for (int i = 0; i < p_size.y; i++) {
  993. for (int j = 0; j < p_size.x; j++) {
  994. int idx = p_indices[i * p_size.x + j];
  995. if (idx >= 0) {
  996. continue; //filled, skip
  997. }
  998. Vector2i closest;
  999. float closest_dist = 1e20;
  1000. for (int y = i - margin; y <= i + margin; y++) {
  1001. for (int x = j - margin; x <= j + margin; x++) {
  1002. if (x == j && y == i) {
  1003. continue;
  1004. }
  1005. if (x < 0 || x >= p_size.x) {
  1006. continue;
  1007. }
  1008. if (y < 0 || y >= p_size.y) {
  1009. continue;
  1010. }
  1011. int cell_idx = p_indices[y * p_size.x + x];
  1012. if (cell_idx < 0) {
  1013. continue; //also ensures that blitted stuff is not reused
  1014. }
  1015. float dist = Vector2(i - y, j - x).length_squared();
  1016. if (dist < closest_dist) {
  1017. closest_dist = dist;
  1018. closest = Vector2(x, y);
  1019. }
  1020. }
  1021. }
  1022. if (closest_dist < 1e20) {
  1023. r_lightmap[i * p_size.x + j] = r_lightmap[closest.y * p_size.x + closest.x];
  1024. }
  1025. }
  1026. }
  1027. }
  1028. void LightmapperCPU::_blit_lightmap(const Vector<Vector3> &p_src, const Vector2i &p_size, Ref<Image> &p_dst, int p_x, int p_y, bool p_with_padding) {
  1029. int padding = p_with_padding ? 1 : 0;
  1030. ERR_FAIL_COND(p_x < padding || p_y < padding);
  1031. ERR_FAIL_COND(p_x + p_size.x > p_dst->get_width() - padding);
  1032. ERR_FAIL_COND(p_y + p_size.y > p_dst->get_height() - padding);
  1033. p_dst->lock();
  1034. for (int y = 0; y < p_size.y; y++) {
  1035. const Vector3 *__restrict src = p_src.ptr() + y * p_size.x;
  1036. for (int x = 0; x < p_size.x; x++) {
  1037. p_dst->set_pixel(p_x + x, p_y + y, Color(src->x, src->y, src->z));
  1038. src++;
  1039. }
  1040. }
  1041. if (p_with_padding) {
  1042. for (int y = -1; y < p_size.y + 1; y++) {
  1043. int yy = CLAMP(y, 0, p_size.y - 1);
  1044. int idx_left = yy * p_size.x;
  1045. int idx_right = idx_left + p_size.x - 1;
  1046. p_dst->set_pixel(p_x - 1, p_y + y, Color(p_src[idx_left].x, p_src[idx_left].y, p_src[idx_left].z));
  1047. p_dst->set_pixel(p_x + p_size.x, p_y + y, Color(p_src[idx_right].x, p_src[idx_right].y, p_src[idx_right].z));
  1048. }
  1049. for (int x = -1; x < p_size.x + 1; x++) {
  1050. int xx = CLAMP(x, 0, p_size.x - 1);
  1051. int idx_top = xx;
  1052. int idx_bot = idx_top + (p_size.y - 1) * p_size.x;
  1053. p_dst->set_pixel(p_x + x, p_y - 1, Color(p_src[idx_top].x, p_src[idx_top].y, p_src[idx_top].z));
  1054. p_dst->set_pixel(p_x + x, p_y + p_size.y, Color(p_src[idx_bot].x, p_src[idx_bot].y, p_src[idx_bot].z));
  1055. }
  1056. }
  1057. p_dst->unlock();
  1058. }
  1059. LightmapperCPU::BakeError LightmapperCPU::bake(BakeQuality p_quality, bool p_use_denoiser, int p_bounces, float p_bounce_indirect_energy, float p_bias, bool p_generate_atlas, int p_max_texture_size, const Ref<Image> &p_environment_panorama, const Basis &p_environment_transform, BakeStepFunc p_step_function, void *p_bake_userdata, BakeStepFunc p_substep_function) {
  1060. if (p_step_function) {
  1061. bool cancelled = p_step_function(0.0, TTR("Begin Bake"), p_bake_userdata, true);
  1062. if (cancelled) {
  1063. return BAKE_ERROR_USER_ABORTED;
  1064. }
  1065. }
  1066. raycaster = LightmapRaycaster::create();
  1067. ERR_FAIL_COND_V(raycaster.is_null(), BAKE_ERROR_NO_RAYCASTER);
  1068. // Collect parameters
  1069. parameters.use_denoiser = p_use_denoiser;
  1070. parameters.use_physical_light_attenuation = bool(GLOBAL_GET("rendering/quality/shading/use_physical_light_attenuation"));
  1071. parameters.bias = p_bias;
  1072. parameters.bounces = p_bounces;
  1073. parameters.bounce_indirect_energy = p_bounce_indirect_energy;
  1074. parameters.environment_transform = p_environment_transform;
  1075. parameters.environment_panorama = p_environment_panorama;
  1076. switch (p_quality) {
  1077. case BAKE_QUALITY_LOW: {
  1078. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/low_quality_ray_count");
  1079. } break;
  1080. case BAKE_QUALITY_MEDIUM: {
  1081. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/medium_quality_ray_count");
  1082. } break;
  1083. case BAKE_QUALITY_HIGH: {
  1084. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/high_quality_ray_count");
  1085. } break;
  1086. case BAKE_QUALITY_ULTRA: {
  1087. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/ultra_quality_ray_count");
  1088. } break;
  1089. }
  1090. bake_textures.clear();
  1091. if (p_step_function) {
  1092. bool cancelled = p_step_function(0.1, TTR("Preparing data structures"), p_bake_userdata, true);
  1093. if (cancelled) {
  1094. return BAKE_ERROR_USER_ABORTED;
  1095. }
  1096. }
  1097. bool has_baked_mesh = false;
  1098. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1099. if (mesh_instances[i].generate_lightmap) {
  1100. has_baked_mesh = true;
  1101. }
  1102. raycaster->add_mesh(mesh_instances[i].data.points, mesh_instances[i].data.normal, mesh_instances[i].data.uv2, i);
  1103. }
  1104. if (!has_baked_mesh) {
  1105. return BAKE_ERROR_NO_MESHES;
  1106. }
  1107. raycaster->commit();
  1108. scene_lightmaps.resize(mesh_instances.size());
  1109. scene_lightmap_indices.resize(mesh_instances.size());
  1110. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1111. if (!mesh_instances[i].cast_shadows) {
  1112. no_shadow_meshes.insert(i);
  1113. }
  1114. }
  1115. raycaster->set_mesh_filter(no_shadow_meshes);
  1116. Vector2i atlas_size = Vector2i(-1, -1);
  1117. int atlas_slices = -1;
  1118. if (p_generate_atlas) {
  1119. Error err = _layout_atlas(p_max_texture_size, &atlas_size, &atlas_slices);
  1120. if (err != OK) {
  1121. return BAKE_ERROR_LIGHTMAP_TOO_SMALL;
  1122. }
  1123. }
  1124. if (p_step_function) {
  1125. bool cancelled = p_step_function(0.2, TTR("Generate buffers"), p_bake_userdata, true);
  1126. if (cancelled) {
  1127. return BAKE_ERROR_USER_ABORTED;
  1128. }
  1129. }
  1130. if (_parallel_run(mesh_instances.size(), "Rasterizing meshes", &LightmapperCPU::_generate_buffer, nullptr, p_substep_function)) {
  1131. return BAKE_ERROR_USER_ABORTED;
  1132. }
  1133. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1134. const Size2i &size = mesh_instances[i].size;
  1135. bool has_alpha = false;
  1136. PoolVector<uint8_t> alpha_data;
  1137. alpha_data.resize(size.x * size.y);
  1138. {
  1139. PoolVector<uint8_t>::Write w = alpha_data.write();
  1140. for (unsigned int j = 0; j < scene_lightmap_indices[i].size(); ++j) {
  1141. int idx = scene_lightmap_indices[i][j];
  1142. uint8_t alpha = 0;
  1143. if (idx >= 0) {
  1144. alpha = CLAMP(scene_lightmaps[i][idx].alpha * 255, 0, 255);
  1145. if (alpha < 255) {
  1146. has_alpha = true;
  1147. }
  1148. }
  1149. w[j] = alpha;
  1150. }
  1151. }
  1152. if (has_alpha) {
  1153. Ref<Image> alpha_texture;
  1154. alpha_texture.instance();
  1155. alpha_texture->create(size.x, size.y, false, Image::FORMAT_L8, alpha_data);
  1156. raycaster->set_mesh_alpha_texture(alpha_texture, i);
  1157. }
  1158. }
  1159. albedo_textures.clear();
  1160. emission_textures.clear();
  1161. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1162. if (p_step_function) {
  1163. float p = float(i) / mesh_instances.size();
  1164. bool cancelled = p_step_function(0.2 + p * 0.2, vformat("%s (%d/%d)", TTR("Direct lighting"), i, mesh_instances.size()), p_bake_userdata, false);
  1165. if (cancelled) {
  1166. return BAKE_ERROR_USER_ABORTED;
  1167. }
  1168. }
  1169. if (_parallel_run(scene_lightmaps[i].size(), "Computing direct light", &LightmapperCPU::_compute_direct_light, scene_lightmaps[i].ptr(), p_substep_function)) {
  1170. return BAKE_ERROR_USER_ABORTED;
  1171. }
  1172. }
  1173. raycaster->clear_mesh_filter();
  1174. int n_lit_meshes = 0;
  1175. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1176. if (mesh_instances[i].generate_lightmap) {
  1177. n_lit_meshes++;
  1178. }
  1179. }
  1180. if (parameters.environment_panorama.is_valid()) {
  1181. parameters.environment_panorama->lock();
  1182. }
  1183. if (parameters.bounces > 0) {
  1184. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1185. if (!mesh_instances[i].generate_lightmap) {
  1186. continue;
  1187. }
  1188. if (p_step_function) {
  1189. float p = float(i) / n_lit_meshes;
  1190. bool cancelled = p_step_function(0.4 + p * 0.4, vformat("%s (%d/%d)", TTR("Indirect lighting"), i, mesh_instances.size()), p_bake_userdata, false);
  1191. if (cancelled) {
  1192. return BAKE_ERROR_USER_ABORTED;
  1193. }
  1194. }
  1195. if (!scene_lightmaps[i].empty()) {
  1196. if (_parallel_run(scene_lightmaps[i].size(), "Computing indirect light", &LightmapperCPU::_compute_indirect_light, scene_lightmaps[i].ptr(), p_substep_function)) {
  1197. return BAKE_ERROR_USER_ABORTED;
  1198. }
  1199. }
  1200. }
  1201. }
  1202. if (parameters.environment_panorama.is_valid()) {
  1203. parameters.environment_panorama->unlock();
  1204. }
  1205. raycaster.unref(); // Not needed anymore, free some memory.
  1206. LocalVector<LocalVector<Vector3>> lightmaps_data;
  1207. lightmaps_data.resize(mesh_instances.size());
  1208. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1209. if (mesh_instances[i].generate_lightmap) {
  1210. const Vector2i size = mesh_instances[i].size;
  1211. lightmaps_data[i].resize(size.x * size.y);
  1212. }
  1213. }
  1214. if (p_step_function) {
  1215. bool cancelled = p_step_function(0.8, TTR("Post processing"), p_bake_userdata, true);
  1216. if (cancelled) {
  1217. return BAKE_ERROR_USER_ABORTED;
  1218. }
  1219. }
  1220. if (_parallel_run(mesh_instances.size(), "Denoise & fix seams", &LightmapperCPU::_post_process, lightmaps_data.ptr(), p_substep_function)) {
  1221. return BAKE_ERROR_USER_ABORTED;
  1222. }
  1223. if (p_generate_atlas) {
  1224. bake_textures.resize(atlas_slices);
  1225. for (int i = 0; i < atlas_slices; i++) {
  1226. Ref<Image> image;
  1227. image.instance();
  1228. image->create(atlas_size.x, atlas_size.y, false, Image::FORMAT_RGBH);
  1229. bake_textures[i] = image;
  1230. }
  1231. } else {
  1232. bake_textures.resize(mesh_instances.size());
  1233. Set<String> used_mesh_names;
  1234. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1235. if (!mesh_instances[i].generate_lightmap) {
  1236. continue;
  1237. }
  1238. String mesh_name = mesh_instances[i].node_name;
  1239. if (mesh_name == "" || mesh_name.find(":") != -1 || mesh_name.find("/") != -1) {
  1240. mesh_name = "LightMap";
  1241. }
  1242. if (used_mesh_names.has(mesh_name)) {
  1243. int idx = 2;
  1244. String base = mesh_name;
  1245. while (true) {
  1246. mesh_name = base + itos(idx);
  1247. if (!used_mesh_names.has(mesh_name)) {
  1248. break;
  1249. }
  1250. idx++;
  1251. }
  1252. }
  1253. used_mesh_names.insert(mesh_name);
  1254. Ref<Image> image;
  1255. image.instance();
  1256. image->create(mesh_instances[i].size.x, mesh_instances[i].size.y, false, Image::FORMAT_RGBH);
  1257. image->set_name(mesh_name);
  1258. bake_textures[i] = image;
  1259. }
  1260. }
  1261. if (p_step_function) {
  1262. bool cancelled = p_step_function(0.9, TTR("Plotting lightmaps"), p_bake_userdata, true);
  1263. if (cancelled) {
  1264. return BAKE_ERROR_USER_ABORTED;
  1265. }
  1266. }
  1267. {
  1268. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1269. if (!mesh_instances[i].generate_lightmap) {
  1270. continue;
  1271. }
  1272. if (p_generate_atlas) {
  1273. _blit_lightmap(lightmaps_data[i], mesh_instances[i].size, bake_textures[mesh_instances[i].slice], mesh_instances[i].offset.x, mesh_instances[i].offset.y, true);
  1274. } else {
  1275. _blit_lightmap(lightmaps_data[i], mesh_instances[i].size, bake_textures[i], 0, 0, false);
  1276. }
  1277. }
  1278. }
  1279. return BAKE_OK;
  1280. }
  1281. int LightmapperCPU::get_bake_texture_count() const {
  1282. return bake_textures.size();
  1283. }
  1284. Ref<Image> LightmapperCPU::get_bake_texture(int p_index) const {
  1285. ERR_FAIL_INDEX_V(p_index, (int)bake_textures.size(), Ref<Image>());
  1286. return bake_textures[p_index];
  1287. }
  1288. int LightmapperCPU::get_bake_mesh_count() const {
  1289. return mesh_instances.size();
  1290. }
  1291. Variant LightmapperCPU::get_bake_mesh_userdata(int p_index) const {
  1292. ERR_FAIL_INDEX_V(p_index, (int)mesh_instances.size(), Variant());
  1293. return mesh_instances[p_index].data.userdata;
  1294. }
  1295. Rect2 LightmapperCPU::get_bake_mesh_uv_scale(int p_index) const {
  1296. ERR_FAIL_COND_V(bake_textures.size() == 0, Rect2());
  1297. Rect2 uv_ofs;
  1298. Vector2 atlas_size = Vector2(bake_textures[0]->get_width(), bake_textures[0]->get_height());
  1299. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  1300. uv_ofs.size = Vector2(mesh_instances[p_index].size) / atlas_size;
  1301. return uv_ofs;
  1302. }
  1303. int LightmapperCPU::get_bake_mesh_texture_slice(int p_index) const {
  1304. ERR_FAIL_INDEX_V(p_index, (int)mesh_instances.size(), Variant());
  1305. return mesh_instances[p_index].slice;
  1306. }
  1307. void LightmapperCPU::add_albedo_texture(Ref<Texture> p_texture) {
  1308. if (p_texture.is_null()) {
  1309. return;
  1310. }
  1311. RID texture_rid = p_texture->get_rid();
  1312. if (!texture_rid.is_valid() || albedo_textures.has(texture_rid)) {
  1313. return;
  1314. }
  1315. Ref<Image> texture_data = p_texture->get_data();
  1316. if (texture_data.is_null()) {
  1317. return;
  1318. }
  1319. if (texture_data->is_compressed()) {
  1320. texture_data->decompress();
  1321. }
  1322. texture_data->convert(Image::FORMAT_RGBA8);
  1323. albedo_textures.insert(texture_rid, texture_data);
  1324. }
  1325. void LightmapperCPU::add_emission_texture(Ref<Texture> p_texture) {
  1326. if (p_texture.is_null()) {
  1327. return;
  1328. }
  1329. RID texture_rid = p_texture->get_rid();
  1330. if (!texture_rid.is_valid() || emission_textures.has(texture_rid)) {
  1331. return;
  1332. }
  1333. Ref<Image> texture_data = p_texture->get_data();
  1334. if (texture_data.is_null()) {
  1335. return;
  1336. }
  1337. if (texture_data->is_compressed()) {
  1338. texture_data->decompress();
  1339. }
  1340. texture_data->convert(Image::FORMAT_RGBH);
  1341. emission_textures.insert(texture_rid, texture_data);
  1342. }
  1343. void LightmapperCPU::add_mesh(const MeshData &p_mesh, Vector2i p_size) {
  1344. ERR_FAIL_COND(p_mesh.points.size() == 0);
  1345. ERR_FAIL_COND(p_mesh.points.size() != p_mesh.uv2.size());
  1346. ERR_FAIL_COND(p_mesh.points.size() != p_mesh.normal.size());
  1347. ERR_FAIL_COND(!p_mesh.uv.empty() && p_mesh.points.size() != p_mesh.uv.size());
  1348. ERR_FAIL_COND(p_mesh.surface_facecounts.size() != p_mesh.albedo.size());
  1349. ERR_FAIL_COND(p_mesh.surface_facecounts.size() != p_mesh.emission.size());
  1350. MeshInstance mi;
  1351. mi.data = p_mesh;
  1352. mi.size = p_size;
  1353. mi.generate_lightmap = true;
  1354. mi.cast_shadows = true;
  1355. mi.node_name = "";
  1356. Dictionary userdata = p_mesh.userdata;
  1357. if (userdata.has("cast_shadows")) {
  1358. mi.cast_shadows = userdata["cast_shadows"];
  1359. }
  1360. if (userdata.has("generate_lightmap")) {
  1361. mi.generate_lightmap = userdata["generate_lightmap"];
  1362. }
  1363. if (userdata.has("node_name")) {
  1364. mi.node_name = userdata["node_name"];
  1365. }
  1366. mesh_instances.push_back(mi);
  1367. }
  1368. void LightmapperCPU::add_directional_light(bool p_bake_direct, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_multiplier, float p_size) {
  1369. Light l;
  1370. l.type = LIGHT_TYPE_DIRECTIONAL;
  1371. l.direction = p_direction;
  1372. l.color = p_color;
  1373. l.energy = p_energy;
  1374. l.indirect_multiplier = p_indirect_multiplier;
  1375. l.bake_direct = p_bake_direct;
  1376. l.size = p_size;
  1377. lights.push_back(l);
  1378. }
  1379. void LightmapperCPU::add_omni_light(bool p_bake_direct, const Vector3 &p_position, const Color &p_color, float p_energy, float p_indirect_multiplier, float p_range, float p_attenuation, float p_size) {
  1380. Light l;
  1381. l.type = LIGHT_TYPE_OMNI;
  1382. l.position = p_position;
  1383. l.range = p_range;
  1384. l.attenuation = p_attenuation;
  1385. l.color = p_color;
  1386. l.energy = p_energy;
  1387. l.indirect_multiplier = p_indirect_multiplier;
  1388. l.bake_direct = p_bake_direct;
  1389. l.size = p_size;
  1390. lights.push_back(l);
  1391. }
  1392. void LightmapperCPU::add_spot_light(bool p_bake_direct, const Vector3 &p_position, const Vector3 p_direction, const Color &p_color, float p_energy, float p_indirect_multiplier, float p_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size) {
  1393. Light l;
  1394. l.type = LIGHT_TYPE_SPOT;
  1395. l.position = p_position;
  1396. l.direction = p_direction;
  1397. l.range = p_range;
  1398. l.attenuation = p_attenuation;
  1399. l.spot_angle = Math::deg2rad(p_spot_angle);
  1400. l.spot_attenuation = p_spot_attenuation;
  1401. l.color = p_color;
  1402. l.energy = p_energy;
  1403. l.indirect_multiplier = p_indirect_multiplier;
  1404. l.bake_direct = p_bake_direct;
  1405. l.size = p_size;
  1406. lights.push_back(l);
  1407. }
  1408. LightmapperCPU::LightmapperCPU() {
  1409. thread_progress = 0;
  1410. thread_cancelled = false;
  1411. }