lightmapper_cpu.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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;
  219. runner_thread.start(_thread_func_callback, &td);
  220. int progress = thread_progress;
  221. while (!cancelled && progress < p_count) {
  222. float p = float(progress) / p_count;
  223. if (p_substep_func) {
  224. cancelled = p_substep_func(p, vformat("%s (%d/%d)", p_description, progress + 1, p_count), nullptr, false);
  225. }
  226. progress = thread_progress;
  227. }
  228. thread_cancelled = cancelled;
  229. runner_thread.wait_to_finish();
  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 / 2.0;
  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 / 2.0);
  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. if (bary.length() <= 1.0) {
  393. Vector3 pos = p0 * bary[0] + p1 * bary[1] + p2 * bary[2];
  394. texel_size[i] = centroid_pos.distance_to(pos);
  395. }
  396. }
  397. Vector<Vector2> pixel_polygon;
  398. pixel_polygon.resize(4);
  399. static const Vector2 corners[4] = { Vector2(0, 0), Vector2(0, 1), Vector2(1, 1), Vector2(1, 0) };
  400. Vector<Vector2> triangle_polygon;
  401. triangle_polygon.push_back(v0);
  402. triangle_polygon.push_back(v1);
  403. triangle_polygon.push_back(v2);
  404. for (uint32_t j = min_y; j <= max_y; ++j) {
  405. for (uint32_t i = min_x; i <= max_x; i++) {
  406. int ofs = j * p_size.x + i;
  407. int texel_idx = r_lightmap_indices[ofs];
  408. if (texel_idx >= 0 && r_lightmap[texel_idx].area_coverage >= 0.5f) {
  409. continue;
  410. }
  411. Vector3 barycentric_coords;
  412. float area_coverage = 0.0f;
  413. bool intersected = false;
  414. for (int k = 0; k < 4; k++) {
  415. pixel_polygon.write[k] = Vector2(i, j) + corners[k];
  416. }
  417. const float max_dist = 0.05;
  418. bool v0eqv1 = v0.distance_squared_to(v1) < max_dist;
  419. bool v1eqv2 = v1.distance_squared_to(v2) < max_dist;
  420. bool v2eqv0 = v2.distance_squared_to(v0) < max_dist;
  421. if (v0eqv1 && v1eqv2 && v2eqv0) {
  422. intersected = true;
  423. barycentric_coords = Vector3(1, 0, 0);
  424. } else if (v0eqv1 || v1eqv2 || v2eqv0) {
  425. Vector<Vector2> segment;
  426. segment.resize(2);
  427. if (v0eqv1) {
  428. segment.write[0] = v0;
  429. segment.write[1] = v2;
  430. } else if (v1eqv2) {
  431. segment.write[0] = v1;
  432. segment.write[1] = v0;
  433. } else {
  434. segment.write[0] = v0;
  435. segment.write[1] = v1;
  436. }
  437. Vector<Vector<Vector2> > intersected_segments = Geometry::intersect_polyline_with_polygon_2d(segment, pixel_polygon);
  438. ERR_FAIL_COND_MSG(intersected_segments.size() > 1, "[Lightmapper] Itersecting a segment and a convex polygon should give at most one segment.");
  439. if (!intersected_segments.empty()) {
  440. const Vector<Vector2> &intersected_segment = intersected_segments[0];
  441. ERR_FAIL_COND_MSG(intersected_segment.size() != 2, "[Lightmapper] Itersecting a segment and a convex polygon should give at most one segment.");
  442. Vector2 sample_pos = (intersected_segment[0] + intersected_segment[1]) / 2.0f;
  443. float u = (segment[0].distance_to(sample_pos)) / (segment[0].distance_to(segment[1]));
  444. float v = (1.0f - u) / 2.0f;
  445. intersected = true;
  446. if (v0eqv1) {
  447. barycentric_coords = Vector3(v, v, u);
  448. } else if (v1eqv2) {
  449. barycentric_coords = Vector3(u, v, v);
  450. } else {
  451. barycentric_coords = Vector3(v, u, v);
  452. }
  453. }
  454. } else if (edgeFunction(v0, v1, v2) < 0.005) {
  455. Vector2 direction = v0 - v1;
  456. Vector2 perpendicular = Vector2(direction.y, -direction.x);
  457. Vector<Vector2> line;
  458. int middle_vertex;
  459. if (SGN(edgeFunction(v0, v0 + perpendicular, v1)) != SGN(edgeFunction(v0, v0 + perpendicular, v2))) {
  460. line.push_back(v1);
  461. line.push_back(v2);
  462. middle_vertex = 0;
  463. } else if (SGN(edgeFunction(v1, v1 + perpendicular, v0)) != SGN(edgeFunction(v1, v1 + perpendicular, v2))) {
  464. line.push_back(v0);
  465. line.push_back(v2);
  466. middle_vertex = 1;
  467. } else {
  468. line.push_back(v0);
  469. line.push_back(v1);
  470. middle_vertex = 2;
  471. }
  472. Vector<Vector<Vector2> > intersected_lines = Geometry::intersect_polyline_with_polygon_2d(line, pixel_polygon);
  473. ERR_FAIL_COND_MSG(intersected_lines.size() > 1, "[Lightmapper] Itersecting a line and a convex polygon should give at most one line.");
  474. if (!intersected_lines.empty()) {
  475. intersected = true;
  476. const Vector<Vector2> &intersected_line = intersected_lines[0];
  477. Vector2 sample_pos = (intersected_line[0] + intersected_line[1]) / 2.0f;
  478. float line_length = line[0].distance_to(line[1]);
  479. float norm = line[0].distance_to(sample_pos) / line_length;
  480. if (middle_vertex == 0) {
  481. barycentric_coords = Vector3(0.0f, 1.0f - norm, norm);
  482. } else if (middle_vertex == 1) {
  483. barycentric_coords = Vector3(1.0f - norm, 0.0f, norm);
  484. } else {
  485. barycentric_coords = Vector3(1.0f - norm, norm, 0.0f);
  486. }
  487. }
  488. } else {
  489. Vector<Vector<Vector2> > intersected_polygons = Geometry::intersect_polygons_2d(pixel_polygon, triangle_polygon);
  490. ERR_FAIL_COND_MSG(intersected_polygons.size() > 1, "[Lightmapper] Itersecting two convex polygons should give at most one polygon.");
  491. if (!intersected_polygons.empty()) {
  492. const Vector<Vector2> &intersected_polygon = intersected_polygons[0];
  493. // do centroid sampling
  494. Vector2 sample_pos = intersected_polygon[0];
  495. Vector2 area_center = Vector2(i, j) + Vector2(0.5f, 0.5f);
  496. float intersected_area = (intersected_polygon[0] - area_center).cross(intersected_polygon[intersected_polygon.size() - 1] - area_center);
  497. for (int k = 1; k < intersected_polygon.size(); k++) {
  498. sample_pos += intersected_polygon[k];
  499. intersected_area += (intersected_polygon[k] - area_center).cross(intersected_polygon[k - 1] - area_center);
  500. }
  501. if (intersected_area != 0.0f) {
  502. sample_pos /= intersected_polygon.size();
  503. barycentric_coords = Geometry::barycentric_coordinates_2d(sample_pos, v0, v1, v2);
  504. intersected = true;
  505. area_coverage = ABS(intersected_area) / 2.0f;
  506. }
  507. }
  508. if (!intersected) {
  509. for (int k = 0; k < 4; ++k) {
  510. for (int l = 0; l < 3; ++l) {
  511. Vector2 intersection_point;
  512. if (Geometry::segment_intersects_segment_2d(pixel_polygon[k], pixel_polygon[(k + 1) % 4], triangle_polygon[l], triangle_polygon[(l + 1) % 3], &intersection_point)) {
  513. intersected = true;
  514. barycentric_coords = Geometry::barycentric_coordinates_2d(intersection_point, v0, v1, v2);
  515. break;
  516. }
  517. }
  518. if (intersected) {
  519. break;
  520. }
  521. }
  522. }
  523. }
  524. if (texel_idx >= 0 && area_coverage < r_lightmap[texel_idx].area_coverage) {
  525. continue; // A previous triangle gives better pixel coverage
  526. }
  527. Vector2 pixel = Vector2(i, j);
  528. if (!intersected && v0.floor() == pixel) {
  529. intersected = true;
  530. barycentric_coords = Vector3(1, 0, 0);
  531. }
  532. if (!intersected && v1.floor() == pixel) {
  533. intersected = true;
  534. barycentric_coords = Vector3(0, 1, 0);
  535. }
  536. if (!intersected && v2.floor() == pixel) {
  537. intersected = true;
  538. barycentric_coords = Vector3(0, 0, 1);
  539. }
  540. if (!intersected) {
  541. continue;
  542. }
  543. if (Math::is_nan(barycentric_coords.x) || Math::is_nan(barycentric_coords.y) || Math::is_nan(barycentric_coords.z)) {
  544. continue;
  545. }
  546. if (Math::is_inf(barycentric_coords.x) || Math::is_inf(barycentric_coords.y) || Math::is_inf(barycentric_coords.z)) {
  547. continue;
  548. }
  549. r_lightmap_indices[ofs] = r_lightmap.size();
  550. Vector3 pos = p0 * barycentric_coords[0] + p1 * barycentric_coords[1] + p2 * barycentric_coords[2];
  551. Vector3 normal = n0 * barycentric_coords[0] + n1 * barycentric_coords[1] + n2 * barycentric_coords[2];
  552. Vector2 uv = uv0 * barycentric_coords[0] + uv1 * barycentric_coords[1] + uv2 * barycentric_coords[2];
  553. Color c = _bilinear_sample(p_albedo, uv);
  554. Color e = _bilinear_sample(p_emission, uv);
  555. Vector2 texel_center = Vector2(i, j) + Vector2(0.5f, 0.5f);
  556. Vector3 texel_center_bary = Geometry::barycentric_coordinates_2d(texel_center, v0, v1, v2);
  557. 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)) {
  558. Vector3 texel_center_pos = p0 * texel_center_bary[0] + p1 * texel_center_bary[1] + p2 * texel_center_bary[2];
  559. pos = _fix_sample_position(pos, texel_center_pos, normal, tangent, bitangent, texel_size);
  560. }
  561. LightmapTexel texel;
  562. texel.normal = normal.normalized();
  563. texel.pos = pos;
  564. texel.albedo = Vector3(c.r, c.g, c.b);
  565. texel.alpha = c.a;
  566. texel.emission = Vector3(e.r, e.g, e.b);
  567. texel.area_coverage = area_coverage;
  568. r_lightmap.push_back(texel);
  569. }
  570. }
  571. }
  572. void LightmapperCPU::_compute_direct_light(uint32_t p_idx, void *r_lightmap) {
  573. LightmapTexel *lightmap = (LightmapTexel *)r_lightmap;
  574. for (unsigned int i = 0; i < lights.size(); ++i) {
  575. const Light &light = lights[i];
  576. Vector3 normal = lightmap[p_idx].normal;
  577. Vector3 position = lightmap[p_idx].pos;
  578. Vector3 final_energy;
  579. Color c = light.color;
  580. Vector3 light_energy = Vector3(c.r, c.g, c.b) * light.energy;
  581. if (light.type == LIGHT_TYPE_OMNI) {
  582. Vector3 light_direction = (position - light.position).normalized();
  583. if (normal.dot(light_direction) >= 0.0) {
  584. continue;
  585. }
  586. float dist = position.distance_to(light.position);
  587. if (dist <= light.range) {
  588. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position, -light_direction, parameters.bias, dist - parameters.bias);
  589. if (raycaster->intersect(ray)) {
  590. continue;
  591. }
  592. float att = powf(1.0 - dist / light.range, light.attenuation);
  593. final_energy = light_energy * att * MAX(0, normal.dot(-light_direction));
  594. }
  595. }
  596. if (light.type == LIGHT_TYPE_SPOT) {
  597. Vector3 light_direction = (position - light.position).normalized();
  598. if (normal.dot(light_direction) >= 0.0) {
  599. continue;
  600. }
  601. float angle = Math::acos(light.direction.dot(light_direction));
  602. if (angle > light.spot_angle) {
  603. continue;
  604. }
  605. float dist = position.distance_to(light.position);
  606. if (dist > light.range) {
  607. continue;
  608. }
  609. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position, -light_direction, parameters.bias, dist);
  610. if (raycaster->intersect(ray)) {
  611. continue;
  612. }
  613. float normalized_dist = dist * (1.0f / MAX(0.001f, light.range));
  614. float norm_light_attenuation = Math::pow(MAX(1.0f - normalized_dist, 0.001f), light.attenuation);
  615. float spot_cutoff = Math::cos(light.spot_angle);
  616. float scos = MAX(light_direction.dot(light.direction), spot_cutoff);
  617. float spot_rim = (1.0f - scos) / (1.0f - spot_cutoff);
  618. norm_light_attenuation *= 1.0f - pow(MAX(spot_rim, 0.001f), light.spot_attenuation);
  619. final_energy = light_energy * norm_light_attenuation * MAX(0, normal.dot(-light_direction));
  620. }
  621. if (light.type == LIGHT_TYPE_DIRECTIONAL) {
  622. if (normal.dot(light.direction) >= 0.0) {
  623. continue;
  624. }
  625. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position + normal * parameters.bias, -light.direction, parameters.bias);
  626. if (raycaster->intersect(ray)) {
  627. continue;
  628. }
  629. final_energy = light_energy * MAX(0, normal.dot(-light.direction));
  630. }
  631. lightmap[p_idx].direct_light += final_energy * light.indirect_multiplier;
  632. if (light.bake_direct) {
  633. lightmap[p_idx].output_light += final_energy;
  634. }
  635. }
  636. }
  637. _ALWAYS_INLINE_ float uniform_rand() {
  638. /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
  639. static thread_local uint32_t state = Math::rand();
  640. state ^= state << 13;
  641. state ^= state >> 17;
  642. state ^= state << 5;
  643. /* implicit conversion from 'unsigned int' to 'float' changes value from 4294967295 to 4294967296 */
  644. return float(state) / float(UINT32_MAX);
  645. }
  646. void LightmapperCPU::_compute_indirect_light(uint32_t p_idx, void *r_lightmap) {
  647. LightmapTexel *lightmap = (LightmapTexel *)r_lightmap;
  648. LightmapTexel &texel = lightmap[p_idx];
  649. Vector3 accum;
  650. const Vector3 const_forward = Vector3(0, 0, 1);
  651. const Vector3 const_up = Vector3(0, 1, 0);
  652. for (int i = 0; i < parameters.samples; i++) {
  653. Vector3 color;
  654. Vector3 throughput = Vector3(1.0f, 1.0f, 1.0f);
  655. Vector3 position = texel.pos;
  656. Vector3 normal = texel.normal;
  657. Vector3 direction;
  658. for (int depth = 0; depth < parameters.bounces; depth++) {
  659. Vector3 tangent = const_forward.cross(normal);
  660. if (unlikely(tangent.length_squared() < 0.005f)) {
  661. tangent = const_up.cross(normal);
  662. }
  663. tangent.normalize();
  664. Vector3 bitangent = tangent.cross(normal);
  665. bitangent.normalize();
  666. Basis normal_xform = Basis(tangent, bitangent, normal);
  667. normal_xform.transpose();
  668. float u1 = uniform_rand();
  669. float u2 = uniform_rand();
  670. float radius = Math::sqrt(u1);
  671. float theta = Math_TAU * u2;
  672. Vector3 axis = Vector3(radius * Math::cos(theta), radius * Math::sin(theta), Math::sqrt(MAX(0.0f, 1.0f - u1)));
  673. direction = normal_xform.xform(axis);
  674. // We can skip multiplying throughput by cos(theta) because de sampling PDF is also cos(theta) and they cancel each other
  675. //float pdf = normal.dot(direction);
  676. //throughput *= normal.dot(direction)/pdf;
  677. LightmapRaycaster::Ray ray(position, direction, parameters.bias);
  678. bool hit = raycaster->intersect(ray);
  679. if (!hit) {
  680. if (parameters.environment_panorama.is_valid()) {
  681. direction = parameters.environment_transform.xform_inv(direction);
  682. Vector2 st = Vector2(Math::atan2(direction.z, direction.x), Math::acos(direction.y));
  683. if (Math::is_nan(st.y)) {
  684. st.y = direction.y > 0.0 ? 0.0 : Math_PI;
  685. }
  686. st.x += Math_PI;
  687. st /= Vector2(Math_TAU, Math_PI);
  688. st.x = Math::fmod(st.x + 0.75, 1.0);
  689. Color c = _bilinear_sample(parameters.environment_panorama, st, false, true);
  690. color += throughput * Vector3(c.r, c.g, c.b) * c.a;
  691. }
  692. break;
  693. }
  694. unsigned int hit_mesh_id = ray.geomID;
  695. const Vector2i &size = mesh_instances[hit_mesh_id].size;
  696. int x = CLAMP(ray.u * size.x, 0, size.x - 1);
  697. int y = CLAMP(ray.v * size.y, 0, size.y - 1);
  698. const int idx = scene_lightmap_indices[hit_mesh_id][y * size.x + x];
  699. if (idx < 0) {
  700. break;
  701. }
  702. const LightmapTexel &sample = scene_lightmaps[hit_mesh_id][idx];
  703. if (sample.normal.dot(ray.dir) > 0.0 && !no_shadow_meshes.has(hit_mesh_id)) {
  704. // We hit a back-face
  705. break;
  706. }
  707. color += throughput * sample.emission;
  708. throughput *= sample.albedo;
  709. color += throughput * sample.direct_light;
  710. // Russian Roulette
  711. // https://computergraphics.stackexchange.com/questions/2316/is-russian-roulette-really-the-answer
  712. const float p = throughput[throughput.max_axis()];
  713. if (uniform_rand() > p) {
  714. break;
  715. }
  716. throughput *= 1.0f / p;
  717. position = sample.pos;
  718. normal = sample.normal;
  719. }
  720. accum += color;
  721. }
  722. texel.output_light += accum / parameters.samples;
  723. }
  724. void LightmapperCPU::_post_process(uint32_t p_idx, void *r_output) {
  725. const MeshInstance &mesh = mesh_instances[p_idx];
  726. if (!mesh.generate_lightmap) {
  727. return;
  728. }
  729. LocalVector<int> &indices = scene_lightmap_indices[p_idx];
  730. LocalVector<LightmapTexel> &lightmap = scene_lightmaps[p_idx];
  731. Vector3 *output = ((LocalVector<Vector3> *)r_output)[p_idx].ptr();
  732. Vector2i size = mesh.size;
  733. // Blit texels to buffer
  734. const int margin = 4;
  735. for (int i = 0; i < size.y; i++) {
  736. for (int j = 0; j < size.x; j++) {
  737. int idx = indices[i * size.x + j];
  738. if (idx >= 0) {
  739. output[i * size.x + j] = lightmap[idx].output_light;
  740. continue; // filled, skip
  741. }
  742. int closest_idx = -1;
  743. float closest_dist = 1e20;
  744. for (int y = i - margin; y <= i + margin; y++) {
  745. for (int x = j - margin; x <= j + margin; x++) {
  746. if (x == j && y == i)
  747. continue;
  748. if (x < 0 || x >= size.x)
  749. continue;
  750. if (y < 0 || y >= size.y)
  751. continue;
  752. int cell_idx = indices[y * size.x + x];
  753. if (cell_idx < 0) {
  754. continue; //also ensures that blitted stuff is not reused
  755. }
  756. float dist = Vector2(i - y, j - x).length_squared();
  757. if (dist < closest_dist) {
  758. closest_dist = dist;
  759. closest_idx = cell_idx;
  760. }
  761. }
  762. }
  763. if (closest_idx != -1) {
  764. output[i * size.x + j] = lightmap[closest_idx].output_light;
  765. }
  766. }
  767. }
  768. lightmap.clear();
  769. LocalVector<UVSeam> seams;
  770. _compute_seams(mesh, seams);
  771. _fix_seams(seams, output, size);
  772. _dilate_lightmap(output, indices, size, margin);
  773. if (parameters.use_denoiser) {
  774. Ref<LightmapDenoiser> denoiser = LightmapDenoiser::create();
  775. if (denoiser.is_valid()) {
  776. int data_size = size.x * size.y * sizeof(Vector3);
  777. Ref<Image> current_image;
  778. current_image.instance();
  779. {
  780. PoolByteArray data;
  781. data.resize(data_size);
  782. PoolByteArray::Write w = data.write();
  783. memcpy(w.ptr(), output, data_size);
  784. current_image->create(size.x, size.y, false, Image::FORMAT_RGBF, data);
  785. }
  786. Ref<Image> denoised_image = denoiser->denoise_image(current_image);
  787. PoolByteArray denoised_data = denoised_image->get_data();
  788. denoised_image.unref();
  789. PoolByteArray::Read r = denoised_data.read();
  790. memcpy(output, r.ptr(), data_size);
  791. }
  792. }
  793. _dilate_lightmap(output, indices, size, margin);
  794. _fix_seams(seams, output, size);
  795. _dilate_lightmap(output, indices, size, margin);
  796. indices.clear();
  797. }
  798. void LightmapperCPU::_compute_seams(const MeshInstance &p_mesh, LocalVector<UVSeam> &r_seams) {
  799. float max_uv_distance = 1.0f / MAX(p_mesh.size.x, p_mesh.size.y);
  800. max_uv_distance *= max_uv_distance; // We use distance_to_squared(), so wee need to square the max distance as well
  801. float max_pos_distance = 0.00025f;
  802. float max_normal_distance = 0.05f;
  803. const Vector<Vector3> &points = p_mesh.data.points;
  804. const Vector<Vector2> &uv2s = p_mesh.data.uv2;
  805. const Vector<Vector3> &normals = p_mesh.data.normal;
  806. LocalVector<SeamEdge> edges;
  807. edges.resize(points.size()); // One edge per vertex
  808. for (int i = 0; i < points.size(); i += 3) {
  809. Vector3 triangle_vtxs[3] = { points[i + 0], points[i + 1], points[i + 2] };
  810. Vector2 triangle_uvs[3] = { uv2s[i + 0], uv2s[i + 1], uv2s[i + 2] };
  811. Vector3 triangle_normals[3] = { normals[i + 0], normals[i + 1], normals[i + 2] };
  812. for (int k = 0; k < 3; k++) {
  813. int idx[2];
  814. idx[0] = k;
  815. idx[1] = (k + 1) % 3;
  816. if (triangle_vtxs[idx[1]] < triangle_vtxs[idx[0]]) {
  817. SWAP(idx[0], idx[1]);
  818. }
  819. SeamEdge e;
  820. for (int l = 0; l < 2; ++l) {
  821. e.pos[l] = triangle_vtxs[idx[l]];
  822. e.uv[l] = triangle_uvs[idx[l]];
  823. e.normal[l] = triangle_normals[idx[l]];
  824. }
  825. edges[i + k] = e;
  826. }
  827. }
  828. edges.sort();
  829. for (unsigned int j = 0; j < edges.size(); j++) {
  830. const SeamEdge &edge0 = edges[j];
  831. if (edge0.uv[0].distance_squared_to(edge0.uv[1]) < 0.001) {
  832. continue;
  833. }
  834. if (edge0.pos[0].distance_squared_to(edge0.pos[1]) < 0.001) {
  835. continue;
  836. }
  837. for (unsigned int k = j + 1; k < edges.size() && edges[k].pos[0].x < (edge0.pos[0].x + max_pos_distance * 1.1f); k++) {
  838. const SeamEdge &edge1 = edges[k];
  839. if (edge1.uv[0].distance_squared_to(edge1.uv[1]) < 0.001) {
  840. continue;
  841. }
  842. if (edge1.pos[0].distance_squared_to(edge1.pos[1]) < 0.001) {
  843. continue;
  844. }
  845. 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) {
  846. continue;
  847. }
  848. 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) {
  849. continue;
  850. }
  851. 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) {
  852. continue;
  853. }
  854. UVSeam s;
  855. s.edge0[0] = edge0.uv[0];
  856. s.edge0[1] = edge0.uv[1];
  857. s.edge1[0] = edge1.uv[0];
  858. s.edge1[1] = edge1.uv[1];
  859. r_seams.push_back(s);
  860. }
  861. }
  862. }
  863. void LightmapperCPU::_fix_seams(const LocalVector<UVSeam> &p_seams, Vector3 *r_lightmap, Vector2i p_size) {
  864. LocalVector<Vector3> extra_buffer;
  865. extra_buffer.resize(p_size.x * p_size.y);
  866. memcpy(extra_buffer.ptr(), r_lightmap, p_size.x * p_size.y * sizeof(Vector3));
  867. Vector3 *read_ptr = extra_buffer.ptr();
  868. Vector3 *write_ptr = r_lightmap;
  869. for (int i = 0; i < 5; i++) {
  870. for (unsigned int j = 0; j < p_seams.size(); j++) {
  871. _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);
  872. _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);
  873. }
  874. memcpy(read_ptr, write_ptr, p_size.x * p_size.y * sizeof(Vector3));
  875. }
  876. }
  877. 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) {
  878. Vector2 line[2];
  879. line[0] = p_pos0 * p_size;
  880. line[1] = p_pos1 * p_size;
  881. const Vector2i start_pixel = line[0].floor();
  882. const Vector2i end_pixel = line[1].floor();
  883. Vector2 seam_dir = (line[1] - line[0]).normalized();
  884. Vector2 t_delta = Vector2(1.0f / Math::abs(seam_dir.x), 1.0f / Math::abs(seam_dir.y));
  885. 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));
  886. Vector2 t_next = Vector2(Math::fmod(line[0].x, 1.0f), Math::fmod(line[0].y, 1.0f));
  887. if (step.x == 1) {
  888. t_next.x = 1.0f - t_next.x;
  889. }
  890. if (step.y == 1) {
  891. t_next.y = 1.0f - t_next.y;
  892. }
  893. t_next.x /= Math::abs(seam_dir.x);
  894. t_next.y /= Math::abs(seam_dir.y);
  895. if (Math::is_nan(t_next.x)) {
  896. t_next.x = 1e20f;
  897. }
  898. if (Math::is_nan(t_next.y)) {
  899. t_next.y = 1e20f;
  900. }
  901. Vector2i pixel = start_pixel;
  902. Vector2 start_p = start_pixel;
  903. float line_length = line[0].distance_to(line[1]);
  904. if (line_length == 0.0f) {
  905. return;
  906. }
  907. while (start_p.distance_to(pixel) < line_length + 1.0f) {
  908. Vector2 current_point = Vector2(pixel) + Vector2(0.5f, 0.5f);
  909. current_point = Geometry::get_closest_point_to_segment_2d(current_point, line);
  910. float t = line[0].distance_to(current_point) / line_length;
  911. Vector2 current_uv = p_uv0 * (1.0 - t) + p_uv1 * t;
  912. Vector2i sampled_point = (current_uv * p_size).floor();
  913. Vector3 current_color = r_write_buffer[pixel.y * p_size.x + pixel.x];
  914. Vector3 sampled_color = p_read_buffer[sampled_point.y * p_size.x + sampled_point.x];
  915. r_write_buffer[pixel.y * p_size.x + pixel.x] = current_color * 0.6f + sampled_color * 0.4f;
  916. if (pixel == end_pixel) {
  917. break;
  918. }
  919. if (t_next.x < t_next.y) {
  920. pixel.x += step.x;
  921. t_next.x += t_delta.x;
  922. } else {
  923. pixel.y += step.y;
  924. t_next.y += t_delta.y;
  925. }
  926. }
  927. }
  928. void LightmapperCPU::_dilate_lightmap(Vector3 *r_lightmap, const LocalVector<int> p_indices, Vector2i p_size, int margin) {
  929. for (int i = 0; i < p_size.y; i++) {
  930. for (int j = 0; j < p_size.x; j++) {
  931. int idx = p_indices[i * p_size.x + j];
  932. if (idx >= 0) {
  933. continue; //filled, skip
  934. }
  935. Vector2i closest;
  936. float closest_dist = 1e20;
  937. for (int y = i - margin; y <= i + margin; y++) {
  938. for (int x = j - margin; x <= j + margin; x++) {
  939. if (x == j && y == i)
  940. continue;
  941. if (x < 0 || x >= p_size.x)
  942. continue;
  943. if (y < 0 || y >= p_size.y)
  944. continue;
  945. int cell_idx = p_indices[y * p_size.x + x];
  946. if (cell_idx < 0) {
  947. continue; //also ensures that blitted stuff is not reused
  948. }
  949. float dist = Vector2(i - y, j - x).length_squared();
  950. if (dist < closest_dist) {
  951. closest_dist = dist;
  952. closest = Vector2(x, y);
  953. }
  954. }
  955. }
  956. if (closest_dist < 1e20) {
  957. r_lightmap[i * p_size.x + j] = r_lightmap[closest.y * p_size.x + closest.x];
  958. }
  959. }
  960. }
  961. }
  962. 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) {
  963. int padding = p_with_padding ? 1 : 0;
  964. ERR_FAIL_COND(p_x < padding || p_y < padding);
  965. ERR_FAIL_COND(p_x + p_size.x > p_dst->get_width() - padding);
  966. ERR_FAIL_COND(p_y + p_size.y > p_dst->get_height() - padding);
  967. p_dst->lock();
  968. for (int y = 0; y < p_size.y; y++) {
  969. const Vector3 *__restrict src = p_src.ptr() + y * p_size.x;
  970. for (int x = 0; x < p_size.x; x++) {
  971. p_dst->set_pixel(p_x + x, p_y + y, Color(src->x, src->y, src->z));
  972. src++;
  973. }
  974. }
  975. if (p_with_padding) {
  976. for (int y = -1; y < p_size.y + 1; y++) {
  977. int yy = CLAMP(y, 0, p_size.y - 1);
  978. int idx_left = yy * p_size.x;
  979. int idx_right = idx_left + p_size.x - 1;
  980. 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));
  981. 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));
  982. }
  983. for (int x = -1; x < p_size.x + 1; x++) {
  984. int xx = CLAMP(x, 0, p_size.x - 1);
  985. int idx_top = xx;
  986. int idx_bot = idx_top + (p_size.y - 1) * p_size.x;
  987. 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));
  988. 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));
  989. }
  990. }
  991. p_dst->unlock();
  992. }
  993. 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) {
  994. if (p_step_function) {
  995. bool cancelled = p_step_function(0.0, TTR("Begin Bake"), p_bake_userdata, true);
  996. if (cancelled) {
  997. return BAKE_ERROR_USER_ABORTED;
  998. }
  999. }
  1000. raycaster = LightmapRaycaster::create();
  1001. ERR_FAIL_COND_V(raycaster.is_null(), BAKE_ERROR_NO_RAYCASTER);
  1002. // Collect parameters
  1003. parameters.use_denoiser = p_use_denoiser;
  1004. parameters.bias = p_bias;
  1005. parameters.bounces = p_bounces;
  1006. parameters.environment_transform = p_environment_transform;
  1007. parameters.environment_panorama = p_environment_panorama;
  1008. switch (p_quality) {
  1009. case BAKE_QUALITY_LOW: {
  1010. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/low_quality_ray_count");
  1011. } break;
  1012. case BAKE_QUALITY_MEDIUM: {
  1013. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/medium_quality_ray_count");
  1014. } break;
  1015. case BAKE_QUALITY_HIGH: {
  1016. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/high_quality_ray_count");
  1017. } break;
  1018. case BAKE_QUALITY_ULTRA: {
  1019. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/ultra_quality_ray_count");
  1020. } break;
  1021. }
  1022. bake_textures.clear();
  1023. if (p_step_function) {
  1024. bool cancelled = p_step_function(0.1, TTR("Preparing data structures"), p_bake_userdata, true);
  1025. if (cancelled) {
  1026. return BAKE_ERROR_USER_ABORTED;
  1027. }
  1028. }
  1029. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1030. raycaster->add_mesh(mesh_instances[i].data.points, mesh_instances[i].data.normal, mesh_instances[i].data.uv2, i);
  1031. }
  1032. raycaster->commit();
  1033. scene_lightmaps.resize(mesh_instances.size());
  1034. scene_lightmap_indices.resize(mesh_instances.size());
  1035. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1036. if (!mesh_instances[i].cast_shadows) {
  1037. no_shadow_meshes.insert(i);
  1038. }
  1039. }
  1040. raycaster->set_mesh_filter(no_shadow_meshes);
  1041. Vector2i atlas_size = Vector2i(-1, -1);
  1042. int atlas_slices = -1;
  1043. if (p_generate_atlas) {
  1044. Error err = _layout_atlas(p_max_texture_size, &atlas_size, &atlas_slices);
  1045. if (err != OK) {
  1046. return BAKE_ERROR_LIGHTMAP_TOO_SMALL;
  1047. }
  1048. }
  1049. if (p_step_function) {
  1050. bool cancelled = p_step_function(0.2, TTR("Generate buffers"), p_bake_userdata, true);
  1051. if (cancelled) {
  1052. return BAKE_ERROR_USER_ABORTED;
  1053. }
  1054. }
  1055. if (_parallel_run(mesh_instances.size(), "Rasterizing meshes", &LightmapperCPU::_generate_buffer, nullptr, p_substep_function)) {
  1056. return BAKE_ERROR_USER_ABORTED;
  1057. }
  1058. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1059. const Size2i &size = mesh_instances[i].size;
  1060. bool has_alpha = false;
  1061. PoolVector<uint8_t> alpha_data;
  1062. alpha_data.resize(size.x * size.y);
  1063. {
  1064. PoolVector<uint8_t>::Write w = alpha_data.write();
  1065. for (unsigned int j = 0; j < scene_lightmap_indices[i].size(); ++j) {
  1066. int idx = scene_lightmap_indices[i][j];
  1067. uint8_t alpha = 0;
  1068. if (idx >= 0) {
  1069. alpha = CLAMP(scene_lightmaps[i][idx].alpha * 255, 0, 255);
  1070. if (alpha < 255) {
  1071. has_alpha = true;
  1072. }
  1073. }
  1074. w[j] = alpha;
  1075. }
  1076. }
  1077. if (has_alpha) {
  1078. Ref<Image> alpha_texture;
  1079. alpha_texture.instance();
  1080. alpha_texture->create(size.x, size.y, false, Image::FORMAT_L8, alpha_data);
  1081. raycaster->set_mesh_alpha_texture(alpha_texture, i);
  1082. }
  1083. }
  1084. albedo_textures.clear();
  1085. emission_textures.clear();
  1086. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1087. if (p_step_function) {
  1088. float p = float(i) / mesh_instances.size();
  1089. 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);
  1090. if (cancelled) {
  1091. return BAKE_ERROR_USER_ABORTED;
  1092. }
  1093. }
  1094. if (_parallel_run(scene_lightmaps[i].size(), "Computing direct light", &LightmapperCPU::_compute_direct_light, scene_lightmaps[i].ptr(), p_substep_function)) {
  1095. return BAKE_ERROR_USER_ABORTED;
  1096. }
  1097. }
  1098. raycaster->clear_mesh_filter();
  1099. int n_lit_meshes = 0;
  1100. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1101. if (mesh_instances[i].generate_lightmap) {
  1102. n_lit_meshes++;
  1103. }
  1104. }
  1105. if (parameters.environment_panorama.is_valid()) {
  1106. parameters.environment_panorama->lock();
  1107. }
  1108. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1109. if (!mesh_instances[i].generate_lightmap) {
  1110. continue;
  1111. }
  1112. if (p_step_function) {
  1113. float p = float(i) / n_lit_meshes;
  1114. 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);
  1115. if (cancelled) {
  1116. return BAKE_ERROR_USER_ABORTED;
  1117. }
  1118. }
  1119. if (!scene_lightmaps[i].empty()) {
  1120. if (_parallel_run(scene_lightmaps[i].size(), "Computing indirect light", &LightmapperCPU::_compute_indirect_light, scene_lightmaps[i].ptr(), p_substep_function)) {
  1121. return BAKE_ERROR_USER_ABORTED;
  1122. }
  1123. }
  1124. }
  1125. if (parameters.environment_panorama.is_valid()) {
  1126. parameters.environment_panorama->unlock();
  1127. }
  1128. raycaster.unref(); // Not needed anymore, free some memory.
  1129. LocalVector<LocalVector<Vector3> > lightmaps_data;
  1130. lightmaps_data.resize(mesh_instances.size());
  1131. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1132. if (mesh_instances[i].generate_lightmap) {
  1133. const Vector2i size = mesh_instances[i].size;
  1134. lightmaps_data[i].resize(size.x * size.y);
  1135. }
  1136. }
  1137. if (p_step_function) {
  1138. bool cancelled = p_step_function(0.8, TTR("Post processing"), p_bake_userdata, true);
  1139. if (cancelled) {
  1140. return BAKE_ERROR_USER_ABORTED;
  1141. }
  1142. }
  1143. if (_parallel_run(mesh_instances.size(), "Denoise & fix seams", &LightmapperCPU::_post_process, lightmaps_data.ptr(), p_substep_function)) {
  1144. return BAKE_ERROR_USER_ABORTED;
  1145. }
  1146. if (p_generate_atlas) {
  1147. bake_textures.resize(atlas_slices);
  1148. for (int i = 0; i < atlas_slices; i++) {
  1149. Ref<Image> image;
  1150. image.instance();
  1151. image->create(atlas_size.x, atlas_size.y, false, Image::FORMAT_RGBH);
  1152. bake_textures[i] = image;
  1153. }
  1154. } else {
  1155. bake_textures.resize(mesh_instances.size());
  1156. Set<String> used_mesh_names;
  1157. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1158. if (!mesh_instances[i].generate_lightmap) {
  1159. continue;
  1160. }
  1161. String mesh_name = mesh_instances[i].node_name;
  1162. if (mesh_name == "" || mesh_name.find(":") != -1 || mesh_name.find("/") != -1) {
  1163. mesh_name = "LightMap";
  1164. }
  1165. if (used_mesh_names.has(mesh_name)) {
  1166. int idx = 2;
  1167. String base = mesh_name;
  1168. while (true) {
  1169. mesh_name = base + itos(idx);
  1170. if (!used_mesh_names.has(mesh_name))
  1171. break;
  1172. idx++;
  1173. }
  1174. }
  1175. used_mesh_names.insert(mesh_name);
  1176. Ref<Image> image;
  1177. image.instance();
  1178. image->create(mesh_instances[i].size.x, mesh_instances[i].size.y, false, Image::FORMAT_RGBH);
  1179. image->set_name(mesh_name);
  1180. bake_textures[i] = image;
  1181. }
  1182. }
  1183. if (p_step_function) {
  1184. bool cancelled = p_step_function(0.9, TTR("Plotting lightmaps"), p_bake_userdata, true);
  1185. if (cancelled) {
  1186. return BAKE_ERROR_USER_ABORTED;
  1187. }
  1188. }
  1189. {
  1190. int j = 0;
  1191. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1192. if (!mesh_instances[i].generate_lightmap) {
  1193. continue;
  1194. }
  1195. if (p_generate_atlas) {
  1196. _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);
  1197. } else {
  1198. _blit_lightmap(lightmaps_data[i], mesh_instances[i].size, bake_textures[j], 0, 0, false);
  1199. }
  1200. j++;
  1201. }
  1202. }
  1203. return BAKE_OK;
  1204. }
  1205. int LightmapperCPU::get_bake_texture_count() const {
  1206. return bake_textures.size();
  1207. }
  1208. Ref<Image> LightmapperCPU::get_bake_texture(int p_index) const {
  1209. ERR_FAIL_INDEX_V(p_index, (int)bake_textures.size(), Ref<Image>());
  1210. return bake_textures[p_index];
  1211. }
  1212. int LightmapperCPU::get_bake_mesh_count() const {
  1213. return mesh_instances.size();
  1214. }
  1215. Variant LightmapperCPU::get_bake_mesh_userdata(int p_index) const {
  1216. ERR_FAIL_INDEX_V(p_index, (int)mesh_instances.size(), Variant());
  1217. return mesh_instances[p_index].data.userdata;
  1218. }
  1219. Rect2 LightmapperCPU::get_bake_mesh_uv_scale(int p_index) const {
  1220. ERR_FAIL_COND_V(bake_textures.size() == 0, Rect2());
  1221. Rect2 uv_ofs;
  1222. Vector2 atlas_size = Vector2(bake_textures[0]->get_width(), bake_textures[0]->get_height());
  1223. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  1224. uv_ofs.size = Vector2(mesh_instances[p_index].size) / atlas_size;
  1225. return uv_ofs;
  1226. }
  1227. int LightmapperCPU::get_bake_mesh_texture_slice(int p_index) const {
  1228. ERR_FAIL_INDEX_V(p_index, (int)mesh_instances.size(), Variant());
  1229. return mesh_instances[p_index].slice;
  1230. }
  1231. void LightmapperCPU::add_albedo_texture(Ref<Texture> p_texture) {
  1232. if (p_texture.is_null()) {
  1233. return;
  1234. }
  1235. RID texture_rid = p_texture->get_rid();
  1236. if (!texture_rid.is_valid() || albedo_textures.has(texture_rid)) {
  1237. return;
  1238. }
  1239. Ref<Image> texture_data = p_texture->get_data();
  1240. if (texture_data.is_null()) {
  1241. return;
  1242. }
  1243. if (texture_data->is_compressed()) {
  1244. texture_data->decompress();
  1245. }
  1246. texture_data->convert(Image::FORMAT_RGBA8);
  1247. albedo_textures.insert(texture_rid, texture_data);
  1248. }
  1249. void LightmapperCPU::add_emission_texture(Ref<Texture> p_texture) {
  1250. if (p_texture.is_null()) {
  1251. return;
  1252. }
  1253. RID texture_rid = p_texture->get_rid();
  1254. if (!texture_rid.is_valid() || emission_textures.has(texture_rid)) {
  1255. return;
  1256. }
  1257. Ref<Image> texture_data = p_texture->get_data();
  1258. if (texture_data.is_null()) {
  1259. return;
  1260. }
  1261. if (texture_data->is_compressed()) {
  1262. texture_data->decompress();
  1263. }
  1264. texture_data->convert(Image::FORMAT_RGBH);
  1265. emission_textures.insert(texture_rid, texture_data);
  1266. }
  1267. void LightmapperCPU::add_mesh(const MeshData &p_mesh, Vector2i p_size) {
  1268. ERR_FAIL_COND(p_mesh.points.size() == 0);
  1269. ERR_FAIL_COND(p_mesh.points.size() != p_mesh.uv2.size());
  1270. ERR_FAIL_COND(p_mesh.points.size() != p_mesh.normal.size());
  1271. ERR_FAIL_COND(!p_mesh.uv.empty() && p_mesh.points.size() != p_mesh.uv.size());
  1272. ERR_FAIL_COND(p_mesh.surface_facecounts.size() != p_mesh.albedo.size());
  1273. ERR_FAIL_COND(p_mesh.surface_facecounts.size() != p_mesh.emission.size());
  1274. MeshInstance mi;
  1275. mi.data = p_mesh;
  1276. mi.size = p_size;
  1277. mi.generate_lightmap = true;
  1278. mi.cast_shadows = true;
  1279. mi.node_name = "";
  1280. Dictionary userdata = p_mesh.userdata;
  1281. if (userdata.has("cast_shadows")) {
  1282. mi.cast_shadows = userdata["cast_shadows"];
  1283. }
  1284. if (userdata.has("generate_lightmap")) {
  1285. mi.generate_lightmap = userdata["generate_lightmap"];
  1286. }
  1287. if (userdata.has("node_name")) {
  1288. mi.node_name = userdata["node_name"];
  1289. }
  1290. mesh_instances.push_back(mi);
  1291. }
  1292. void LightmapperCPU::add_directional_light(bool p_bake_direct, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_multiplier) {
  1293. Light l;
  1294. l.type = LIGHT_TYPE_DIRECTIONAL;
  1295. l.direction = p_direction;
  1296. l.color = p_color;
  1297. l.energy = p_energy;
  1298. l.indirect_multiplier = p_indirect_multiplier;
  1299. l.bake_direct = p_bake_direct;
  1300. lights.push_back(l);
  1301. }
  1302. 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) {
  1303. Light l;
  1304. l.type = LIGHT_TYPE_OMNI;
  1305. l.position = p_position;
  1306. l.range = p_range;
  1307. l.attenuation = p_attenuation;
  1308. l.color = p_color;
  1309. l.energy = p_energy;
  1310. l.indirect_multiplier = p_indirect_multiplier;
  1311. l.bake_direct = p_bake_direct;
  1312. lights.push_back(l);
  1313. }
  1314. 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) {
  1315. Light l;
  1316. l.type = LIGHT_TYPE_SPOT;
  1317. l.position = p_position;
  1318. l.direction = p_direction;
  1319. l.range = p_range;
  1320. l.attenuation = p_attenuation;
  1321. l.spot_angle = Math::deg2rad(p_spot_angle);
  1322. l.spot_attenuation = p_spot_attenuation;
  1323. l.color = p_color;
  1324. l.energy = p_energy;
  1325. l.indirect_multiplier = p_indirect_multiplier;
  1326. l.bake_direct = p_bake_direct;
  1327. lights.push_back(l);
  1328. }
  1329. LightmapperCPU::LightmapperCPU() {
  1330. thread_progress = 0;
  1331. thread_cancelled = false;
  1332. }