lightmapper_cpu.cpp 52 KB

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