voxel_light_baker.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425
  1. /*************************************************************************/
  2. /* voxel_light_baker.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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 "voxel_light_baker.h"
  31. #include "core/os/os.h"
  32. #include "core/os/threaded_array_processor.h"
  33. #include <stdlib.h>
  34. #define FINDMINMAX(x0, x1, x2, min, max) \
  35. min = max = x0; \
  36. if (x1 < min) min = x1; \
  37. if (x1 > max) max = x1; \
  38. if (x2 < min) min = x2; \
  39. if (x2 > max) max = x2;
  40. static bool planeBoxOverlap(Vector3 normal, float d, Vector3 maxbox) {
  41. int q;
  42. Vector3 vmin, vmax;
  43. for (q = 0; q <= 2; q++) {
  44. if (normal[q] > 0.0f) {
  45. vmin[q] = -maxbox[q];
  46. vmax[q] = maxbox[q];
  47. } else {
  48. vmin[q] = maxbox[q];
  49. vmax[q] = -maxbox[q];
  50. }
  51. }
  52. if (normal.dot(vmin) + d > 0.0f) return false;
  53. if (normal.dot(vmax) + d >= 0.0f) return true;
  54. return false;
  55. }
  56. /*======================== X-tests ========================*/
  57. #define AXISTEST_X01(a, b, fa, fb) \
  58. p0 = a * v0.y - b * v0.z; \
  59. p2 = a * v2.y - b * v2.z; \
  60. if (p0 < p2) { \
  61. min = p0; \
  62. max = p2; \
  63. } else { \
  64. min = p2; \
  65. max = p0; \
  66. } \
  67. rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
  68. if (min > rad || max < -rad) return false;
  69. #define AXISTEST_X2(a, b, fa, fb) \
  70. p0 = a * v0.y - b * v0.z; \
  71. p1 = a * v1.y - b * v1.z; \
  72. if (p0 < p1) { \
  73. min = p0; \
  74. max = p1; \
  75. } else { \
  76. min = p1; \
  77. max = p0; \
  78. } \
  79. rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
  80. if (min > rad || max < -rad) return false;
  81. /*======================== Y-tests ========================*/
  82. #define AXISTEST_Y02(a, b, fa, fb) \
  83. p0 = -a * v0.x + b * v0.z; \
  84. p2 = -a * v2.x + b * v2.z; \
  85. if (p0 < p2) { \
  86. min = p0; \
  87. max = p2; \
  88. } else { \
  89. min = p2; \
  90. max = p0; \
  91. } \
  92. rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
  93. if (min > rad || max < -rad) return false;
  94. #define AXISTEST_Y1(a, b, fa, fb) \
  95. p0 = -a * v0.x + b * v0.z; \
  96. p1 = -a * v1.x + b * v1.z; \
  97. if (p0 < p1) { \
  98. min = p0; \
  99. max = p1; \
  100. } else { \
  101. min = p1; \
  102. max = p0; \
  103. } \
  104. rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
  105. if (min > rad || max < -rad) return false;
  106. /*======================== Z-tests ========================*/
  107. #define AXISTEST_Z12(a, b, fa, fb) \
  108. p1 = a * v1.x - b * v1.y; \
  109. p2 = a * v2.x - b * v2.y; \
  110. if (p2 < p1) { \
  111. min = p2; \
  112. max = p1; \
  113. } else { \
  114. min = p1; \
  115. max = p2; \
  116. } \
  117. rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
  118. if (min > rad || max < -rad) return false;
  119. #define AXISTEST_Z0(a, b, fa, fb) \
  120. p0 = a * v0.x - b * v0.y; \
  121. p1 = a * v1.x - b * v1.y; \
  122. if (p0 < p1) { \
  123. min = p0; \
  124. max = p1; \
  125. } else { \
  126. min = p1; \
  127. max = p0; \
  128. } \
  129. rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
  130. if (min > rad || max < -rad) return false;
  131. static bool fast_tri_box_overlap(const Vector3 &boxcenter, const Vector3 boxhalfsize, const Vector3 *triverts) {
  132. /* use separating axis theorem to test overlap between triangle and box */
  133. /* need to test for overlap in these directions: */
  134. /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
  135. /* we do not even need to test these) */
  136. /* 2) normal of the triangle */
  137. /* 3) crossproduct(edge from tri, {x,y,z}-directin) */
  138. /* this gives 3x3=9 more tests */
  139. Vector3 v0, v1, v2;
  140. float min, max, d, p0, p1, p2, rad, fex, fey, fez;
  141. Vector3 normal, e0, e1, e2;
  142. /* This is the fastest branch on Sun */
  143. /* move everything so that the boxcenter is in (0,0,0) */
  144. v0 = triverts[0] - boxcenter;
  145. v1 = triverts[1] - boxcenter;
  146. v2 = triverts[2] - boxcenter;
  147. /* compute triangle edges */
  148. e0 = v1 - v0; /* tri edge 0 */
  149. e1 = v2 - v1; /* tri edge 1 */
  150. e2 = v0 - v2; /* tri edge 2 */
  151. /* Bullet 3: */
  152. /* test the 9 tests first (this was faster) */
  153. fex = Math::abs(e0.x);
  154. fey = Math::abs(e0.y);
  155. fez = Math::abs(e0.z);
  156. AXISTEST_X01(e0.z, e0.y, fez, fey);
  157. AXISTEST_Y02(e0.z, e0.x, fez, fex);
  158. AXISTEST_Z12(e0.y, e0.x, fey, fex);
  159. fex = Math::abs(e1.x);
  160. fey = Math::abs(e1.y);
  161. fez = Math::abs(e1.z);
  162. AXISTEST_X01(e1.z, e1.y, fez, fey);
  163. AXISTEST_Y02(e1.z, e1.x, fez, fex);
  164. AXISTEST_Z0(e1.y, e1.x, fey, fex);
  165. fex = Math::abs(e2.x);
  166. fey = Math::abs(e2.y);
  167. fez = Math::abs(e2.z);
  168. AXISTEST_X2(e2.z, e2.y, fez, fey);
  169. AXISTEST_Y1(e2.z, e2.x, fez, fex);
  170. AXISTEST_Z12(e2.y, e2.x, fey, fex);
  171. /* Bullet 1: */
  172. /* first test overlap in the {x,y,z}-directions */
  173. /* find min, max of the triangle each direction, and test for overlap in */
  174. /* that direction -- this is equivalent to testing a minimal AABB around */
  175. /* the triangle against the AABB */
  176. /* test in X-direction */
  177. FINDMINMAX(v0.x, v1.x, v2.x, min, max);
  178. if (min > boxhalfsize.x || max < -boxhalfsize.x) return false;
  179. /* test in Y-direction */
  180. FINDMINMAX(v0.y, v1.y, v2.y, min, max);
  181. if (min > boxhalfsize.y || max < -boxhalfsize.y) return false;
  182. /* test in Z-direction */
  183. FINDMINMAX(v0.z, v1.z, v2.z, min, max);
  184. if (min > boxhalfsize.z || max < -boxhalfsize.z) return false;
  185. /* Bullet 2: */
  186. /* test if the box intersects the plane of the triangle */
  187. /* compute plane equation of triangle: normal*x+d=0 */
  188. normal = e0.cross(e1);
  189. d = -normal.dot(v0); /* plane eq: normal.x+d=0 */
  190. if (!planeBoxOverlap(normal, d, boxhalfsize)) return false;
  191. return true; /* box and triangle overlaps */
  192. }
  193. static _FORCE_INLINE_ void get_uv_and_normal(const Vector3 &p_pos, const Vector3 *p_vtx, const Vector2 *p_uv, const Vector3 *p_normal, Vector2 &r_uv, Vector3 &r_normal) {
  194. if (p_pos.distance_squared_to(p_vtx[0]) < CMP_EPSILON2) {
  195. r_uv = p_uv[0];
  196. r_normal = p_normal[0];
  197. return;
  198. }
  199. if (p_pos.distance_squared_to(p_vtx[1]) < CMP_EPSILON2) {
  200. r_uv = p_uv[1];
  201. r_normal = p_normal[1];
  202. return;
  203. }
  204. if (p_pos.distance_squared_to(p_vtx[2]) < CMP_EPSILON2) {
  205. r_uv = p_uv[2];
  206. r_normal = p_normal[2];
  207. return;
  208. }
  209. Vector3 v0 = p_vtx[1] - p_vtx[0];
  210. Vector3 v1 = p_vtx[2] - p_vtx[0];
  211. Vector3 v2 = p_pos - p_vtx[0];
  212. float d00 = v0.dot(v0);
  213. float d01 = v0.dot(v1);
  214. float d11 = v1.dot(v1);
  215. float d20 = v2.dot(v0);
  216. float d21 = v2.dot(v1);
  217. float denom = (d00 * d11 - d01 * d01);
  218. if (denom == 0) {
  219. r_uv = p_uv[0];
  220. r_normal = p_normal[0];
  221. return;
  222. }
  223. float v = (d11 * d20 - d01 * d21) / denom;
  224. float w = (d00 * d21 - d01 * d20) / denom;
  225. float u = 1.0f - v - w;
  226. r_uv = p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
  227. r_normal = (p_normal[0] * u + p_normal[1] * v + p_normal[2] * w).normalized();
  228. }
  229. void VoxelLightBaker::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, const Vector3 *p_vtx, const Vector3 *p_normal, const Vector2 *p_uv, const MaterialCache &p_material, const AABB &p_aabb) {
  230. if (p_level == cell_subdiv - 1) {
  231. //plot the face by guessing its albedo and emission value
  232. //find best axis to map to, for scanning values
  233. int closest_axis = 0;
  234. float closest_dot = 0;
  235. Plane plane = Plane(p_vtx[0], p_vtx[1], p_vtx[2]);
  236. Vector3 normal = plane.normal;
  237. for (int i = 0; i < 3; i++) {
  238. Vector3 axis;
  239. axis[i] = 1.0;
  240. float dot = ABS(normal.dot(axis));
  241. if (i == 0 || dot > closest_dot) {
  242. closest_axis = i;
  243. closest_dot = dot;
  244. }
  245. }
  246. Vector3 axis;
  247. axis[closest_axis] = 1.0;
  248. Vector3 t1;
  249. t1[(closest_axis + 1) % 3] = 1.0;
  250. Vector3 t2;
  251. t2[(closest_axis + 2) % 3] = 1.0;
  252. t1 *= p_aabb.size[(closest_axis + 1) % 3] / float(color_scan_cell_width);
  253. t2 *= p_aabb.size[(closest_axis + 2) % 3] / float(color_scan_cell_width);
  254. Color albedo_accum;
  255. Color emission_accum;
  256. Vector3 normal_accum;
  257. float alpha = 0.0;
  258. //map to a grid average in the best axis for this face
  259. for (int i = 0; i < color_scan_cell_width; i++) {
  260. Vector3 ofs_i = float(i) * t1;
  261. for (int j = 0; j < color_scan_cell_width; j++) {
  262. Vector3 ofs_j = float(j) * t2;
  263. Vector3 from = p_aabb.position + ofs_i + ofs_j;
  264. Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis];
  265. Vector3 half = (to - from) * 0.5;
  266. //is in this cell?
  267. if (!fast_tri_box_overlap(from + half, half, p_vtx)) {
  268. continue; //face does not span this cell
  269. }
  270. //go from -size to +size*2 to avoid skipping collisions
  271. Vector3 ray_from = from + (t1 + t2) * 0.5 - axis * p_aabb.size[closest_axis];
  272. Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis] * 2;
  273. if (normal.dot(ray_from - ray_to) < 0) {
  274. SWAP(ray_from, ray_to);
  275. }
  276. Vector3 intersection;
  277. if (!plane.intersects_segment(ray_from, ray_to, &intersection)) {
  278. if (ABS(plane.distance_to(ray_from)) < ABS(plane.distance_to(ray_to))) {
  279. intersection = plane.project(ray_from);
  280. } else {
  281. intersection = plane.project(ray_to);
  282. }
  283. }
  284. intersection = Face3(p_vtx[0], p_vtx[1], p_vtx[2]).get_closest_point_to(intersection);
  285. Vector2 uv;
  286. Vector3 lnormal;
  287. get_uv_and_normal(intersection, p_vtx, p_uv, p_normal, uv, lnormal);
  288. if (lnormal == Vector3()) //just in case normal as nor provided
  289. lnormal = normal;
  290. int uv_x = CLAMP(int(Math::fposmod(uv.x, 1.0f) * bake_texture_size), 0, bake_texture_size - 1);
  291. int uv_y = CLAMP(int(Math::fposmod(uv.y, 1.0f) * bake_texture_size), 0, bake_texture_size - 1);
  292. int ofs = uv_y * bake_texture_size + uv_x;
  293. albedo_accum.r += p_material.albedo[ofs].r;
  294. albedo_accum.g += p_material.albedo[ofs].g;
  295. albedo_accum.b += p_material.albedo[ofs].b;
  296. albedo_accum.a += p_material.albedo[ofs].a;
  297. emission_accum.r += p_material.emission[ofs].r;
  298. emission_accum.g += p_material.emission[ofs].g;
  299. emission_accum.b += p_material.emission[ofs].b;
  300. normal_accum += lnormal;
  301. alpha += 1.0;
  302. }
  303. }
  304. if (alpha == 0) {
  305. //could not in any way get texture information.. so use closest point to center
  306. Face3 f(p_vtx[0], p_vtx[1], p_vtx[2]);
  307. Vector3 inters = f.get_closest_point_to(p_aabb.position + p_aabb.size * 0.5);
  308. Vector3 lnormal;
  309. Vector2 uv;
  310. get_uv_and_normal(inters, p_vtx, p_uv, p_normal, uv, normal);
  311. if (lnormal == Vector3()) //just in case normal as nor provided
  312. lnormal = normal;
  313. int uv_x = CLAMP(Math::fposmod(uv.x, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
  314. int uv_y = CLAMP(Math::fposmod(uv.y, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
  315. int ofs = uv_y * bake_texture_size + uv_x;
  316. alpha = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  317. albedo_accum.r = p_material.albedo[ofs].r * alpha;
  318. albedo_accum.g = p_material.albedo[ofs].g * alpha;
  319. albedo_accum.b = p_material.albedo[ofs].b * alpha;
  320. albedo_accum.a = p_material.albedo[ofs].a * alpha;
  321. emission_accum.r = p_material.emission[ofs].r * alpha;
  322. emission_accum.g = p_material.emission[ofs].g * alpha;
  323. emission_accum.b = p_material.emission[ofs].b * alpha;
  324. normal_accum = lnormal * alpha;
  325. } else {
  326. float accdiv = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  327. alpha *= accdiv;
  328. albedo_accum.r *= accdiv;
  329. albedo_accum.g *= accdiv;
  330. albedo_accum.b *= accdiv;
  331. albedo_accum.a *= accdiv;
  332. emission_accum.r *= accdiv;
  333. emission_accum.g *= accdiv;
  334. emission_accum.b *= accdiv;
  335. normal_accum *= accdiv;
  336. }
  337. //put this temporarily here, corrected in a later step
  338. bake_cells.write[p_idx].albedo[0] += albedo_accum.r;
  339. bake_cells.write[p_idx].albedo[1] += albedo_accum.g;
  340. bake_cells.write[p_idx].albedo[2] += albedo_accum.b;
  341. bake_cells.write[p_idx].emission[0] += emission_accum.r;
  342. bake_cells.write[p_idx].emission[1] += emission_accum.g;
  343. bake_cells.write[p_idx].emission[2] += emission_accum.b;
  344. bake_cells.write[p_idx].normal[0] += normal_accum.x;
  345. bake_cells.write[p_idx].normal[1] += normal_accum.y;
  346. bake_cells.write[p_idx].normal[2] += normal_accum.z;
  347. bake_cells.write[p_idx].alpha += alpha;
  348. } else {
  349. //go down
  350. int half = (1 << (cell_subdiv - 1)) >> (p_level + 1);
  351. for (int i = 0; i < 8; i++) {
  352. AABB aabb = p_aabb;
  353. aabb.size *= 0.5;
  354. int nx = p_x;
  355. int ny = p_y;
  356. int nz = p_z;
  357. if (i & 1) {
  358. aabb.position.x += aabb.size.x;
  359. nx += half;
  360. }
  361. if (i & 2) {
  362. aabb.position.y += aabb.size.y;
  363. ny += half;
  364. }
  365. if (i & 4) {
  366. aabb.position.z += aabb.size.z;
  367. nz += half;
  368. }
  369. //make sure to not plot beyond limits
  370. if (nx < 0 || nx >= axis_cell_size[0] || ny < 0 || ny >= axis_cell_size[1] || nz < 0 || nz >= axis_cell_size[2])
  371. continue;
  372. {
  373. AABB test_aabb = aabb;
  374. //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time
  375. Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test
  376. if (!fast_tri_box_overlap(test_aabb.position + qsize, qsize, p_vtx)) {
  377. //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
  378. //does not fit in child, go on
  379. continue;
  380. }
  381. }
  382. if (bake_cells[p_idx].children[i] == CHILD_EMPTY) {
  383. //sub cell must be created
  384. uint32_t child_idx = bake_cells.size();
  385. bake_cells.write[p_idx].children[i] = child_idx;
  386. bake_cells.resize(bake_cells.size() + 1);
  387. bake_cells.write[child_idx].level = p_level + 1;
  388. }
  389. _plot_face(bake_cells[p_idx].children[i], p_level + 1, nx, ny, nz, p_vtx, p_normal, p_uv, p_material, aabb);
  390. }
  391. }
  392. }
  393. Vector<Color> VoxelLightBaker::_get_bake_texture(Ref<Image> p_image, const Color &p_color_mul, const Color &p_color_add) {
  394. Vector<Color> ret;
  395. if (p_image.is_null() || p_image->empty()) {
  396. ret.resize(bake_texture_size * bake_texture_size);
  397. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  398. ret.write[i] = p_color_add;
  399. }
  400. return ret;
  401. }
  402. p_image = p_image->duplicate();
  403. if (p_image->is_compressed()) {
  404. p_image->decompress();
  405. }
  406. p_image->convert(Image::FORMAT_RGBA8);
  407. p_image->resize(bake_texture_size, bake_texture_size, Image::INTERPOLATE_CUBIC);
  408. PoolVector<uint8_t>::Read r = p_image->get_data().read();
  409. ret.resize(bake_texture_size * bake_texture_size);
  410. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  411. Color c;
  412. c.r = (r[i * 4 + 0] / 255.0) * p_color_mul.r + p_color_add.r;
  413. c.g = (r[i * 4 + 1] / 255.0) * p_color_mul.g + p_color_add.g;
  414. c.b = (r[i * 4 + 2] / 255.0) * p_color_mul.b + p_color_add.b;
  415. c.a = r[i * 4 + 3] / 255.0;
  416. ret.write[i] = c;
  417. }
  418. return ret;
  419. }
  420. VoxelLightBaker::MaterialCache VoxelLightBaker::_get_material_cache(Ref<Material> p_material) {
  421. //this way of obtaining materials is inaccurate and also does not support some compressed formats very well
  422. Ref<SpatialMaterial> mat = p_material;
  423. Ref<Material> material = mat; //hack for now
  424. if (material_cache.has(material)) {
  425. return material_cache[material];
  426. }
  427. MaterialCache mc;
  428. if (mat.is_valid()) {
  429. Ref<Texture> albedo_tex = mat->get_texture(SpatialMaterial::TEXTURE_ALBEDO);
  430. Ref<Image> img_albedo;
  431. if (albedo_tex.is_valid()) {
  432. img_albedo = albedo_tex->get_data();
  433. mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo(), Color(0, 0, 0)); // albedo texture, color is multiplicative
  434. } else {
  435. mc.albedo = _get_bake_texture(img_albedo, Color(1, 1, 1), mat->get_albedo()); // no albedo texture, color is additive
  436. }
  437. Ref<Texture> emission_tex = mat->get_texture(SpatialMaterial::TEXTURE_EMISSION);
  438. Color emission_col = mat->get_emission();
  439. float emission_energy = mat->get_emission_energy();
  440. Ref<Image> img_emission;
  441. if (emission_tex.is_valid()) {
  442. img_emission = emission_tex->get_data();
  443. }
  444. if (mat->get_emission_operator() == SpatialMaterial::EMISSION_OP_ADD) {
  445. mc.emission = _get_bake_texture(img_emission, Color(1, 1, 1) * emission_energy, emission_col * emission_energy);
  446. } else {
  447. mc.emission = _get_bake_texture(img_emission, emission_col * emission_energy, Color(0, 0, 0));
  448. }
  449. } else {
  450. Ref<Image> empty;
  451. mc.albedo = _get_bake_texture(empty, Color(0, 0, 0), Color(1, 1, 1));
  452. mc.emission = _get_bake_texture(empty, Color(0, 0, 0), Color(0, 0, 0));
  453. }
  454. material_cache[p_material] = mc;
  455. return mc;
  456. }
  457. void VoxelLightBaker::plot_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material> > &p_materials, const Ref<Material> &p_override_material) {
  458. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  459. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
  460. continue; //only triangles
  461. Ref<Material> src_material;
  462. if (p_override_material.is_valid()) {
  463. src_material = p_override_material;
  464. } else if (i < p_materials.size() && p_materials[i].is_valid()) {
  465. src_material = p_materials[i];
  466. } else {
  467. src_material = p_mesh->surface_get_material(i);
  468. }
  469. MaterialCache material = _get_material_cache(src_material);
  470. Array a = p_mesh->surface_get_arrays(i);
  471. PoolVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  472. PoolVector<Vector3>::Read vr = vertices.read();
  473. PoolVector<Vector2> uv = a[Mesh::ARRAY_TEX_UV];
  474. PoolVector<Vector2>::Read uvr;
  475. PoolVector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
  476. PoolVector<Vector3>::Read nr;
  477. PoolVector<int> index = a[Mesh::ARRAY_INDEX];
  478. bool read_uv = false;
  479. bool read_normals = false;
  480. if (uv.size()) {
  481. uvr = uv.read();
  482. read_uv = true;
  483. }
  484. if (normals.size()) {
  485. read_normals = true;
  486. nr = normals.read();
  487. }
  488. if (index.size()) {
  489. int facecount = index.size() / 3;
  490. PoolVector<int>::Read ir = index.read();
  491. for (int j = 0; j < facecount; j++) {
  492. Vector3 vtxs[3];
  493. Vector2 uvs[3];
  494. Vector3 normal[3];
  495. for (int k = 0; k < 3; k++) {
  496. vtxs[k] = p_xform.xform(vr[ir[j * 3 + k]]);
  497. }
  498. if (read_uv) {
  499. for (int k = 0; k < 3; k++) {
  500. uvs[k] = uvr[ir[j * 3 + k]];
  501. }
  502. }
  503. if (read_normals) {
  504. for (int k = 0; k < 3; k++) {
  505. normal[k] = nr[ir[j * 3 + k]];
  506. }
  507. }
  508. //test against original bounds
  509. if (!fast_tri_box_overlap(original_bounds.position + original_bounds.size * 0.5, original_bounds.size * 0.5, vtxs))
  510. continue;
  511. //plot
  512. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  513. }
  514. } else {
  515. int facecount = vertices.size() / 3;
  516. for (int j = 0; j < facecount; j++) {
  517. Vector3 vtxs[3];
  518. Vector2 uvs[3];
  519. Vector3 normal[3];
  520. for (int k = 0; k < 3; k++) {
  521. vtxs[k] = p_xform.xform(vr[j * 3 + k]);
  522. }
  523. if (read_uv) {
  524. for (int k = 0; k < 3; k++) {
  525. uvs[k] = uvr[j * 3 + k];
  526. }
  527. }
  528. if (read_normals) {
  529. for (int k = 0; k < 3; k++) {
  530. normal[k] = nr[j * 3 + k];
  531. }
  532. }
  533. //test against original bounds
  534. if (!fast_tri_box_overlap(original_bounds.position + original_bounds.size * 0.5, original_bounds.size * 0.5, vtxs))
  535. continue;
  536. //plot face
  537. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  538. }
  539. }
  540. }
  541. max_original_cells = bake_cells.size();
  542. }
  543. void VoxelLightBaker::_init_light_plot(int p_idx, int p_level, int p_x, int p_y, int p_z, uint32_t p_parent) {
  544. bake_light.write[p_idx].x = p_x;
  545. bake_light.write[p_idx].y = p_y;
  546. bake_light.write[p_idx].z = p_z;
  547. if (p_level == cell_subdiv - 1) {
  548. bake_light.write[p_idx].next_leaf = first_leaf;
  549. first_leaf = p_idx;
  550. } else {
  551. //go down
  552. int half = (1 << (cell_subdiv - 1)) >> (p_level + 1);
  553. for (int i = 0; i < 8; i++) {
  554. uint32_t child = bake_cells[p_idx].children[i];
  555. if (child == CHILD_EMPTY)
  556. continue;
  557. int nx = p_x;
  558. int ny = p_y;
  559. int nz = p_z;
  560. if (i & 1)
  561. nx += half;
  562. if (i & 2)
  563. ny += half;
  564. if (i & 4)
  565. nz += half;
  566. _init_light_plot(child, p_level + 1, nx, ny, nz, p_idx);
  567. }
  568. }
  569. }
  570. void VoxelLightBaker::begin_bake_light(BakeQuality p_quality, BakeMode p_bake_mode, float p_propagation, float p_energy) {
  571. _check_init_light();
  572. propagation = p_propagation;
  573. bake_quality = p_quality;
  574. bake_mode = p_bake_mode;
  575. energy = p_energy;
  576. }
  577. void VoxelLightBaker::_check_init_light() {
  578. if (bake_light.size() == 0) {
  579. direct_lights_baked = false;
  580. leaf_voxel_count = 0;
  581. _fixup_plot(0, 0); //pre fixup, so normal, albedo, emission, etc. work for lighting.
  582. bake_light.resize(bake_cells.size());
  583. print_line("bake light size: " + itos(bake_light.size()));
  584. //zeromem(bake_light.ptrw(), bake_light.size() * sizeof(Light));
  585. first_leaf = -1;
  586. _init_light_plot(0, 0, 0, 0, 0, CHILD_EMPTY);
  587. }
  588. }
  589. static float _get_normal_advance(const Vector3 &p_normal) {
  590. Vector3 normal = p_normal;
  591. Vector3 unorm = normal.abs();
  592. if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) {
  593. // x code
  594. unorm = normal.x > 0.0 ? Vector3(1.0, 0.0, 0.0) : Vector3(-1.0, 0.0, 0.0);
  595. } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) {
  596. // y code
  597. unorm = normal.y > 0.0 ? Vector3(0.0, 1.0, 0.0) : Vector3(0.0, -1.0, 0.0);
  598. } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) {
  599. // z code
  600. unorm = normal.z > 0.0 ? Vector3(0.0, 0.0, 1.0) : Vector3(0.0, 0.0, -1.0);
  601. } else {
  602. // oh-no we messed up code
  603. // has to be
  604. unorm = Vector3(1.0, 0.0, 0.0);
  605. }
  606. return 1.0 / normal.dot(unorm);
  607. }
  608. static const Vector3 aniso_normal[6] = {
  609. Vector3(-1, 0, 0),
  610. Vector3(1, 0, 0),
  611. Vector3(0, -1, 0),
  612. Vector3(0, 1, 0),
  613. Vector3(0, 0, -1),
  614. Vector3(0, 0, 1)
  615. };
  616. uint32_t VoxelLightBaker::_find_cell_at_pos(const Cell *cells, int x, int y, int z) {
  617. uint32_t cell = 0;
  618. int ofs_x = 0;
  619. int ofs_y = 0;
  620. int ofs_z = 0;
  621. int size = 1 << (cell_subdiv - 1);
  622. int half = size / 2;
  623. if (x < 0 || x >= size)
  624. return -1;
  625. if (y < 0 || y >= size)
  626. return -1;
  627. if (z < 0 || z >= size)
  628. return -1;
  629. for (int i = 0; i < cell_subdiv - 1; i++) {
  630. const Cell *bc = &cells[cell];
  631. int child = 0;
  632. if (x >= ofs_x + half) {
  633. child |= 1;
  634. ofs_x += half;
  635. }
  636. if (y >= ofs_y + half) {
  637. child |= 2;
  638. ofs_y += half;
  639. }
  640. if (z >= ofs_z + half) {
  641. child |= 4;
  642. ofs_z += half;
  643. }
  644. cell = bc->children[child];
  645. if (cell == CHILD_EMPTY)
  646. return CHILD_EMPTY;
  647. half >>= 1;
  648. }
  649. return cell;
  650. }
  651. void VoxelLightBaker::plot_light_directional(const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_energy, bool p_direct) {
  652. _check_init_light();
  653. float max_len = Vector3(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]).length() * 1.1;
  654. if (p_direct)
  655. direct_lights_baked = true;
  656. Vector3 light_axis = p_direction;
  657. Plane clip[3];
  658. int clip_planes = 0;
  659. Light *light_data = bake_light.ptrw();
  660. const Cell *cells = bake_cells.ptr();
  661. for (int i = 0; i < 3; i++) {
  662. if (ABS(light_axis[i]) < CMP_EPSILON)
  663. continue;
  664. clip[clip_planes].normal[i] = 1.0;
  665. if (light_axis[i] < 0) {
  666. clip[clip_planes].d = axis_cell_size[i] + 1;
  667. } else {
  668. clip[clip_planes].d -= 1.0;
  669. }
  670. clip_planes++;
  671. }
  672. float distance_adv = _get_normal_advance(light_axis);
  673. int success_count = 0;
  674. Vector3 light_energy = Vector3(p_color.r, p_color.g, p_color.b) * p_energy * p_indirect_energy;
  675. int idx = first_leaf;
  676. while (idx >= 0) {
  677. Light *light = &light_data[idx];
  678. Vector3 to(light->x + 0.5, light->y + 0.5, light->z + 0.5);
  679. to += -light_axis.sign() * 0.47; //make it more likely to receive a ray
  680. Vector3 from = to - max_len * light_axis;
  681. for (int j = 0; j < clip_planes; j++) {
  682. clip[j].intersects_segment(from, to, &from);
  683. }
  684. float distance = (to - from).length();
  685. distance += distance_adv - Math::fmod(distance, distance_adv); //make it reach the center of the box always
  686. from = to - light_axis * distance;
  687. uint32_t result = 0xFFFFFFFF;
  688. while (distance > -distance_adv) { //use this to avoid precision errors
  689. result = _find_cell_at_pos(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)));
  690. if (result != 0xFFFFFFFF) {
  691. break;
  692. }
  693. from += light_axis * distance_adv;
  694. distance -= distance_adv;
  695. }
  696. if (result == (uint32_t)idx) {
  697. //cell hit itself! hooray!
  698. Vector3 normal(cells[idx].normal[0], cells[idx].normal[1], cells[idx].normal[2]);
  699. if (normal == Vector3()) {
  700. for (int i = 0; i < 6; i++) {
  701. light->accum[i][0] += light_energy.x * cells[idx].albedo[0];
  702. light->accum[i][1] += light_energy.y * cells[idx].albedo[1];
  703. light->accum[i][2] += light_energy.z * cells[idx].albedo[2];
  704. }
  705. } else {
  706. for (int i = 0; i < 6; i++) {
  707. float s = MAX(0.0, aniso_normal[i].dot(-normal));
  708. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * s;
  709. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * s;
  710. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * s;
  711. }
  712. }
  713. if (p_direct) {
  714. for (int i = 0; i < 6; i++) {
  715. float s = MAX(0.0, aniso_normal[i].dot(-light_axis)); //light depending on normal for direct
  716. light->direct_accum[i][0] += light_energy.x * s;
  717. light->direct_accum[i][1] += light_energy.y * s;
  718. light->direct_accum[i][2] += light_energy.z * s;
  719. }
  720. }
  721. success_count++;
  722. }
  723. idx = light_data[idx].next_leaf;
  724. }
  725. }
  726. void VoxelLightBaker::plot_light_omni(const Vector3 &p_pos, const Color &p_color, float p_energy, float p_indirect_energy, float p_radius, float p_attenutation, bool p_direct) {
  727. _check_init_light();
  728. if (p_direct)
  729. direct_lights_baked = true;
  730. Plane clip[3];
  731. int clip_planes = 0;
  732. // uint64_t us = OS::get_singleton()->get_ticks_usec();
  733. Vector3 light_pos = to_cell_space.xform(p_pos) + Vector3(0.5, 0.5, 0.5);
  734. //Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized();
  735. float local_radius = to_cell_space.basis.xform(Vector3(0, 0, 1)).length() * p_radius;
  736. Light *light_data = bake_light.ptrw();
  737. const Cell *cells = bake_cells.ptr();
  738. Vector3 light_energy = Vector3(p_color.r, p_color.g, p_color.b) * p_energy * p_indirect_energy;
  739. int idx = first_leaf;
  740. while (idx >= 0) {
  741. Light *light = &light_data[idx];
  742. Vector3 to(light->x + 0.5, light->y + 0.5, light->z + 0.5);
  743. to += (light_pos - to).sign() * 0.47; //make it more likely to receive a ray
  744. Vector3 light_axis = (to - light_pos).normalized();
  745. float distance_adv = _get_normal_advance(light_axis);
  746. Vector3 normal(cells[idx].normal[0], cells[idx].normal[1], cells[idx].normal[2]);
  747. if (normal != Vector3() && normal.dot(-light_axis) < 0.001) {
  748. idx = light_data[idx].next_leaf;
  749. continue;
  750. }
  751. float att = 1.0;
  752. {
  753. float d = light_pos.distance_to(to);
  754. if (d + distance_adv > local_radius) {
  755. idx = light_data[idx].next_leaf;
  756. continue; // too far away
  757. }
  758. float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
  759. att *= powf(1.0 - dt, p_attenutation);
  760. }
  761. clip_planes = 0;
  762. for (int c = 0; c < 3; c++) {
  763. if (ABS(light_axis[c]) < CMP_EPSILON)
  764. continue;
  765. clip[clip_planes].normal[c] = 1.0;
  766. if (light_axis[c] < 0) {
  767. clip[clip_planes].d = (1 << (cell_subdiv - 1)) + 1;
  768. } else {
  769. clip[clip_planes].d -= 1.0;
  770. }
  771. clip_planes++;
  772. }
  773. Vector3 from = light_pos;
  774. for (int j = 0; j < clip_planes; j++) {
  775. clip[j].intersects_segment(from, to, &from);
  776. }
  777. float distance = (to - from).length();
  778. distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
  779. from = to - light_axis * distance;
  780. to += (light_pos - to).sign() * 0.47; //make it more likely to receive a ray
  781. uint32_t result = 0xFFFFFFFF;
  782. while (distance > -distance_adv) { //use this to avoid precision errors
  783. result = _find_cell_at_pos(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)));
  784. if (result != 0xFFFFFFFF) {
  785. break;
  786. }
  787. from += light_axis * distance_adv;
  788. distance -= distance_adv;
  789. }
  790. if (result == (uint32_t)idx) {
  791. //cell hit itself! hooray!
  792. if (normal == Vector3()) {
  793. for (int i = 0; i < 6; i++) {
  794. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * att;
  795. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * att;
  796. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * att;
  797. }
  798. } else {
  799. for (int i = 0; i < 6; i++) {
  800. float s = MAX(0.0, aniso_normal[i].dot(-normal));
  801. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * s * att;
  802. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * s * att;
  803. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * s * att;
  804. }
  805. }
  806. if (p_direct) {
  807. for (int i = 0; i < 6; i++) {
  808. float s = MAX(0.0, aniso_normal[i].dot(-light_axis)); //light depending on normal for direct
  809. light->direct_accum[i][0] += light_energy.x * s * att;
  810. light->direct_accum[i][1] += light_energy.y * s * att;
  811. light->direct_accum[i][2] += light_energy.z * s * att;
  812. }
  813. }
  814. }
  815. idx = light_data[idx].next_leaf;
  816. }
  817. }
  818. void VoxelLightBaker::plot_light_spot(const Vector3 &p_pos, const Vector3 &p_axis, const Color &p_color, float p_energy, float p_indirect_energy, float p_radius, float p_attenutation, float p_spot_angle, float p_spot_attenuation, bool p_direct) {
  819. _check_init_light();
  820. if (p_direct)
  821. direct_lights_baked = true;
  822. Plane clip[3];
  823. int clip_planes = 0;
  824. // uint64_t us = OS::get_singleton()->get_ticks_usec();
  825. Vector3 light_pos = to_cell_space.xform(p_pos) + Vector3(0.5, 0.5, 0.5);
  826. Vector3 spot_axis = to_cell_space.basis.xform(p_axis).normalized();
  827. float local_radius = to_cell_space.basis.xform(Vector3(0, 0, 1)).length() * p_radius;
  828. Light *light_data = bake_light.ptrw();
  829. const Cell *cells = bake_cells.ptr();
  830. Vector3 light_energy = Vector3(p_color.r, p_color.g, p_color.b) * p_energy * p_indirect_energy;
  831. int idx = first_leaf;
  832. while (idx >= 0) {
  833. Light *light = &light_data[idx];
  834. Vector3 to(light->x + 0.5, light->y + 0.5, light->z + 0.5);
  835. Vector3 light_axis = (to - light_pos).normalized();
  836. float distance_adv = _get_normal_advance(light_axis);
  837. Vector3 normal(cells[idx].normal[0], cells[idx].normal[1], cells[idx].normal[2]);
  838. if (normal != Vector3() && normal.dot(-light_axis) < 0.001) {
  839. idx = light_data[idx].next_leaf;
  840. continue;
  841. }
  842. float angle = Math::rad2deg(Math::acos(light_axis.dot(-spot_axis)));
  843. if (angle > p_spot_angle) {
  844. idx = light_data[idx].next_leaf;
  845. continue; // too far away
  846. }
  847. float att = Math::pow(1.0f - angle / p_spot_angle, p_spot_attenuation);
  848. {
  849. float d = light_pos.distance_to(to);
  850. if (d + distance_adv > local_radius) {
  851. idx = light_data[idx].next_leaf;
  852. continue; // too far away
  853. }
  854. float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
  855. att *= powf(1.0 - dt, p_attenutation);
  856. }
  857. clip_planes = 0;
  858. for (int c = 0; c < 3; c++) {
  859. if (ABS(light_axis[c]) < CMP_EPSILON)
  860. continue;
  861. clip[clip_planes].normal[c] = 1.0;
  862. if (light_axis[c] < 0) {
  863. clip[clip_planes].d = (1 << (cell_subdiv - 1)) + 1;
  864. } else {
  865. clip[clip_planes].d -= 1.0;
  866. }
  867. clip_planes++;
  868. }
  869. Vector3 from = light_pos;
  870. for (int j = 0; j < clip_planes; j++) {
  871. clip[j].intersects_segment(from, to, &from);
  872. }
  873. float distance = (to - from).length();
  874. distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
  875. from = to - light_axis * distance;
  876. uint32_t result = 0xFFFFFFFF;
  877. while (distance > -distance_adv) { //use this to avoid precision errors
  878. result = _find_cell_at_pos(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)));
  879. if (result != 0xFFFFFFFF) {
  880. break;
  881. }
  882. from += light_axis * distance_adv;
  883. distance -= distance_adv;
  884. }
  885. if (result == (uint32_t)idx) {
  886. //cell hit itself! hooray!
  887. if (normal == Vector3()) {
  888. for (int i = 0; i < 6; i++) {
  889. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * att;
  890. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * att;
  891. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * att;
  892. }
  893. } else {
  894. for (int i = 0; i < 6; i++) {
  895. float s = MAX(0.0, aniso_normal[i].dot(-normal));
  896. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * s * att;
  897. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * s * att;
  898. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * s * att;
  899. }
  900. }
  901. if (p_direct) {
  902. for (int i = 0; i < 6; i++) {
  903. float s = MAX(0.0, aniso_normal[i].dot(-light_axis)); //light depending on normal for direct
  904. light->direct_accum[i][0] += light_energy.x * s * att;
  905. light->direct_accum[i][1] += light_energy.y * s * att;
  906. light->direct_accum[i][2] += light_energy.z * s * att;
  907. }
  908. }
  909. }
  910. idx = light_data[idx].next_leaf;
  911. }
  912. }
  913. void VoxelLightBaker::_fixup_plot(int p_idx, int p_level) {
  914. if (p_level == cell_subdiv - 1) {
  915. leaf_voxel_count++;
  916. float alpha = bake_cells[p_idx].alpha;
  917. bake_cells.write[p_idx].albedo[0] /= alpha;
  918. bake_cells.write[p_idx].albedo[1] /= alpha;
  919. bake_cells.write[p_idx].albedo[2] /= alpha;
  920. //transfer emission to light
  921. bake_cells.write[p_idx].emission[0] /= alpha;
  922. bake_cells.write[p_idx].emission[1] /= alpha;
  923. bake_cells.write[p_idx].emission[2] /= alpha;
  924. bake_cells.write[p_idx].normal[0] /= alpha;
  925. bake_cells.write[p_idx].normal[1] /= alpha;
  926. bake_cells.write[p_idx].normal[2] /= alpha;
  927. Vector3 n(bake_cells[p_idx].normal[0], bake_cells[p_idx].normal[1], bake_cells[p_idx].normal[2]);
  928. if (n.length() < 0.01) {
  929. //too much fight over normal, zero it
  930. bake_cells.write[p_idx].normal[0] = 0;
  931. bake_cells.write[p_idx].normal[1] = 0;
  932. bake_cells.write[p_idx].normal[2] = 0;
  933. } else {
  934. n.normalize();
  935. bake_cells.write[p_idx].normal[0] = n.x;
  936. bake_cells.write[p_idx].normal[1] = n.y;
  937. bake_cells.write[p_idx].normal[2] = n.z;
  938. }
  939. bake_cells.write[p_idx].alpha = 1.0;
  940. /*if (bake_light.size()) {
  941. for(int i=0;i<6;i++) {
  942. }
  943. }*/
  944. } else {
  945. //go down
  946. bake_cells.write[p_idx].emission[0] = 0;
  947. bake_cells.write[p_idx].emission[1] = 0;
  948. bake_cells.write[p_idx].emission[2] = 0;
  949. bake_cells.write[p_idx].normal[0] = 0;
  950. bake_cells.write[p_idx].normal[1] = 0;
  951. bake_cells.write[p_idx].normal[2] = 0;
  952. bake_cells.write[p_idx].albedo[0] = 0;
  953. bake_cells.write[p_idx].albedo[1] = 0;
  954. bake_cells.write[p_idx].albedo[2] = 0;
  955. if (bake_light.size()) {
  956. for (int j = 0; j < 6; j++) {
  957. bake_light.write[p_idx].accum[j][0] = 0;
  958. bake_light.write[p_idx].accum[j][1] = 0;
  959. bake_light.write[p_idx].accum[j][2] = 0;
  960. }
  961. }
  962. float alpha_average = 0;
  963. int children_found = 0;
  964. for (int i = 0; i < 8; i++) {
  965. uint32_t child = bake_cells[p_idx].children[i];
  966. if (child == CHILD_EMPTY)
  967. continue;
  968. _fixup_plot(child, p_level + 1);
  969. alpha_average += bake_cells[child].alpha;
  970. if (bake_light.size() > 0) {
  971. for (int j = 0; j < 6; j++) {
  972. bake_light.write[p_idx].accum[j][0] += bake_light[child].accum[j][0];
  973. bake_light.write[p_idx].accum[j][1] += bake_light[child].accum[j][1];
  974. bake_light.write[p_idx].accum[j][2] += bake_light[child].accum[j][2];
  975. }
  976. bake_cells.write[p_idx].emission[0] += bake_cells[child].emission[0];
  977. bake_cells.write[p_idx].emission[1] += bake_cells[child].emission[1];
  978. bake_cells.write[p_idx].emission[2] += bake_cells[child].emission[2];
  979. }
  980. children_found++;
  981. }
  982. bake_cells.write[p_idx].alpha = alpha_average / 8.0;
  983. if (bake_light.size() && children_found) {
  984. float divisor = Math::lerp(8, children_found, propagation);
  985. for (int j = 0; j < 6; j++) {
  986. bake_light.write[p_idx].accum[j][0] /= divisor;
  987. bake_light.write[p_idx].accum[j][1] /= divisor;
  988. bake_light.write[p_idx].accum[j][2] /= divisor;
  989. }
  990. bake_cells.write[p_idx].emission[0] /= divisor;
  991. bake_cells.write[p_idx].emission[1] /= divisor;
  992. bake_cells.write[p_idx].emission[2] /= divisor;
  993. }
  994. }
  995. }
  996. //make sure any cell (save for the root) has an empty cell previous to it, so it can be interpolated into
  997. void VoxelLightBaker::_plot_triangle(Vector2 *vertices, Vector3 *positions, Vector3 *normals, LightMap *pixels, int width, int height) {
  998. int x[3];
  999. int y[3];
  1000. for (int j = 0; j < 3; j++) {
  1001. x[j] = vertices[j].x * width;
  1002. y[j] = vertices[j].y * height;
  1003. //x[j] = CLAMP(x[j], 0, bt.width - 1);
  1004. //y[j] = CLAMP(y[j], 0, bt.height - 1);
  1005. }
  1006. // sort the points vertically
  1007. if (y[1] > y[2]) {
  1008. SWAP(x[1], x[2]);
  1009. SWAP(y[1], y[2]);
  1010. SWAP(positions[1], positions[2]);
  1011. SWAP(normals[1], normals[2]);
  1012. }
  1013. if (y[0] > y[1]) {
  1014. SWAP(x[0], x[1]);
  1015. SWAP(y[0], y[1]);
  1016. SWAP(positions[0], positions[1]);
  1017. SWAP(normals[0], normals[1]);
  1018. }
  1019. if (y[1] > y[2]) {
  1020. SWAP(x[1], x[2]);
  1021. SWAP(y[1], y[2]);
  1022. SWAP(positions[1], positions[2]);
  1023. SWAP(normals[1], normals[2]);
  1024. }
  1025. double dx_far = double(x[2] - x[0]) / (y[2] - y[0] + 1);
  1026. double dx_upper = double(x[1] - x[0]) / (y[1] - y[0] + 1);
  1027. double dx_low = double(x[2] - x[1]) / (y[2] - y[1] + 1);
  1028. double xf = x[0];
  1029. double xt = x[0] + dx_upper; // if y[0] == y[1], special case
  1030. for (int yi = y[0]; yi <= (y[2] > height - 1 ? height - 1 : y[2]); yi++) {
  1031. if (yi >= 0) {
  1032. for (int xi = (xf > 0 ? int(xf) : 0); xi <= (xt < width ? xt : width - 1); xi++) {
  1033. //pixels[int(x + y * width)] = color;
  1034. Vector2 v0 = Vector2(x[1] - x[0], y[1] - y[0]);
  1035. Vector2 v1 = Vector2(x[2] - x[0], y[2] - y[0]);
  1036. //vertices[2] - vertices[0];
  1037. Vector2 v2 = Vector2(xi - x[0], yi - y[0]);
  1038. float d00 = v0.dot(v0);
  1039. float d01 = v0.dot(v1);
  1040. float d11 = v1.dot(v1);
  1041. float d20 = v2.dot(v0);
  1042. float d21 = v2.dot(v1);
  1043. float denom = (d00 * d11 - d01 * d01);
  1044. Vector3 pos;
  1045. Vector3 normal;
  1046. if (denom == 0) {
  1047. pos = positions[0];
  1048. normal = normals[0];
  1049. } else {
  1050. float v = (d11 * d20 - d01 * d21) / denom;
  1051. float w = (d00 * d21 - d01 * d20) / denom;
  1052. float u = 1.0f - v - w;
  1053. pos = positions[0] * u + positions[1] * v + positions[2] * w;
  1054. normal = normals[0] * u + normals[1] * v + normals[2] * w;
  1055. }
  1056. int ofs = yi * width + xi;
  1057. pixels[ofs].normal = normal;
  1058. pixels[ofs].pos = pos;
  1059. }
  1060. for (int xi = (xf < width ? int(xf) : width - 1); xi >= (xt > 0 ? xt : 0); xi--) {
  1061. //pixels[int(x + y * width)] = color;
  1062. Vector2 v0 = Vector2(x[1] - x[0], y[1] - y[0]);
  1063. Vector2 v1 = Vector2(x[2] - x[0], y[2] - y[0]);
  1064. //vertices[2] - vertices[0];
  1065. Vector2 v2 = Vector2(xi - x[0], yi - y[0]);
  1066. float d00 = v0.dot(v0);
  1067. float d01 = v0.dot(v1);
  1068. float d11 = v1.dot(v1);
  1069. float d20 = v2.dot(v0);
  1070. float d21 = v2.dot(v1);
  1071. float denom = (d00 * d11 - d01 * d01);
  1072. Vector3 pos;
  1073. Vector3 normal;
  1074. if (denom == 0) {
  1075. pos = positions[0];
  1076. normal = normals[0];
  1077. } else {
  1078. float v = (d11 * d20 - d01 * d21) / denom;
  1079. float w = (d00 * d21 - d01 * d20) / denom;
  1080. float u = 1.0f - v - w;
  1081. pos = positions[0] * u + positions[1] * v + positions[2] * w;
  1082. normal = normals[0] * u + normals[1] * v + normals[2] * w;
  1083. }
  1084. int ofs = yi * width + xi;
  1085. pixels[ofs].normal = normal;
  1086. pixels[ofs].pos = pos;
  1087. }
  1088. }
  1089. xf += dx_far;
  1090. if (yi < y[1])
  1091. xt += dx_upper;
  1092. else
  1093. xt += dx_low;
  1094. }
  1095. }
  1096. void VoxelLightBaker::_sample_baked_octree_filtered_and_anisotropic(const Vector3 &p_posf, const Vector3 &p_direction, float p_level, Vector3 &r_color, float &r_alpha) {
  1097. int size = 1 << (cell_subdiv - 1);
  1098. int clamp_v = size - 1;
  1099. //first of all, clamp
  1100. Vector3 pos;
  1101. pos.x = CLAMP(p_posf.x, 0, clamp_v);
  1102. pos.y = CLAMP(p_posf.y, 0, clamp_v);
  1103. pos.z = CLAMP(p_posf.z, 0, clamp_v);
  1104. float level = (cell_subdiv - 1) - p_level;
  1105. int target_level;
  1106. float level_filter;
  1107. if (level <= 0.0) {
  1108. level_filter = 0;
  1109. target_level = 0;
  1110. } else {
  1111. target_level = Math::ceil(level);
  1112. level_filter = target_level - level;
  1113. }
  1114. const Cell *cells = bake_cells.ptr();
  1115. const Light *light = bake_light.ptr();
  1116. Vector3 color[2][8];
  1117. float alpha[2][8];
  1118. zeromem(alpha, sizeof(float) * 2 * 8);
  1119. //find cell at given level first
  1120. for (int c = 0; c < 2; c++) {
  1121. int current_level = MAX(0, target_level - c);
  1122. int level_cell_size = (1 << (cell_subdiv - 1)) >> current_level;
  1123. for (int n = 0; n < 8; n++) {
  1124. int x = int(pos.x);
  1125. int y = int(pos.y);
  1126. int z = int(pos.z);
  1127. if (n & 1)
  1128. x += level_cell_size;
  1129. if (n & 2)
  1130. y += level_cell_size;
  1131. if (n & 4)
  1132. z += level_cell_size;
  1133. int ofs_x = 0;
  1134. int ofs_y = 0;
  1135. int ofs_z = 0;
  1136. x = CLAMP(x, 0, clamp_v);
  1137. y = CLAMP(y, 0, clamp_v);
  1138. z = CLAMP(z, 0, clamp_v);
  1139. int half = size / 2;
  1140. uint32_t cell = 0;
  1141. for (int i = 0; i < current_level; i++) {
  1142. const Cell *bc = &cells[cell];
  1143. int child = 0;
  1144. if (x >= ofs_x + half) {
  1145. child |= 1;
  1146. ofs_x += half;
  1147. }
  1148. if (y >= ofs_y + half) {
  1149. child |= 2;
  1150. ofs_y += half;
  1151. }
  1152. if (z >= ofs_z + half) {
  1153. child |= 4;
  1154. ofs_z += half;
  1155. }
  1156. cell = bc->children[child];
  1157. if (cell == CHILD_EMPTY)
  1158. break;
  1159. half >>= 1;
  1160. }
  1161. if (cell == CHILD_EMPTY) {
  1162. alpha[c][n] = 0;
  1163. } else {
  1164. alpha[c][n] = cells[cell].alpha;
  1165. for (int i = 0; i < 6; i++) {
  1166. //anisotropic read light
  1167. float amount = p_direction.dot(aniso_normal[i]);
  1168. if (amount < 0)
  1169. amount = 0;
  1170. color[c][n].x += light[cell].accum[i][0] * amount;
  1171. color[c][n].y += light[cell].accum[i][1] * amount;
  1172. color[c][n].z += light[cell].accum[i][2] * amount;
  1173. }
  1174. color[c][n].x += cells[cell].emission[0];
  1175. color[c][n].y += cells[cell].emission[1];
  1176. color[c][n].z += cells[cell].emission[2];
  1177. }
  1178. }
  1179. }
  1180. float target_level_size = size >> target_level;
  1181. Vector3 pos_fract[2];
  1182. pos_fract[0].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  1183. pos_fract[0].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  1184. pos_fract[0].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  1185. target_level_size = size >> MAX(0, target_level - 1);
  1186. pos_fract[1].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  1187. pos_fract[1].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  1188. pos_fract[1].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  1189. float alpha_interp[2];
  1190. Vector3 color_interp[2];
  1191. for (int i = 0; i < 2; i++) {
  1192. Vector3 color_x00 = color[i][0].linear_interpolate(color[i][1], pos_fract[i].x);
  1193. Vector3 color_xy0 = color[i][2].linear_interpolate(color[i][3], pos_fract[i].x);
  1194. Vector3 blend_z0 = color_x00.linear_interpolate(color_xy0, pos_fract[i].y);
  1195. Vector3 color_x0z = color[i][4].linear_interpolate(color[i][5], pos_fract[i].x);
  1196. Vector3 color_xyz = color[i][6].linear_interpolate(color[i][7], pos_fract[i].x);
  1197. Vector3 blend_z1 = color_x0z.linear_interpolate(color_xyz, pos_fract[i].y);
  1198. color_interp[i] = blend_z0.linear_interpolate(blend_z1, pos_fract[i].z);
  1199. float alpha_x00 = Math::lerp(alpha[i][0], alpha[i][1], pos_fract[i].x);
  1200. float alpha_xy0 = Math::lerp(alpha[i][2], alpha[i][3], pos_fract[i].x);
  1201. float alpha_z0 = Math::lerp(alpha_x00, alpha_xy0, pos_fract[i].y);
  1202. float alpha_x0z = Math::lerp(alpha[i][4], alpha[i][5], pos_fract[i].x);
  1203. float alpha_xyz = Math::lerp(alpha[i][6], alpha[i][7], pos_fract[i].x);
  1204. float alpha_z1 = Math::lerp(alpha_x0z, alpha_xyz, pos_fract[i].y);
  1205. alpha_interp[i] = Math::lerp(alpha_z0, alpha_z1, pos_fract[i].z);
  1206. }
  1207. r_color = color_interp[0].linear_interpolate(color_interp[1], level_filter);
  1208. r_alpha = Math::lerp(alpha_interp[0], alpha_interp[1], level_filter);
  1209. }
  1210. Vector3 VoxelLightBaker::_voxel_cone_trace(const Vector3 &p_pos, const Vector3 &p_normal, float p_aperture) {
  1211. float bias = 2.5;
  1212. float max_distance = (Vector3(1, 1, 1) * (1 << (cell_subdiv - 1))).length();
  1213. float dist = bias;
  1214. float alpha = 0.0;
  1215. Vector3 color;
  1216. Vector3 scolor;
  1217. float salpha;
  1218. while (dist < max_distance && alpha < 0.95) {
  1219. float diameter = MAX(1.0, 2.0 * p_aperture * dist);
  1220. _sample_baked_octree_filtered_and_anisotropic(p_pos + dist * p_normal, p_normal, log2(diameter), scolor, salpha);
  1221. float a = (1.0 - alpha);
  1222. color += scolor * a;
  1223. alpha += a * salpha;
  1224. dist += diameter * 0.5;
  1225. }
  1226. /*if (blend_ambient) {
  1227. color.rgb = mix(ambient,color.rgb,min(1.0,alpha/0.95));
  1228. }*/
  1229. return color;
  1230. }
  1231. Vector3 VoxelLightBaker::_compute_pixel_light_at_pos(const Vector3 &p_pos, const Vector3 &p_normal) {
  1232. //find arbitrary tangent and bitangent, then build a matrix
  1233. Vector3 v0 = Math::abs(p_normal.z) < 0.999 ? Vector3(0, 0, 1) : Vector3(0, 1, 0);
  1234. Vector3 tangent = v0.cross(p_normal).normalized();
  1235. Vector3 bitangent = tangent.cross(p_normal).normalized();
  1236. Basis normal_xform = Basis(tangent, bitangent, p_normal).transposed();
  1237. const Vector3 *cone_dirs = NULL;
  1238. const float *cone_weights = NULL;
  1239. int cone_dir_count = 0;
  1240. float cone_aperture = 0;
  1241. switch (bake_quality) {
  1242. case BAKE_QUALITY_LOW: {
  1243. //default quality
  1244. static const Vector3 dirs[4] = {
  1245. Vector3(0.707107, 0, 0.707107),
  1246. Vector3(0, 0.707107, 0.707107),
  1247. Vector3(-0.707107, 0, 0.707107),
  1248. Vector3(0, -0.707107, 0.707107)
  1249. };
  1250. static const float weights[4] = { 0.25, 0.25, 0.25, 0.25 };
  1251. cone_dirs = dirs;
  1252. cone_dir_count = 4;
  1253. cone_aperture = 1.0; // tan(angle) 90 degrees
  1254. cone_weights = weights;
  1255. } break;
  1256. case BAKE_QUALITY_MEDIUM: {
  1257. //default quality
  1258. static const Vector3 dirs[6] = {
  1259. Vector3(0, 0, 1),
  1260. Vector3(0.866025, 0, 0.5),
  1261. Vector3(0.267617, 0.823639, 0.5),
  1262. Vector3(-0.700629, 0.509037, 0.5),
  1263. Vector3(-0.700629, -0.509037, 0.5),
  1264. Vector3(0.267617, -0.823639, 0.5)
  1265. };
  1266. static const float weights[6] = { 0.25f, 0.15f, 0.15f, 0.15f, 0.15f, 0.15f };
  1267. //
  1268. cone_dirs = dirs;
  1269. cone_dir_count = 6;
  1270. cone_aperture = 0.577; // tan(angle) 60 degrees
  1271. cone_weights = weights;
  1272. } break;
  1273. case BAKE_QUALITY_HIGH: {
  1274. //high qualily
  1275. static const Vector3 dirs[10] = {
  1276. Vector3(0.8781648411741658, 0.0, 0.478358141694643),
  1277. Vector3(0.5369754325592234, 0.6794204427701518, 0.5000452447267606),
  1278. Vector3(-0.19849436573466497, 0.8429904390140635, 0.49996710542041645),
  1279. Vector3(-0.7856196499811189, 0.3639120321329737, 0.5003696617825604),
  1280. Vector3(-0.7856196499811189, -0.3639120321329737, 0.5003696617825604),
  1281. Vector3(-0.19849436573466497, -0.8429904390140635, 0.49996710542041645),
  1282. Vector3(0.5369754325592234, -0.6794204427701518, 0.5000452447267606),
  1283. Vector3(-0.4451656858129485, 0.0, 0.8954482185892644),
  1284. Vector3(0.19124006749743122, 0.39355745585016605, 0.8991883926788214),
  1285. Vector3(0.19124006749743122, -0.39355745585016605, 0.8991883926788214),
  1286. };
  1287. static const float weights[10] = { 0.08571f, 0.08571f, 0.08571f, 0.08571f, 0.08571f, 0.08571f, 0.08571f, 0.133333f, 0.133333f, 0.13333f };
  1288. cone_dirs = dirs;
  1289. cone_dir_count = 10;
  1290. cone_aperture = 0.404; // tan(angle) 45 degrees
  1291. cone_weights = weights;
  1292. } break;
  1293. }
  1294. Vector3 accum;
  1295. for (int i = 0; i < cone_dir_count; i++) {
  1296. Vector3 dir = normal_xform.xform(cone_dirs[i]).normalized(); //normal may not completely correct when transformed to cell
  1297. accum += _voxel_cone_trace(p_pos, dir, cone_aperture) * cone_weights[i];
  1298. }
  1299. return accum;
  1300. }
  1301. _ALWAYS_INLINE_ uint32_t xorshift32(uint32_t *state) {
  1302. /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
  1303. uint32_t x = *state;
  1304. x ^= x << 13;
  1305. x ^= x >> 17;
  1306. x ^= x << 5;
  1307. *state = x;
  1308. return x;
  1309. }
  1310. Vector3 VoxelLightBaker::_compute_ray_trace_at_pos(const Vector3 &p_pos, const Vector3 &p_normal) {
  1311. int samples_per_quality[3] = { 48, 128, 512 };
  1312. int samples = samples_per_quality[bake_quality];
  1313. //create a basis in Z
  1314. Vector3 v0 = Math::abs(p_normal.z) < 0.999 ? Vector3(0, 0, 1) : Vector3(0, 1, 0);
  1315. Vector3 tangent = v0.cross(p_normal).normalized();
  1316. Vector3 bitangent = tangent.cross(p_normal).normalized();
  1317. Basis normal_xform = Basis(tangent, bitangent, p_normal).transposed();
  1318. float bias = 1.5;
  1319. int max_level = cell_subdiv - 1;
  1320. int size = 1 << max_level;
  1321. Vector3 accum;
  1322. float spread = Math::deg2rad(80.0);
  1323. const Light *light = bake_light.ptr();
  1324. const Cell *cells = bake_cells.ptr();
  1325. uint32_t local_rng_state = rand(); //needs to be fixed again
  1326. for (int i = 0; i < samples; i++) {
  1327. float random_angle1 = (((xorshift32(&local_rng_state) % 65535) / 65535.0) * 2.0 - 1.0) * spread;
  1328. Vector3 axis(0, sin(random_angle1), cos(random_angle1));
  1329. float random_angle2 = ((xorshift32(&local_rng_state) % 65535) / 65535.0) * Math_PI * 2.0;
  1330. Basis rot(Vector3(0, 0, 1), random_angle2);
  1331. axis = rot.xform(axis);
  1332. Vector3 direction = normal_xform.xform(axis).normalized();
  1333. Vector3 advance = direction * _get_normal_advance(direction);
  1334. Vector3 pos = p_pos /*+ Vector3(0.5, 0.5, 0.5)*/ + advance * bias;
  1335. uint32_t cell = CHILD_EMPTY;
  1336. while (cell == CHILD_EMPTY) {
  1337. int x = int(pos.x);
  1338. int y = int(pos.y);
  1339. int z = int(pos.z);
  1340. int ofs_x = 0;
  1341. int ofs_y = 0;
  1342. int ofs_z = 0;
  1343. int half = size / 2;
  1344. if (x < 0 || x >= size)
  1345. break;
  1346. if (y < 0 || y >= size)
  1347. break;
  1348. if (z < 0 || z >= size)
  1349. break;
  1350. //int level_limit = max_level;
  1351. cell = 0; //start from root
  1352. for (int j = 0; j < max_level; j++) {
  1353. const Cell *bc = &cells[cell];
  1354. int child = 0;
  1355. if (x >= ofs_x + half) {
  1356. child |= 1;
  1357. ofs_x += half;
  1358. }
  1359. if (y >= ofs_y + half) {
  1360. child |= 2;
  1361. ofs_y += half;
  1362. }
  1363. if (z >= ofs_z + half) {
  1364. child |= 4;
  1365. ofs_z += half;
  1366. }
  1367. cell = bc->children[child];
  1368. if (unlikely(cell == CHILD_EMPTY))
  1369. break;
  1370. half >>= 1;
  1371. }
  1372. pos += advance;
  1373. }
  1374. if (unlikely(cell != CHILD_EMPTY)) {
  1375. for (int j = 0; j < 6; j++) {
  1376. //anisotropic read light
  1377. float amount = direction.dot(aniso_normal[j]);
  1378. if (amount <= 0)
  1379. continue;
  1380. accum.x += light[cell].accum[j][0] * amount;
  1381. accum.y += light[cell].accum[j][1] * amount;
  1382. accum.z += light[cell].accum[j][2] * amount;
  1383. }
  1384. accum.x += cells[cell].emission[0];
  1385. accum.y += cells[cell].emission[1];
  1386. accum.z += cells[cell].emission[2];
  1387. }
  1388. }
  1389. // Make sure we don't reset this thread's RNG state
  1390. return accum / samples;
  1391. }
  1392. void VoxelLightBaker::_lightmap_bake_point(uint32_t p_x, LightMap *p_line) {
  1393. LightMap *pixel = &p_line[p_x];
  1394. if (pixel->pos == Vector3())
  1395. return;
  1396. switch (bake_mode) {
  1397. case BAKE_MODE_CONE_TRACE: {
  1398. pixel->light = _compute_pixel_light_at_pos(pixel->pos, pixel->normal) * energy;
  1399. } break;
  1400. case BAKE_MODE_RAY_TRACE: {
  1401. pixel->light = _compute_ray_trace_at_pos(pixel->pos, pixel->normal) * energy;
  1402. } break;
  1403. }
  1404. }
  1405. Error VoxelLightBaker::make_lightmap(const Transform &p_xform, Ref<Mesh> &p_mesh, LightMapData &r_lightmap, bool (*p_bake_time_func)(void *, float, float), void *p_bake_time_ud) {
  1406. //transfer light information to a lightmap
  1407. Ref<Mesh> mesh = p_mesh;
  1408. int width = mesh->get_lightmap_size_hint().x;
  1409. int height = mesh->get_lightmap_size_hint().y;
  1410. //step 1 - create lightmap
  1411. Vector<LightMap> lightmap;
  1412. lightmap.resize(width * height);
  1413. Transform xform = to_cell_space * p_xform;
  1414. //step 2 plot faces to lightmap
  1415. for (int i = 0; i < mesh->get_surface_count(); i++) {
  1416. Array arrays = mesh->surface_get_arrays(i);
  1417. PoolVector<Vector3> vertices = arrays[Mesh::ARRAY_VERTEX];
  1418. PoolVector<Vector3> normals = arrays[Mesh::ARRAY_NORMAL];
  1419. PoolVector<Vector2> uv2 = arrays[Mesh::ARRAY_TEX_UV2];
  1420. PoolVector<int> indices = arrays[Mesh::ARRAY_INDEX];
  1421. ERR_FAIL_COND_V(vertices.size() == 0, ERR_INVALID_PARAMETER);
  1422. ERR_FAIL_COND_V(normals.size() == 0, ERR_INVALID_PARAMETER);
  1423. ERR_FAIL_COND_V(uv2.size() == 0, ERR_INVALID_PARAMETER);
  1424. int vc = vertices.size();
  1425. PoolVector<Vector3>::Read vr = vertices.read();
  1426. PoolVector<Vector3>::Read nr = normals.read();
  1427. PoolVector<Vector2>::Read u2r = uv2.read();
  1428. PoolVector<int>::Read ir;
  1429. int ic = 0;
  1430. if (indices.size()) {
  1431. ic = indices.size();
  1432. ir = indices.read();
  1433. }
  1434. int faces = ic ? ic / 3 : vc / 3;
  1435. for (int j = 0; j < faces; j++) {
  1436. Vector3 vertex[3];
  1437. Vector3 normal[3];
  1438. Vector2 uv[3];
  1439. for (int k = 0; k < 3; k++) {
  1440. int idx = ic ? ir[j * 3 + k] : j * 3 + k;
  1441. vertex[k] = xform.xform(vr[idx]);
  1442. normal[k] = xform.basis.xform(nr[idx]).normalized();
  1443. uv[k] = u2r[idx];
  1444. }
  1445. _plot_triangle(uv, vertex, normal, lightmap.ptrw(), width, height);
  1446. }
  1447. }
  1448. //step 3 perform voxel cone trace on lightmap pixels
  1449. {
  1450. LightMap *lightmap_ptr = lightmap.ptrw();
  1451. uint64_t begin_time = OS::get_singleton()->get_ticks_usec();
  1452. volatile int lines = 0;
  1453. // make sure our OS-level rng is seeded
  1454. for (int i = 0; i < height; i++) {
  1455. thread_process_array(width, this, &VoxelLightBaker::_lightmap_bake_point, &lightmap_ptr[i * width]);
  1456. lines = MAX(lines, i); //for multithread
  1457. if (p_bake_time_func) {
  1458. uint64_t elapsed = OS::get_singleton()->get_ticks_usec() - begin_time;
  1459. float elapsed_sec = double(elapsed) / 1000000.0;
  1460. float remaining = lines < 1 ? 0 : (elapsed_sec / lines) * (height - lines - 1);
  1461. if (p_bake_time_func(p_bake_time_ud, remaining, lines / float(height))) {
  1462. return ERR_SKIP;
  1463. }
  1464. }
  1465. }
  1466. if (bake_mode == BAKE_MODE_RAY_TRACE) {
  1467. //blur
  1468. //gauss kernel, 7 step sigma 2
  1469. static const float gauss_kernel[4] = { 0.214607f, 0.189879f, 0.131514f, 0.071303f };
  1470. //horizontal pass
  1471. for (int i = 0; i < height; i++) {
  1472. for (int j = 0; j < width; j++) {
  1473. if (lightmap_ptr[i * width + j].normal == Vector3()) {
  1474. continue; //empty
  1475. }
  1476. float gauss_sum = gauss_kernel[0];
  1477. Vector3 accum = lightmap_ptr[i * width + j].light * gauss_kernel[0];
  1478. for (int k = 1; k < 4; k++) {
  1479. int new_x = j + k;
  1480. if (new_x >= width || lightmap_ptr[i * width + new_x].normal == Vector3())
  1481. break;
  1482. gauss_sum += gauss_kernel[k];
  1483. accum += lightmap_ptr[i * width + new_x].light * gauss_kernel[k];
  1484. }
  1485. for (int k = 1; k < 4; k++) {
  1486. int new_x = j - k;
  1487. if (new_x < 0 || lightmap_ptr[i * width + new_x].normal == Vector3())
  1488. break;
  1489. gauss_sum += gauss_kernel[k];
  1490. accum += lightmap_ptr[i * width + new_x].light * gauss_kernel[k];
  1491. }
  1492. lightmap_ptr[i * width + j].pos = accum /= gauss_sum;
  1493. }
  1494. }
  1495. //vertical pass
  1496. for (int i = 0; i < height; i++) {
  1497. for (int j = 0; j < width; j++) {
  1498. if (lightmap_ptr[i * width + j].normal == Vector3())
  1499. continue; //empty, don't write over it anyway
  1500. float gauss_sum = gauss_kernel[0];
  1501. Vector3 accum = lightmap_ptr[i * width + j].pos * gauss_kernel[0];
  1502. for (int k = 1; k < 4; k++) {
  1503. int new_y = i + k;
  1504. if (new_y >= height || lightmap_ptr[new_y * width + j].normal == Vector3())
  1505. break;
  1506. gauss_sum += gauss_kernel[k];
  1507. accum += lightmap_ptr[new_y * width + j].pos * gauss_kernel[k];
  1508. }
  1509. for (int k = 1; k < 4; k++) {
  1510. int new_y = i - k;
  1511. if (new_y < 0 || lightmap_ptr[new_y * width + j].normal == Vector3())
  1512. break;
  1513. gauss_sum += gauss_kernel[k];
  1514. accum += lightmap_ptr[new_y * width + j].pos * gauss_kernel[k];
  1515. }
  1516. lightmap_ptr[i * width + j].light = accum /= gauss_sum;
  1517. }
  1518. }
  1519. }
  1520. //add directional light (do this after blur)
  1521. {
  1522. const Cell *cells = bake_cells.ptr();
  1523. const Light *light = bake_light.ptr();
  1524. #ifdef _OPENMP
  1525. #pragma omp parallel
  1526. #endif
  1527. for (int i = 0; i < height; i++) {
  1528. #ifdef _OPENMP
  1529. #pragma omp parallel for schedule(dynamic, 1)
  1530. #endif
  1531. for (int j = 0; j < width; j++) {
  1532. //if (i == 125 && j == 280) {
  1533. LightMap *pixel = &lightmap_ptr[i * width + j];
  1534. if (pixel->pos == Vector3())
  1535. continue; //unused, skipe
  1536. int x = int(pixel->pos.x) - 1;
  1537. int y = int(pixel->pos.y) - 1;
  1538. int z = int(pixel->pos.z) - 1;
  1539. Color accum;
  1540. int size = 1 << (cell_subdiv - 1);
  1541. int found = 0;
  1542. for (int k = 0; k < 8; k++) {
  1543. int ofs_x = x;
  1544. int ofs_y = y;
  1545. int ofs_z = z;
  1546. if (k & 1)
  1547. ofs_x++;
  1548. if (k & 2)
  1549. ofs_y++;
  1550. if (k & 4)
  1551. ofs_z++;
  1552. if (x < 0 || x >= size)
  1553. continue;
  1554. if (y < 0 || y >= size)
  1555. continue;
  1556. if (z < 0 || z >= size)
  1557. continue;
  1558. uint32_t cell = _find_cell_at_pos(cells, ofs_x, ofs_y, ofs_z);
  1559. if (cell == CHILD_EMPTY)
  1560. continue;
  1561. for (int l = 0; l < 6; l++) {
  1562. float s = pixel->normal.dot(aniso_normal[l]);
  1563. if (s < 0)
  1564. s = 0;
  1565. accum.r += light[cell].direct_accum[l][0] * s;
  1566. accum.g += light[cell].direct_accum[l][1] * s;
  1567. accum.b += light[cell].direct_accum[l][2] * s;
  1568. }
  1569. found++;
  1570. }
  1571. if (found) {
  1572. accum /= found;
  1573. pixel->light.x += accum.r;
  1574. pixel->light.y += accum.g;
  1575. pixel->light.z += accum.b;
  1576. }
  1577. }
  1578. }
  1579. }
  1580. {
  1581. //fill gaps with neighbour vertices to avoid filter fades to black on edges
  1582. for (int i = 0; i < height; i++) {
  1583. for (int j = 0; j < width; j++) {
  1584. if (lightmap_ptr[i * width + j].normal != Vector3()) {
  1585. continue; //filled, skip
  1586. }
  1587. //this can't be made separatable..
  1588. int closest_i = -1, closest_j = 1;
  1589. float closest_dist = 1e20;
  1590. const int margin = 3;
  1591. for (int y = i - margin; y <= i + margin; y++) {
  1592. for (int x = j - margin; x <= j + margin; x++) {
  1593. if (x == j && y == i)
  1594. continue;
  1595. if (x < 0 || x >= width)
  1596. continue;
  1597. if (y < 0 || y >= height)
  1598. continue;
  1599. if (lightmap_ptr[y * width + x].normal == Vector3())
  1600. continue; //also ensures that blitted stuff is not reused
  1601. float dist = Vector2(i - y, j - x).length();
  1602. if (dist > closest_dist)
  1603. continue;
  1604. closest_dist = dist;
  1605. closest_i = y;
  1606. closest_j = x;
  1607. }
  1608. }
  1609. if (closest_i != -1) {
  1610. lightmap_ptr[i * width + j].light = lightmap_ptr[closest_i * width + closest_j].light;
  1611. }
  1612. }
  1613. }
  1614. }
  1615. {
  1616. //fill the lightmap data
  1617. r_lightmap.width = width;
  1618. r_lightmap.height = height;
  1619. r_lightmap.light.resize(lightmap.size() * 3);
  1620. PoolVector<float>::Write w = r_lightmap.light.write();
  1621. for (int i = 0; i < lightmap.size(); i++) {
  1622. w[i * 3 + 0] = lightmap[i].light.x;
  1623. w[i * 3 + 1] = lightmap[i].light.y;
  1624. w[i * 3 + 2] = lightmap[i].light.z;
  1625. }
  1626. }
  1627. // Enable for debugging
  1628. #if 0
  1629. {
  1630. PoolVector<uint8_t> img;
  1631. int ls = lightmap.size();
  1632. img.resize(ls * 3);
  1633. {
  1634. PoolVector<uint8_t>::Write w = img.write();
  1635. for (int i = 0; i < ls; i++) {
  1636. w[i * 3 + 0] = CLAMP(lightmap_ptr[i].light.x * 255, 0, 255);
  1637. w[i * 3 + 1] = CLAMP(lightmap_ptr[i].light.y * 255, 0, 255);
  1638. w[i * 3 + 2] = CLAMP(lightmap_ptr[i].light.z * 255, 0, 255);
  1639. //w[i * 3 + 0] = CLAMP(lightmap_ptr[i].normal.x * 255, 0, 255);
  1640. //w[i * 3 + 1] = CLAMP(lightmap_ptr[i].normal.y * 255, 0, 255);
  1641. //w[i * 3 + 2] = CLAMP(lightmap_ptr[i].normal.z * 255, 0, 255);
  1642. //w[i * 3 + 0] = CLAMP(lightmap_ptr[i].pos.x / (1 << (cell_subdiv - 1)) * 255, 0, 255);
  1643. //w[i * 3 + 1] = CLAMP(lightmap_ptr[i].pos.y / (1 << (cell_subdiv - 1)) * 255, 0, 255);
  1644. //w[i * 3 + 2] = CLAMP(lightmap_ptr[i].pos.z / (1 << (cell_subdiv - 1)) * 255, 0, 255);
  1645. }
  1646. }
  1647. Ref<Image> image;
  1648. image.instance();
  1649. image->create(width, height, false, Image::FORMAT_RGB8, img);
  1650. String name = p_mesh->get_name();
  1651. if (name == "") {
  1652. name = "Mesh" + itos(p_mesh->get_instance_id());
  1653. }
  1654. image->save_png(name + ".png");
  1655. }
  1656. #endif
  1657. }
  1658. return OK;
  1659. }
  1660. void VoxelLightBaker::begin_bake(int p_subdiv, const AABB &p_bounds) {
  1661. original_bounds = p_bounds;
  1662. cell_subdiv = p_subdiv;
  1663. bake_cells.resize(1);
  1664. material_cache.clear();
  1665. //find out the actual real bounds, power of 2, which gets the highest subdivision
  1666. po2_bounds = p_bounds;
  1667. int longest_axis = po2_bounds.get_longest_axis_index();
  1668. axis_cell_size[longest_axis] = (1 << (cell_subdiv - 1));
  1669. leaf_voxel_count = 0;
  1670. for (int i = 0; i < 3; i++) {
  1671. if (i == longest_axis)
  1672. continue;
  1673. axis_cell_size[i] = axis_cell_size[longest_axis];
  1674. float axis_size = po2_bounds.size[longest_axis];
  1675. //shrink until fit subdiv
  1676. while (axis_size / 2.0 >= po2_bounds.size[i]) {
  1677. axis_size /= 2.0;
  1678. axis_cell_size[i] >>= 1;
  1679. }
  1680. po2_bounds.size[i] = po2_bounds.size[longest_axis];
  1681. }
  1682. Transform to_bounds;
  1683. to_bounds.basis.scale(Vector3(po2_bounds.size[longest_axis], po2_bounds.size[longest_axis], po2_bounds.size[longest_axis]));
  1684. to_bounds.origin = po2_bounds.position;
  1685. Transform to_grid;
  1686. to_grid.basis.scale(Vector3(axis_cell_size[longest_axis], axis_cell_size[longest_axis], axis_cell_size[longest_axis]));
  1687. to_cell_space = to_grid * to_bounds.affine_inverse();
  1688. cell_size = po2_bounds.size[longest_axis] / axis_cell_size[longest_axis];
  1689. }
  1690. void VoxelLightBaker::end_bake() {
  1691. _fixup_plot(0, 0);
  1692. }
  1693. //create the data for visual server
  1694. PoolVector<int> VoxelLightBaker::create_gi_probe_data() {
  1695. PoolVector<int> data;
  1696. data.resize(16 + (8 + 1 + 1 + 1 + 1) * bake_cells.size()); //4 for header, rest for rest.
  1697. {
  1698. PoolVector<int>::Write w = data.write();
  1699. uint32_t *w32 = (uint32_t *)w.ptr();
  1700. w32[0] = 0; //version
  1701. w32[1] = cell_subdiv; //subdiv
  1702. w32[2] = axis_cell_size[0];
  1703. w32[3] = axis_cell_size[1];
  1704. w32[4] = axis_cell_size[2];
  1705. w32[5] = bake_cells.size();
  1706. w32[6] = leaf_voxel_count;
  1707. int ofs = 16;
  1708. for (int i = 0; i < bake_cells.size(); i++) {
  1709. for (int j = 0; j < 8; j++) {
  1710. w32[ofs++] = bake_cells[i].children[j];
  1711. }
  1712. { //albedo
  1713. uint32_t rgba = uint32_t(CLAMP(bake_cells[i].albedo[0] * 255.0, 0, 255)) << 16;
  1714. rgba |= uint32_t(CLAMP(bake_cells[i].albedo[1] * 255.0, 0, 255)) << 8;
  1715. rgba |= uint32_t(CLAMP(bake_cells[i].albedo[2] * 255.0, 0, 255)) << 0;
  1716. w32[ofs++] = rgba;
  1717. }
  1718. { //emission
  1719. Vector3 e(bake_cells[i].emission[0], bake_cells[i].emission[1], bake_cells[i].emission[2]);
  1720. float l = e.length();
  1721. if (l > 0) {
  1722. e.normalize();
  1723. l = CLAMP(l / 8.0, 0, 1.0);
  1724. }
  1725. uint32_t em = uint32_t(CLAMP(e[0] * 255, 0, 255)) << 24;
  1726. em |= uint32_t(CLAMP(e[1] * 255, 0, 255)) << 16;
  1727. em |= uint32_t(CLAMP(e[2] * 255, 0, 255)) << 8;
  1728. em |= uint32_t(CLAMP(l * 255, 0, 255));
  1729. w32[ofs++] = em;
  1730. }
  1731. //w32[ofs++]=bake_cells[i].used_sides;
  1732. { //normal
  1733. Vector3 n(bake_cells[i].normal[0], bake_cells[i].normal[1], bake_cells[i].normal[2]);
  1734. n = n * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
  1735. uint32_t norm = 0;
  1736. norm |= uint32_t(CLAMP(n.x * 255.0, 0, 255)) << 16;
  1737. norm |= uint32_t(CLAMP(n.y * 255.0, 0, 255)) << 8;
  1738. norm |= uint32_t(CLAMP(n.z * 255.0, 0, 255)) << 0;
  1739. w32[ofs++] = norm;
  1740. }
  1741. {
  1742. uint16_t alpha = MIN(uint32_t(bake_cells[i].alpha * 65535.0), 65535);
  1743. uint16_t level = bake_cells[i].level;
  1744. w32[ofs++] = (uint32_t(level) << 16) | uint32_t(alpha);
  1745. }
  1746. }
  1747. }
  1748. return data;
  1749. }
  1750. void VoxelLightBaker::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx, DebugMode p_mode) {
  1751. if (p_level == cell_subdiv - 1) {
  1752. Vector3 center = p_aabb.position + p_aabb.size * 0.5;
  1753. Transform xform;
  1754. xform.origin = center;
  1755. xform.basis.scale(p_aabb.size * 0.5);
  1756. p_multimesh->set_instance_transform(idx, xform);
  1757. Color col;
  1758. if (p_mode == DEBUG_ALBEDO) {
  1759. col = Color(bake_cells[p_idx].albedo[0], bake_cells[p_idx].albedo[1], bake_cells[p_idx].albedo[2]);
  1760. } else if (p_mode == DEBUG_LIGHT) {
  1761. for (int i = 0; i < 6; i++) {
  1762. col.r += bake_light[p_idx].accum[i][0];
  1763. col.g += bake_light[p_idx].accum[i][1];
  1764. col.b += bake_light[p_idx].accum[i][2];
  1765. col.r += bake_light[p_idx].direct_accum[i][0];
  1766. col.g += bake_light[p_idx].direct_accum[i][1];
  1767. col.b += bake_light[p_idx].direct_accum[i][2];
  1768. }
  1769. }
  1770. //Color col = Color(bake_cells[p_idx].emission[0], bake_cells[p_idx].emission[1], bake_cells[p_idx].emission[2]);
  1771. p_multimesh->set_instance_color(idx, col);
  1772. idx++;
  1773. } else {
  1774. for (int i = 0; i < 8; i++) {
  1775. uint32_t child = bake_cells[p_idx].children[i];
  1776. if (child == CHILD_EMPTY || child >= (uint32_t)max_original_cells)
  1777. continue;
  1778. AABB aabb = p_aabb;
  1779. aabb.size *= 0.5;
  1780. if (i & 1)
  1781. aabb.position.x += aabb.size.x;
  1782. if (i & 2)
  1783. aabb.position.y += aabb.size.y;
  1784. if (i & 4)
  1785. aabb.position.z += aabb.size.z;
  1786. _debug_mesh(bake_cells[p_idx].children[i], p_level + 1, aabb, p_multimesh, idx, p_mode);
  1787. }
  1788. }
  1789. }
  1790. Ref<MultiMesh> VoxelLightBaker::create_debug_multimesh(DebugMode p_mode) {
  1791. Ref<MultiMesh> mm;
  1792. ERR_FAIL_COND_V(p_mode == DEBUG_LIGHT && bake_light.size() == 0, mm);
  1793. mm.instance();
  1794. mm->set_transform_format(MultiMesh::TRANSFORM_3D);
  1795. mm->set_color_format(MultiMesh::COLOR_8BIT);
  1796. mm->set_instance_count(leaf_voxel_count);
  1797. Ref<ArrayMesh> mesh;
  1798. mesh.instance();
  1799. {
  1800. Array arr;
  1801. arr.resize(Mesh::ARRAY_MAX);
  1802. PoolVector<Vector3> vertices;
  1803. PoolVector<Color> colors;
  1804. #define ADD_VTX(m_idx) \
  1805. ; \
  1806. vertices.push_back(face_points[m_idx]); \
  1807. colors.push_back(Color(1, 1, 1, 1));
  1808. for (int i = 0; i < 6; i++) {
  1809. Vector3 face_points[4];
  1810. for (int j = 0; j < 4; j++) {
  1811. float v[3];
  1812. v[0] = 1.0;
  1813. v[1] = 1 - 2 * ((j >> 1) & 1);
  1814. v[2] = v[1] * (1 - 2 * (j & 1));
  1815. for (int k = 0; k < 3; k++) {
  1816. if (i < 3)
  1817. face_points[j][(i + k) % 3] = v[k];
  1818. else
  1819. face_points[3 - j][(i + k) % 3] = -v[k];
  1820. }
  1821. }
  1822. //tri 1
  1823. ADD_VTX(0);
  1824. ADD_VTX(1);
  1825. ADD_VTX(2);
  1826. //tri 2
  1827. ADD_VTX(2);
  1828. ADD_VTX(3);
  1829. ADD_VTX(0);
  1830. }
  1831. arr[Mesh::ARRAY_VERTEX] = vertices;
  1832. arr[Mesh::ARRAY_COLOR] = colors;
  1833. mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  1834. }
  1835. {
  1836. Ref<SpatialMaterial> fsm;
  1837. fsm.instance();
  1838. fsm->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  1839. fsm->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  1840. fsm->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  1841. fsm->set_albedo(Color(1, 1, 1, 1));
  1842. mesh->surface_set_material(0, fsm);
  1843. }
  1844. mm->set_mesh(mesh);
  1845. int idx = 0;
  1846. _debug_mesh(0, 0, po2_bounds, mm, idx, p_mode);
  1847. return mm;
  1848. }
  1849. struct VoxelLightBakerOctree {
  1850. enum {
  1851. CHILD_EMPTY = 0xFFFFFFFF
  1852. };
  1853. uint16_t light[6][3]; //anisotropic light
  1854. float alpha;
  1855. uint32_t children[8];
  1856. };
  1857. PoolVector<uint8_t> VoxelLightBaker::create_capture_octree(int p_subdiv) {
  1858. p_subdiv = MIN(p_subdiv, cell_subdiv); // use the smaller one
  1859. Vector<uint32_t> remap;
  1860. int bc = bake_cells.size();
  1861. remap.resize(bc);
  1862. Vector<uint32_t> demap;
  1863. int new_size = 0;
  1864. for (int i = 0; i < bc; i++) {
  1865. uint32_t c = CHILD_EMPTY;
  1866. if (bake_cells[i].level < p_subdiv) {
  1867. c = new_size;
  1868. new_size++;
  1869. demap.push_back(i);
  1870. }
  1871. remap.write[i] = c;
  1872. }
  1873. Vector<VoxelLightBakerOctree> octree;
  1874. octree.resize(new_size);
  1875. for (int i = 0; i < new_size; i++) {
  1876. octree.write[i].alpha = bake_cells[demap[i]].alpha;
  1877. for (int j = 0; j < 6; j++) {
  1878. for (int k = 0; k < 3; k++) {
  1879. float l = bake_light[demap[i]].accum[j][k]; //add anisotropic light
  1880. l += bake_cells[demap[i]].emission[k]; //add emission
  1881. octree.write[i].light[j][k] = CLAMP(l * 1024, 0, 65535); //give two more bits to octree
  1882. }
  1883. }
  1884. for (int j = 0; j < 8; j++) {
  1885. uint32_t child = bake_cells[demap[i]].children[j];
  1886. octree.write[i].children[j] = child == CHILD_EMPTY ? CHILD_EMPTY : remap[child];
  1887. }
  1888. }
  1889. PoolVector<uint8_t> ret;
  1890. int ret_bytes = octree.size() * sizeof(VoxelLightBakerOctree);
  1891. ret.resize(ret_bytes);
  1892. {
  1893. PoolVector<uint8_t>::Write w = ret.write();
  1894. copymem(w.ptr(), octree.ptr(), ret_bytes);
  1895. }
  1896. return ret;
  1897. }
  1898. float VoxelLightBaker::get_cell_size() const {
  1899. return cell_size;
  1900. }
  1901. Transform VoxelLightBaker::get_to_cell_space_xform() const {
  1902. return to_cell_space;
  1903. }
  1904. VoxelLightBaker::VoxelLightBaker() {
  1905. color_scan_cell_width = 4;
  1906. bake_texture_size = 128;
  1907. propagation = 0.85;
  1908. energy = 1.0;
  1909. }