voxel_light_baker.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. /**************************************************************************/
  2. /* voxel_light_baker.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "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) \
  37. min = x1; \
  38. if (x1 > max) \
  39. max = x1; \
  40. if (x2 < min) \
  41. min = x2; \
  42. if (x2 > max) \
  43. max = x2;
  44. static bool planeBoxOverlap(Vector3 normal, float d, Vector3 maxbox) {
  45. int q;
  46. Vector3 vmin, vmax;
  47. for (q = 0; q <= 2; q++) {
  48. if (normal[q] > 0.0f) {
  49. vmin[q] = -maxbox[q];
  50. vmax[q] = maxbox[q];
  51. } else {
  52. vmin[q] = maxbox[q];
  53. vmax[q] = -maxbox[q];
  54. }
  55. }
  56. if (normal.dot(vmin) + d > 0.0f) {
  57. return false;
  58. }
  59. if (normal.dot(vmax) + d >= 0.0f) {
  60. return true;
  61. }
  62. return false;
  63. }
  64. /*======================== X-tests ========================*/
  65. #define AXISTEST_X01(a, b, fa, fb) \
  66. p0 = a * v0.y - b * v0.z; \
  67. p2 = a * v2.y - b * v2.z; \
  68. if (p0 < p2) { \
  69. min = p0; \
  70. max = p2; \
  71. } else { \
  72. min = p2; \
  73. max = p0; \
  74. } \
  75. rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
  76. if (min > rad || max < -rad) \
  77. return false;
  78. #define AXISTEST_X2(a, b, fa, fb) \
  79. p0 = a * v0.y - b * v0.z; \
  80. p1 = a * v1.y - b * v1.z; \
  81. if (p0 < p1) { \
  82. min = p0; \
  83. max = p1; \
  84. } else { \
  85. min = p1; \
  86. max = p0; \
  87. } \
  88. rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
  89. if (min > rad || max < -rad) \
  90. return false;
  91. /*======================== Y-tests ========================*/
  92. #define AXISTEST_Y02(a, b, fa, fb) \
  93. p0 = -a * v0.x + b * v0.z; \
  94. p2 = -a * v2.x + b * v2.z; \
  95. if (p0 < p2) { \
  96. min = p0; \
  97. max = p2; \
  98. } else { \
  99. min = p2; \
  100. max = p0; \
  101. } \
  102. rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
  103. if (min > rad || max < -rad) \
  104. return false;
  105. #define AXISTEST_Y1(a, b, fa, fb) \
  106. p0 = -a * v0.x + b * v0.z; \
  107. p1 = -a * v1.x + b * v1.z; \
  108. if (p0 < p1) { \
  109. min = p0; \
  110. max = p1; \
  111. } else { \
  112. min = p1; \
  113. max = p0; \
  114. } \
  115. rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
  116. if (min > rad || max < -rad) \
  117. return false;
  118. /*======================== Z-tests ========================*/
  119. #define AXISTEST_Z12(a, b, fa, fb) \
  120. p1 = a * v1.x - b * v1.y; \
  121. p2 = a * v2.x - b * v2.y; \
  122. if (p2 < p1) { \
  123. min = p2; \
  124. max = p1; \
  125. } else { \
  126. min = p1; \
  127. max = p2; \
  128. } \
  129. rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
  130. if (min > rad || max < -rad) \
  131. return false;
  132. #define AXISTEST_Z0(a, b, fa, fb) \
  133. p0 = a * v0.x - b * v0.y; \
  134. p1 = a * v1.x - b * v1.y; \
  135. if (p0 < p1) { \
  136. min = p0; \
  137. max = p1; \
  138. } else { \
  139. min = p1; \
  140. max = p0; \
  141. } \
  142. rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
  143. if (min > rad || max < -rad) \
  144. return false;
  145. static bool fast_tri_box_overlap(const Vector3 &boxcenter, const Vector3 boxhalfsize, const Vector3 *triverts) {
  146. /* use separating axis theorem to test overlap between triangle and box */
  147. /* need to test for overlap in these directions: */
  148. /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
  149. /* we do not even need to test these) */
  150. /* 2) normal of the triangle */
  151. /* 3) crossproduct(edge from tri, {x,y,z}-directin) */
  152. /* this gives 3x3=9 more tests */
  153. Vector3 v0, v1, v2;
  154. float min, max, d, p0, p1, p2, rad, fex, fey, fez;
  155. Vector3 normal, e0, e1, e2;
  156. /* This is the fastest branch on Sun */
  157. /* move everything so that the boxcenter is in (0,0,0) */
  158. v0 = triverts[0] - boxcenter;
  159. v1 = triverts[1] - boxcenter;
  160. v2 = triverts[2] - boxcenter;
  161. /* compute triangle edges */
  162. e0 = v1 - v0; /* tri edge 0 */
  163. e1 = v2 - v1; /* tri edge 1 */
  164. e2 = v0 - v2; /* tri edge 2 */
  165. /* Bullet 3: */
  166. /* test the 9 tests first (this was faster) */
  167. fex = Math::abs(e0.x);
  168. fey = Math::abs(e0.y);
  169. fez = Math::abs(e0.z);
  170. AXISTEST_X01(e0.z, e0.y, fez, fey);
  171. AXISTEST_Y02(e0.z, e0.x, fez, fex);
  172. AXISTEST_Z12(e0.y, e0.x, fey, fex);
  173. fex = Math::abs(e1.x);
  174. fey = Math::abs(e1.y);
  175. fez = Math::abs(e1.z);
  176. AXISTEST_X01(e1.z, e1.y, fez, fey);
  177. AXISTEST_Y02(e1.z, e1.x, fez, fex);
  178. AXISTEST_Z0(e1.y, e1.x, fey, fex);
  179. fex = Math::abs(e2.x);
  180. fey = Math::abs(e2.y);
  181. fez = Math::abs(e2.z);
  182. AXISTEST_X2(e2.z, e2.y, fez, fey);
  183. AXISTEST_Y1(e2.z, e2.x, fez, fex);
  184. AXISTEST_Z12(e2.y, e2.x, fey, fex);
  185. /* Bullet 1: */
  186. /* first test overlap in the {x,y,z}-directions */
  187. /* find min, max of the triangle each direction, and test for overlap in */
  188. /* that direction -- this is equivalent to testing a minimal AABB around */
  189. /* the triangle against the AABB */
  190. /* test in X-direction */
  191. FINDMINMAX(v0.x, v1.x, v2.x, min, max);
  192. if (min > boxhalfsize.x || max < -boxhalfsize.x) {
  193. return false;
  194. }
  195. /* test in Y-direction */
  196. FINDMINMAX(v0.y, v1.y, v2.y, min, max);
  197. if (min > boxhalfsize.y || max < -boxhalfsize.y) {
  198. return false;
  199. }
  200. /* test in Z-direction */
  201. FINDMINMAX(v0.z, v1.z, v2.z, min, max);
  202. if (min > boxhalfsize.z || max < -boxhalfsize.z) {
  203. return false;
  204. }
  205. /* Bullet 2: */
  206. /* test if the box intersects the plane of the triangle */
  207. /* compute plane equation of triangle: normal*x+d=0 */
  208. normal = e0.cross(e1);
  209. d = -normal.dot(v0); /* plane eq: normal.x+d=0 */
  210. return planeBoxOverlap(normal, d, boxhalfsize); /* if true, box and triangle overlaps */
  211. }
  212. 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) {
  213. if (p_pos.distance_squared_to(p_vtx[0]) < CMP_EPSILON2) {
  214. r_uv = p_uv[0];
  215. r_normal = p_normal[0];
  216. return;
  217. }
  218. if (p_pos.distance_squared_to(p_vtx[1]) < CMP_EPSILON2) {
  219. r_uv = p_uv[1];
  220. r_normal = p_normal[1];
  221. return;
  222. }
  223. if (p_pos.distance_squared_to(p_vtx[2]) < CMP_EPSILON2) {
  224. r_uv = p_uv[2];
  225. r_normal = p_normal[2];
  226. return;
  227. }
  228. Vector3 v0 = p_vtx[1] - p_vtx[0];
  229. Vector3 v1 = p_vtx[2] - p_vtx[0];
  230. Vector3 v2 = p_pos - p_vtx[0];
  231. float d00 = v0.dot(v0);
  232. float d01 = v0.dot(v1);
  233. float d11 = v1.dot(v1);
  234. float d20 = v2.dot(v0);
  235. float d21 = v2.dot(v1);
  236. float denom = (d00 * d11 - d01 * d01);
  237. if (denom == 0) {
  238. r_uv = p_uv[0];
  239. r_normal = p_normal[0];
  240. return;
  241. }
  242. float v = (d11 * d20 - d01 * d21) / denom;
  243. float w = (d00 * d21 - d01 * d20) / denom;
  244. float u = 1.0f - v - w;
  245. r_uv = p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
  246. r_normal = (p_normal[0] * u + p_normal[1] * v + p_normal[2] * w).normalized();
  247. }
  248. 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) {
  249. if (p_level == cell_subdiv - 1) {
  250. //plot the face by guessing its albedo and emission value
  251. //find best axis to map to, for scanning values
  252. int closest_axis = 0;
  253. float closest_dot = 0;
  254. Plane plane = Plane(p_vtx[0], p_vtx[1], p_vtx[2]);
  255. Vector3 normal = plane.normal;
  256. for (int i = 0; i < 3; i++) {
  257. Vector3 axis;
  258. axis[i] = 1.0;
  259. float dot = ABS(normal.dot(axis));
  260. if (i == 0 || dot > closest_dot) {
  261. closest_axis = i;
  262. closest_dot = dot;
  263. }
  264. }
  265. Vector3 axis;
  266. axis[closest_axis] = 1.0;
  267. Vector3 t1;
  268. t1[(closest_axis + 1) % 3] = 1.0;
  269. Vector3 t2;
  270. t2[(closest_axis + 2) % 3] = 1.0;
  271. t1 *= p_aabb.size[(closest_axis + 1) % 3] / float(color_scan_cell_width);
  272. t2 *= p_aabb.size[(closest_axis + 2) % 3] / float(color_scan_cell_width);
  273. Color albedo_accum;
  274. Color emission_accum;
  275. Vector3 normal_accum;
  276. float alpha = 0.0;
  277. //map to a grid average in the best axis for this face
  278. for (int i = 0; i < color_scan_cell_width; i++) {
  279. Vector3 ofs_i = float(i) * t1;
  280. for (int j = 0; j < color_scan_cell_width; j++) {
  281. Vector3 ofs_j = float(j) * t2;
  282. Vector3 from = p_aabb.position + ofs_i + ofs_j;
  283. Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis];
  284. Vector3 half = (to - from) * 0.5;
  285. //is in this cell?
  286. if (!fast_tri_box_overlap(from + half, half, p_vtx)) {
  287. continue; //face does not span this cell
  288. }
  289. //go from -size to +size*2 to avoid skipping collisions
  290. Vector3 ray_from = from + (t1 + t2) * 0.5 - axis * p_aabb.size[closest_axis];
  291. Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis] * 2;
  292. if (normal.dot(ray_from - ray_to) < 0) {
  293. SWAP(ray_from, ray_to);
  294. }
  295. Vector3 intersection;
  296. if (!plane.intersects_segment(ray_from, ray_to, &intersection)) {
  297. if (ABS(plane.distance_to(ray_from)) < ABS(plane.distance_to(ray_to))) {
  298. intersection = plane.project(ray_from);
  299. } else {
  300. intersection = plane.project(ray_to);
  301. }
  302. }
  303. intersection = Face3(p_vtx[0], p_vtx[1], p_vtx[2]).get_closest_point_to(intersection);
  304. Vector2 uv;
  305. Vector3 lnormal;
  306. get_uv_and_normal(intersection, p_vtx, p_uv, p_normal, uv, lnormal);
  307. if (lnormal == Vector3()) { //just in case normal as nor provided
  308. lnormal = normal;
  309. }
  310. int uv_x = CLAMP(int(Math::fposmod(uv.x, 1.0f) * bake_texture_size), 0, bake_texture_size - 1);
  311. int uv_y = CLAMP(int(Math::fposmod(uv.y, 1.0f) * bake_texture_size), 0, bake_texture_size - 1);
  312. int ofs = uv_y * bake_texture_size + uv_x;
  313. albedo_accum.r += p_material.albedo[ofs].r;
  314. albedo_accum.g += p_material.albedo[ofs].g;
  315. albedo_accum.b += p_material.albedo[ofs].b;
  316. albedo_accum.a += p_material.albedo[ofs].a;
  317. emission_accum.r += p_material.emission[ofs].r;
  318. emission_accum.g += p_material.emission[ofs].g;
  319. emission_accum.b += p_material.emission[ofs].b;
  320. normal_accum += lnormal;
  321. alpha += 1.0;
  322. }
  323. }
  324. if (alpha == 0) {
  325. //could not in any way get texture information.. so use closest point to center
  326. Face3 f(p_vtx[0], p_vtx[1], p_vtx[2]);
  327. Vector3 inters = f.get_closest_point_to(p_aabb.position + p_aabb.size * 0.5);
  328. Vector3 lnormal;
  329. Vector2 uv;
  330. get_uv_and_normal(inters, p_vtx, p_uv, p_normal, uv, normal);
  331. if (lnormal == Vector3()) { //just in case normal as nor provided
  332. lnormal = normal;
  333. }
  334. int uv_x = CLAMP(Math::fposmod(uv.x, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
  335. int uv_y = CLAMP(Math::fposmod(uv.y, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
  336. int ofs = uv_y * bake_texture_size + uv_x;
  337. alpha = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  338. albedo_accum.r = p_material.albedo[ofs].r * alpha;
  339. albedo_accum.g = p_material.albedo[ofs].g * alpha;
  340. albedo_accum.b = p_material.albedo[ofs].b * alpha;
  341. albedo_accum.a = p_material.albedo[ofs].a * alpha;
  342. emission_accum.r = p_material.emission[ofs].r * alpha;
  343. emission_accum.g = p_material.emission[ofs].g * alpha;
  344. emission_accum.b = p_material.emission[ofs].b * alpha;
  345. normal_accum = lnormal * alpha;
  346. } else {
  347. float accdiv = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  348. alpha *= accdiv;
  349. albedo_accum.r *= accdiv;
  350. albedo_accum.g *= accdiv;
  351. albedo_accum.b *= accdiv;
  352. albedo_accum.a *= accdiv;
  353. emission_accum.r *= accdiv;
  354. emission_accum.g *= accdiv;
  355. emission_accum.b *= accdiv;
  356. normal_accum *= accdiv;
  357. }
  358. //put this temporarily here, corrected in a later step
  359. bake_cells.write[p_idx].albedo[0] += albedo_accum.r;
  360. bake_cells.write[p_idx].albedo[1] += albedo_accum.g;
  361. bake_cells.write[p_idx].albedo[2] += albedo_accum.b;
  362. bake_cells.write[p_idx].emission[0] += emission_accum.r;
  363. bake_cells.write[p_idx].emission[1] += emission_accum.g;
  364. bake_cells.write[p_idx].emission[2] += emission_accum.b;
  365. bake_cells.write[p_idx].normal[0] += normal_accum.x;
  366. bake_cells.write[p_idx].normal[1] += normal_accum.y;
  367. bake_cells.write[p_idx].normal[2] += normal_accum.z;
  368. bake_cells.write[p_idx].alpha += alpha;
  369. } else {
  370. //go down
  371. int half = (1 << (cell_subdiv - 1)) >> (p_level + 1);
  372. for (int i = 0; i < 8; i++) {
  373. AABB aabb = p_aabb;
  374. aabb.size *= 0.5;
  375. int nx = p_x;
  376. int ny = p_y;
  377. int nz = p_z;
  378. if (i & 1) {
  379. aabb.position.x += aabb.size.x;
  380. nx += half;
  381. }
  382. if (i & 2) {
  383. aabb.position.y += aabb.size.y;
  384. ny += half;
  385. }
  386. if (i & 4) {
  387. aabb.position.z += aabb.size.z;
  388. nz += half;
  389. }
  390. //make sure to not plot beyond limits
  391. if (nx < 0 || nx >= axis_cell_size[0] || ny < 0 || ny >= axis_cell_size[1] || nz < 0 || nz >= axis_cell_size[2]) {
  392. continue;
  393. }
  394. {
  395. AABB test_aabb = aabb;
  396. //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time
  397. Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test
  398. if (!fast_tri_box_overlap(test_aabb.position + qsize, qsize, p_vtx)) {
  399. //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
  400. //does not fit in child, go on
  401. continue;
  402. }
  403. }
  404. if (bake_cells[p_idx].children[i] == CHILD_EMPTY) {
  405. //sub cell must be created
  406. uint32_t child_idx = bake_cells.size();
  407. bake_cells.write[p_idx].children[i] = child_idx;
  408. bake_cells.resize(bake_cells.size() + 1);
  409. bake_cells.write[child_idx].level = p_level + 1;
  410. }
  411. _plot_face(bake_cells[p_idx].children[i], p_level + 1, nx, ny, nz, p_vtx, p_normal, p_uv, p_material, aabb);
  412. }
  413. }
  414. }
  415. Vector<Color> VoxelLightBaker::_get_bake_texture(Ref<Image> p_image, const Color &p_color_mul, const Color &p_color_add) {
  416. Vector<Color> ret;
  417. if (p_image.is_null() || p_image->empty()) {
  418. ret.resize(bake_texture_size * bake_texture_size);
  419. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  420. ret.write[i] = p_color_add;
  421. }
  422. return ret;
  423. }
  424. p_image = p_image->duplicate();
  425. if (p_image->is_compressed()) {
  426. p_image->decompress();
  427. }
  428. p_image->convert(Image::FORMAT_RGBA8);
  429. p_image->resize(bake_texture_size, bake_texture_size, Image::INTERPOLATE_CUBIC);
  430. PoolVector<uint8_t>::Read r = p_image->get_data().read();
  431. ret.resize(bake_texture_size * bake_texture_size);
  432. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  433. Color c;
  434. c.r = (r[i * 4 + 0] / 255.0) * p_color_mul.r + p_color_add.r;
  435. c.g = (r[i * 4 + 1] / 255.0) * p_color_mul.g + p_color_add.g;
  436. c.b = (r[i * 4 + 2] / 255.0) * p_color_mul.b + p_color_add.b;
  437. c.a = r[i * 4 + 3] / 255.0;
  438. ret.write[i] = c;
  439. }
  440. return ret;
  441. }
  442. VoxelLightBaker::MaterialCache VoxelLightBaker::_get_material_cache(Ref<Material> p_material) {
  443. //this way of obtaining materials is inaccurate and also does not support some compressed formats very well
  444. Ref<SpatialMaterial> mat = p_material;
  445. Ref<Material> material = mat; //hack for now
  446. if (material_cache.has(material)) {
  447. return material_cache[material];
  448. }
  449. MaterialCache mc;
  450. Ref<Image> empty;
  451. if (mat.is_valid()) {
  452. Ref<Texture> albedo_tex = mat->get_texture(SpatialMaterial::TEXTURE_ALBEDO);
  453. Ref<Image> img_albedo;
  454. if (albedo_tex.is_valid()) {
  455. img_albedo = albedo_tex->get_data();
  456. mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo(), Color(0, 0, 0)); // albedo texture, color is multiplicative
  457. } else {
  458. mc.albedo = _get_bake_texture(img_albedo, Color(1, 1, 1), mat->get_albedo()); // no albedo texture, color is additive
  459. }
  460. if (mat->get_feature(SpatialMaterial::FEATURE_EMISSION)) {
  461. Ref<Texture> emission_tex = mat->get_texture(SpatialMaterial::TEXTURE_EMISSION);
  462. Color emission_col = mat->get_emission();
  463. float emission_energy = mat->get_emission_energy();
  464. Ref<Image> img_emission;
  465. if (emission_tex.is_valid()) {
  466. img_emission = emission_tex->get_data();
  467. }
  468. if (mat->get_emission_operator() == SpatialMaterial::EMISSION_OP_ADD) {
  469. mc.emission = _get_bake_texture(img_emission, Color(1, 1, 1) * emission_energy, emission_col * emission_energy);
  470. } else {
  471. mc.emission = _get_bake_texture(img_emission, emission_col * emission_energy, Color(0, 0, 0));
  472. }
  473. } else {
  474. mc.emission = _get_bake_texture(empty, Color(0, 0, 0), Color(0, 0, 0));
  475. }
  476. } else {
  477. mc.albedo = _get_bake_texture(empty, Color(0, 0, 0), Color(1, 1, 1));
  478. mc.emission = _get_bake_texture(empty, Color(0, 0, 0), Color(0, 0, 0));
  479. }
  480. material_cache[p_material] = mc;
  481. return mc;
  482. }
  483. void VoxelLightBaker::plot_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material>> &p_materials, const Ref<Material> &p_override_material) {
  484. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  485. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  486. continue; //only triangles
  487. }
  488. Ref<Material> src_material;
  489. if (p_override_material.is_valid()) {
  490. src_material = p_override_material;
  491. } else if (i < p_materials.size() && p_materials[i].is_valid()) {
  492. src_material = p_materials[i];
  493. } else {
  494. src_material = p_mesh->surface_get_material(i);
  495. }
  496. MaterialCache material = _get_material_cache(src_material);
  497. Array a = p_mesh->surface_get_arrays(i);
  498. PoolVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  499. PoolVector<Vector3>::Read vr = vertices.read();
  500. PoolVector<Vector2> uv = a[Mesh::ARRAY_TEX_UV];
  501. PoolVector<Vector2>::Read uvr;
  502. PoolVector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
  503. PoolVector<Vector3>::Read nr;
  504. PoolVector<int> index = a[Mesh::ARRAY_INDEX];
  505. bool read_uv = false;
  506. bool read_normals = false;
  507. if (uv.size()) {
  508. uvr = uv.read();
  509. read_uv = true;
  510. }
  511. if (normals.size()) {
  512. read_normals = true;
  513. nr = normals.read();
  514. }
  515. if (index.size()) {
  516. int facecount = index.size() / 3;
  517. PoolVector<int>::Read ir = index.read();
  518. for (int j = 0; j < facecount; j++) {
  519. Vector3 vtxs[3];
  520. Vector2 uvs[3];
  521. Vector3 normal[3];
  522. for (int k = 0; k < 3; k++) {
  523. vtxs[k] = p_xform.xform(vr[ir[j * 3 + k]]);
  524. }
  525. if (read_uv) {
  526. for (int k = 0; k < 3; k++) {
  527. uvs[k] = uvr[ir[j * 3 + k]];
  528. }
  529. }
  530. if (read_normals) {
  531. for (int k = 0; k < 3; k++) {
  532. normal[k] = nr[ir[j * 3 + k]];
  533. }
  534. }
  535. //test against original bounds
  536. if (!fast_tri_box_overlap(original_bounds.position + original_bounds.size * 0.5, original_bounds.size * 0.5, vtxs)) {
  537. continue;
  538. }
  539. //plot
  540. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  541. }
  542. } else {
  543. int facecount = vertices.size() / 3;
  544. for (int j = 0; j < facecount; j++) {
  545. Vector3 vtxs[3];
  546. Vector2 uvs[3];
  547. Vector3 normal[3];
  548. for (int k = 0; k < 3; k++) {
  549. vtxs[k] = p_xform.xform(vr[j * 3 + k]);
  550. }
  551. if (read_uv) {
  552. for (int k = 0; k < 3; k++) {
  553. uvs[k] = uvr[j * 3 + k];
  554. }
  555. }
  556. if (read_normals) {
  557. for (int k = 0; k < 3; k++) {
  558. normal[k] = nr[j * 3 + k];
  559. }
  560. }
  561. //test against original bounds
  562. if (!fast_tri_box_overlap(original_bounds.position + original_bounds.size * 0.5, original_bounds.size * 0.5, vtxs)) {
  563. continue;
  564. }
  565. //plot face
  566. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  567. }
  568. }
  569. }
  570. max_original_cells = bake_cells.size();
  571. }
  572. void VoxelLightBaker::_init_light_plot(int p_idx, int p_level, int p_x, int p_y, int p_z, uint32_t p_parent) {
  573. bake_light.write[p_idx].x = p_x;
  574. bake_light.write[p_idx].y = p_y;
  575. bake_light.write[p_idx].z = p_z;
  576. if (p_level == cell_subdiv - 1) {
  577. bake_light.write[p_idx].next_leaf = first_leaf;
  578. first_leaf = p_idx;
  579. } else {
  580. //go down
  581. int half = (1 << (cell_subdiv - 1)) >> (p_level + 1);
  582. for (int i = 0; i < 8; i++) {
  583. uint32_t child = bake_cells[p_idx].children[i];
  584. if (child == CHILD_EMPTY) {
  585. continue;
  586. }
  587. int nx = p_x;
  588. int ny = p_y;
  589. int nz = p_z;
  590. if (i & 1) {
  591. nx += half;
  592. }
  593. if (i & 2) {
  594. ny += half;
  595. }
  596. if (i & 4) {
  597. nz += half;
  598. }
  599. _init_light_plot(child, p_level + 1, nx, ny, nz, p_idx);
  600. }
  601. }
  602. }
  603. void VoxelLightBaker::begin_bake_light(BakeQuality p_quality, float p_propagation) {
  604. _check_init_light();
  605. propagation = p_propagation;
  606. bake_quality = p_quality;
  607. }
  608. void VoxelLightBaker::_check_init_light() {
  609. if (bake_light.size() == 0) {
  610. direct_lights_baked = false;
  611. leaf_voxel_count = 0;
  612. _fixup_plot(0, 0); //pre fixup, so normal, albedo, emission, etc. work for lighting.
  613. bake_light.resize(bake_cells.size());
  614. //memset(bake_light.ptrw(), 0, bake_light.size() * sizeof(Light));
  615. first_leaf = -1;
  616. _init_light_plot(0, 0, 0, 0, 0, CHILD_EMPTY);
  617. }
  618. }
  619. static float _get_normal_advance(const Vector3 &p_normal) {
  620. Vector3 normal = p_normal;
  621. Vector3 unorm = normal.abs();
  622. if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) {
  623. // x code
  624. unorm = normal.x > 0.0 ? Vector3(1.0, 0.0, 0.0) : Vector3(-1.0, 0.0, 0.0);
  625. } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) {
  626. // y code
  627. unorm = normal.y > 0.0 ? Vector3(0.0, 1.0, 0.0) : Vector3(0.0, -1.0, 0.0);
  628. } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) {
  629. // z code
  630. unorm = normal.z > 0.0 ? Vector3(0.0, 0.0, 1.0) : Vector3(0.0, 0.0, -1.0);
  631. } else {
  632. // oh-no we messed up code
  633. // has to be
  634. unorm = Vector3(1.0, 0.0, 0.0);
  635. }
  636. return 1.0 / normal.dot(unorm);
  637. }
  638. static const Vector3 aniso_normal[6] = {
  639. Vector3(-1, 0, 0),
  640. Vector3(1, 0, 0),
  641. Vector3(0, -1, 0),
  642. Vector3(0, 1, 0),
  643. Vector3(0, 0, -1),
  644. Vector3(0, 0, 1)
  645. };
  646. uint32_t VoxelLightBaker::_find_cell_at_pos(const Cell *cells, int x, int y, int z) {
  647. uint32_t cell = 0;
  648. int ofs_x = 0;
  649. int ofs_y = 0;
  650. int ofs_z = 0;
  651. int size = 1 << (cell_subdiv - 1);
  652. int half = size / 2;
  653. if (x < 0 || x >= size) {
  654. return -1;
  655. }
  656. if (y < 0 || y >= size) {
  657. return -1;
  658. }
  659. if (z < 0 || z >= size) {
  660. return -1;
  661. }
  662. for (int i = 0; i < cell_subdiv - 1; i++) {
  663. const Cell *bc = &cells[cell];
  664. int child = 0;
  665. if (x >= ofs_x + half) {
  666. child |= 1;
  667. ofs_x += half;
  668. }
  669. if (y >= ofs_y + half) {
  670. child |= 2;
  671. ofs_y += half;
  672. }
  673. if (z >= ofs_z + half) {
  674. child |= 4;
  675. ofs_z += half;
  676. }
  677. cell = bc->children[child];
  678. if (cell == CHILD_EMPTY) {
  679. return CHILD_EMPTY;
  680. }
  681. half >>= 1;
  682. }
  683. return cell;
  684. }
  685. void VoxelLightBaker::plot_light_directional(const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_energy, bool p_direct) {
  686. _check_init_light();
  687. float max_len = Vector3(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]).length() * 1.1;
  688. if (p_direct) {
  689. direct_lights_baked = true;
  690. }
  691. Vector3 light_axis = p_direction;
  692. Plane clip[3];
  693. int clip_planes = 0;
  694. Light *light_data = bake_light.ptrw();
  695. const Cell *cells = bake_cells.ptr();
  696. for (int i = 0; i < 3; i++) {
  697. if (Math::is_zero_approx(light_axis[i])) {
  698. continue;
  699. }
  700. clip[clip_planes].normal[i] = 1.0;
  701. if (light_axis[i] < 0) {
  702. clip[clip_planes].d = axis_cell_size[i] + 1;
  703. } else {
  704. clip[clip_planes].d -= 1.0;
  705. }
  706. clip_planes++;
  707. }
  708. float distance_adv = _get_normal_advance(light_axis);
  709. Vector3 light_energy = Vector3(p_color.r, p_color.g, p_color.b) * p_energy * p_indirect_energy;
  710. int idx = first_leaf;
  711. while (idx >= 0) {
  712. Light *light = &light_data[idx];
  713. Vector3 to(light->x + 0.5, light->y + 0.5, light->z + 0.5);
  714. to += -light_axis.sign() * 0.47; //make it more likely to receive a ray
  715. Vector3 from = to - max_len * light_axis;
  716. for (int j = 0; j < clip_planes; j++) {
  717. clip[j].intersects_segment(from, to, &from);
  718. }
  719. float distance = (to - from).length();
  720. distance += distance_adv - Math::fmod(distance, distance_adv); //make it reach the center of the box always
  721. from = to - light_axis * distance;
  722. uint32_t result = 0xFFFFFFFF;
  723. while (distance > -distance_adv) { //use this to avoid precision errors
  724. result = _find_cell_at_pos(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)));
  725. if (result != 0xFFFFFFFF) {
  726. break;
  727. }
  728. from += light_axis * distance_adv;
  729. distance -= distance_adv;
  730. }
  731. if (result == (uint32_t)idx) {
  732. //cell hit itself! hooray!
  733. Vector3 normal(cells[idx].normal[0], cells[idx].normal[1], cells[idx].normal[2]);
  734. if (normal == Vector3()) {
  735. for (int i = 0; i < 6; i++) {
  736. light->accum[i][0] += light_energy.x * cells[idx].albedo[0];
  737. light->accum[i][1] += light_energy.y * cells[idx].albedo[1];
  738. light->accum[i][2] += light_energy.z * cells[idx].albedo[2];
  739. }
  740. } else {
  741. for (int i = 0; i < 6; i++) {
  742. float s = MAX(0.0, aniso_normal[i].dot(-normal));
  743. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * s;
  744. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * s;
  745. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * s;
  746. }
  747. }
  748. if (p_direct) {
  749. for (int i = 0; i < 6; i++) {
  750. float s = MAX(0.0, aniso_normal[i].dot(-light_axis)); //light depending on normal for direct
  751. light->direct_accum[i][0] += light_energy.x * s;
  752. light->direct_accum[i][1] += light_energy.y * s;
  753. light->direct_accum[i][2] += light_energy.z * s;
  754. }
  755. }
  756. }
  757. idx = light_data[idx].next_leaf;
  758. }
  759. }
  760. 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) {
  761. _check_init_light();
  762. if (p_direct) {
  763. direct_lights_baked = true;
  764. }
  765. Plane clip[3];
  766. int clip_planes = 0;
  767. // uint64_t us = OS::get_singleton()->get_ticks_usec();
  768. Vector3 light_pos = to_cell_space.xform(p_pos) + Vector3(0.5, 0.5, 0.5);
  769. //Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized();
  770. float local_radius = to_cell_space.basis.xform(Vector3(0, 0, 1)).length() * p_radius;
  771. Light *light_data = bake_light.ptrw();
  772. const Cell *cells = bake_cells.ptr();
  773. Vector3 light_energy = Vector3(p_color.r, p_color.g, p_color.b) * p_energy * p_indirect_energy;
  774. int idx = first_leaf;
  775. while (idx >= 0) {
  776. Light *light = &light_data[idx];
  777. Vector3 to(light->x + 0.5, light->y + 0.5, light->z + 0.5);
  778. to += (light_pos - to).sign() * 0.47; //make it more likely to receive a ray
  779. Vector3 light_axis = (to - light_pos).normalized();
  780. float distance_adv = _get_normal_advance(light_axis);
  781. Vector3 normal(cells[idx].normal[0], cells[idx].normal[1], cells[idx].normal[2]);
  782. if (normal != Vector3() && normal.dot(-light_axis) < 0.001) {
  783. idx = light_data[idx].next_leaf;
  784. continue;
  785. }
  786. float att = 1.0;
  787. {
  788. float d = light_pos.distance_to(to);
  789. if (d + distance_adv > local_radius) {
  790. idx = light_data[idx].next_leaf;
  791. continue; // too far away
  792. }
  793. float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
  794. att *= powf(1.0 - dt, p_attenutation);
  795. }
  796. clip_planes = 0;
  797. for (int c = 0; c < 3; c++) {
  798. if (Math::is_zero_approx(light_axis[c])) {
  799. continue;
  800. }
  801. clip[clip_planes].normal[c] = 1.0;
  802. if (light_axis[c] < 0) {
  803. clip[clip_planes].d = (1 << (cell_subdiv - 1)) + 1;
  804. } else {
  805. clip[clip_planes].d -= 1.0;
  806. }
  807. clip_planes++;
  808. }
  809. Vector3 from = light_pos;
  810. for (int j = 0; j < clip_planes; j++) {
  811. clip[j].intersects_segment(from, to, &from);
  812. }
  813. float distance = (to - from).length();
  814. distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
  815. from = to - light_axis * distance;
  816. to += (light_pos - to).sign() * 0.47; //make it more likely to receive a ray
  817. uint32_t result = 0xFFFFFFFF;
  818. while (distance > -distance_adv) { //use this to avoid precision errors
  819. result = _find_cell_at_pos(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)));
  820. if (result != 0xFFFFFFFF) {
  821. break;
  822. }
  823. from += light_axis * distance_adv;
  824. distance -= distance_adv;
  825. }
  826. if (result == (uint32_t)idx) {
  827. //cell hit itself! hooray!
  828. if (normal == Vector3()) {
  829. for (int i = 0; i < 6; i++) {
  830. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * att;
  831. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * att;
  832. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * att;
  833. }
  834. } else {
  835. for (int i = 0; i < 6; i++) {
  836. float s = MAX(0.0, aniso_normal[i].dot(-normal));
  837. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * s * att;
  838. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * s * att;
  839. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * s * att;
  840. }
  841. }
  842. if (p_direct) {
  843. for (int i = 0; i < 6; i++) {
  844. float s = MAX(0.0, aniso_normal[i].dot(-light_axis)); //light depending on normal for direct
  845. light->direct_accum[i][0] += light_energy.x * s * att;
  846. light->direct_accum[i][1] += light_energy.y * s * att;
  847. light->direct_accum[i][2] += light_energy.z * s * att;
  848. }
  849. }
  850. }
  851. idx = light_data[idx].next_leaf;
  852. }
  853. }
  854. 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) {
  855. _check_init_light();
  856. if (p_direct) {
  857. direct_lights_baked = true;
  858. }
  859. Plane clip[3];
  860. int clip_planes = 0;
  861. // uint64_t us = OS::get_singleton()->get_ticks_usec();
  862. Vector3 light_pos = to_cell_space.xform(p_pos) + Vector3(0.5, 0.5, 0.5);
  863. Vector3 spot_axis = to_cell_space.basis.xform(p_axis).normalized();
  864. float local_radius = to_cell_space.basis.xform(Vector3(0, 0, 1)).length() * p_radius;
  865. Light *light_data = bake_light.ptrw();
  866. const Cell *cells = bake_cells.ptr();
  867. Vector3 light_energy = Vector3(p_color.r, p_color.g, p_color.b) * p_energy * p_indirect_energy;
  868. int idx = first_leaf;
  869. while (idx >= 0) {
  870. Light *light = &light_data[idx];
  871. Vector3 to(light->x + 0.5, light->y + 0.5, light->z + 0.5);
  872. Vector3 light_axis = (to - light_pos).normalized();
  873. float distance_adv = _get_normal_advance(light_axis);
  874. Vector3 normal(cells[idx].normal[0], cells[idx].normal[1], cells[idx].normal[2]);
  875. if (normal != Vector3() && normal.dot(-light_axis) < 0.001) {
  876. idx = light_data[idx].next_leaf;
  877. continue;
  878. }
  879. float angle = Math::rad2deg(Math::acos(light_axis.dot(-spot_axis)));
  880. if (angle > p_spot_angle) {
  881. idx = light_data[idx].next_leaf;
  882. continue; // too far away
  883. }
  884. float att = Math::pow(1.0f - angle / p_spot_angle, p_spot_attenuation);
  885. {
  886. float d = light_pos.distance_to(to);
  887. if (d + distance_adv > local_radius) {
  888. idx = light_data[idx].next_leaf;
  889. continue; // too far away
  890. }
  891. float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
  892. att *= powf(1.0 - dt, p_attenutation);
  893. }
  894. clip_planes = 0;
  895. for (int c = 0; c < 3; c++) {
  896. if (Math::is_zero_approx(light_axis[c])) {
  897. continue;
  898. }
  899. clip[clip_planes].normal[c] = 1.0;
  900. if (light_axis[c] < 0) {
  901. clip[clip_planes].d = (1 << (cell_subdiv - 1)) + 1;
  902. } else {
  903. clip[clip_planes].d -= 1.0;
  904. }
  905. clip_planes++;
  906. }
  907. Vector3 from = light_pos;
  908. for (int j = 0; j < clip_planes; j++) {
  909. clip[j].intersects_segment(from, to, &from);
  910. }
  911. float distance = (to - from).length();
  912. distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
  913. from = to - light_axis * distance;
  914. uint32_t result = 0xFFFFFFFF;
  915. while (distance > -distance_adv) { //use this to avoid precision errors
  916. result = _find_cell_at_pos(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)));
  917. if (result != 0xFFFFFFFF) {
  918. break;
  919. }
  920. from += light_axis * distance_adv;
  921. distance -= distance_adv;
  922. }
  923. if (result == (uint32_t)idx) {
  924. //cell hit itself! hooray!
  925. if (normal == Vector3()) {
  926. for (int i = 0; i < 6; i++) {
  927. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * att;
  928. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * att;
  929. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * att;
  930. }
  931. } else {
  932. for (int i = 0; i < 6; i++) {
  933. float s = MAX(0.0, aniso_normal[i].dot(-normal));
  934. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * s * att;
  935. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * s * att;
  936. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * s * att;
  937. }
  938. }
  939. if (p_direct) {
  940. for (int i = 0; i < 6; i++) {
  941. float s = MAX(0.0, aniso_normal[i].dot(-light_axis)); //light depending on normal for direct
  942. light->direct_accum[i][0] += light_energy.x * s * att;
  943. light->direct_accum[i][1] += light_energy.y * s * att;
  944. light->direct_accum[i][2] += light_energy.z * s * att;
  945. }
  946. }
  947. }
  948. idx = light_data[idx].next_leaf;
  949. }
  950. }
  951. void VoxelLightBaker::_fixup_plot(int p_idx, int p_level) {
  952. if (p_level == cell_subdiv - 1) {
  953. leaf_voxel_count++;
  954. float alpha = bake_cells[p_idx].alpha;
  955. bake_cells.write[p_idx].albedo[0] /= alpha;
  956. bake_cells.write[p_idx].albedo[1] /= alpha;
  957. bake_cells.write[p_idx].albedo[2] /= alpha;
  958. //transfer emission to light
  959. bake_cells.write[p_idx].emission[0] /= alpha;
  960. bake_cells.write[p_idx].emission[1] /= alpha;
  961. bake_cells.write[p_idx].emission[2] /= alpha;
  962. bake_cells.write[p_idx].normal[0] /= alpha;
  963. bake_cells.write[p_idx].normal[1] /= alpha;
  964. bake_cells.write[p_idx].normal[2] /= alpha;
  965. Vector3 n(bake_cells[p_idx].normal[0], bake_cells[p_idx].normal[1], bake_cells[p_idx].normal[2]);
  966. if (n.length() < 0.01) {
  967. //too much fight over normal, zero it
  968. bake_cells.write[p_idx].normal[0] = 0;
  969. bake_cells.write[p_idx].normal[1] = 0;
  970. bake_cells.write[p_idx].normal[2] = 0;
  971. } else {
  972. n.normalize();
  973. bake_cells.write[p_idx].normal[0] = n.x;
  974. bake_cells.write[p_idx].normal[1] = n.y;
  975. bake_cells.write[p_idx].normal[2] = n.z;
  976. }
  977. bake_cells.write[p_idx].alpha = 1.0;
  978. /*if (bake_light.size()) {
  979. for(int i=0;i<6;i++) {
  980. }
  981. }*/
  982. } else {
  983. //go down
  984. bake_cells.write[p_idx].emission[0] = 0;
  985. bake_cells.write[p_idx].emission[1] = 0;
  986. bake_cells.write[p_idx].emission[2] = 0;
  987. bake_cells.write[p_idx].normal[0] = 0;
  988. bake_cells.write[p_idx].normal[1] = 0;
  989. bake_cells.write[p_idx].normal[2] = 0;
  990. bake_cells.write[p_idx].albedo[0] = 0;
  991. bake_cells.write[p_idx].albedo[1] = 0;
  992. bake_cells.write[p_idx].albedo[2] = 0;
  993. if (bake_light.size()) {
  994. for (int j = 0; j < 6; j++) {
  995. bake_light.write[p_idx].accum[j][0] = 0;
  996. bake_light.write[p_idx].accum[j][1] = 0;
  997. bake_light.write[p_idx].accum[j][2] = 0;
  998. }
  999. }
  1000. float alpha_average = 0;
  1001. int children_found = 0;
  1002. for (int i = 0; i < 8; i++) {
  1003. uint32_t child = bake_cells[p_idx].children[i];
  1004. if (child == CHILD_EMPTY) {
  1005. continue;
  1006. }
  1007. _fixup_plot(child, p_level + 1);
  1008. alpha_average += bake_cells[child].alpha;
  1009. if (bake_light.size() > 0) {
  1010. for (int j = 0; j < 6; j++) {
  1011. bake_light.write[p_idx].accum[j][0] += bake_light[child].accum[j][0];
  1012. bake_light.write[p_idx].accum[j][1] += bake_light[child].accum[j][1];
  1013. bake_light.write[p_idx].accum[j][2] += bake_light[child].accum[j][2];
  1014. }
  1015. bake_cells.write[p_idx].emission[0] += bake_cells[child].emission[0];
  1016. bake_cells.write[p_idx].emission[1] += bake_cells[child].emission[1];
  1017. bake_cells.write[p_idx].emission[2] += bake_cells[child].emission[2];
  1018. }
  1019. children_found++;
  1020. }
  1021. bake_cells.write[p_idx].alpha = alpha_average / 8.0;
  1022. if (bake_light.size() && children_found) {
  1023. float divisor = Math::lerp(8, children_found, propagation);
  1024. for (int j = 0; j < 6; j++) {
  1025. bake_light.write[p_idx].accum[j][0] /= divisor;
  1026. bake_light.write[p_idx].accum[j][1] /= divisor;
  1027. bake_light.write[p_idx].accum[j][2] /= divisor;
  1028. }
  1029. bake_cells.write[p_idx].emission[0] /= divisor;
  1030. bake_cells.write[p_idx].emission[1] /= divisor;
  1031. bake_cells.write[p_idx].emission[2] /= divisor;
  1032. }
  1033. }
  1034. }
  1035. void VoxelLightBaker::begin_bake(int p_subdiv, const AABB &p_bounds) {
  1036. original_bounds = p_bounds;
  1037. cell_subdiv = p_subdiv;
  1038. bake_cells.resize(1);
  1039. material_cache.clear();
  1040. //find out the actual real bounds, power of 2, which gets the highest subdivision
  1041. po2_bounds = p_bounds;
  1042. int longest_axis = po2_bounds.get_longest_axis_index();
  1043. axis_cell_size[longest_axis] = (1 << (cell_subdiv - 1));
  1044. leaf_voxel_count = 0;
  1045. for (int i = 0; i < 3; i++) {
  1046. if (i == longest_axis) {
  1047. continue;
  1048. }
  1049. axis_cell_size[i] = axis_cell_size[longest_axis];
  1050. float axis_size = po2_bounds.size[longest_axis];
  1051. //shrink until fit subdiv
  1052. while (axis_size / 2.0 >= po2_bounds.size[i]) {
  1053. axis_size /= 2.0;
  1054. axis_cell_size[i] >>= 1;
  1055. }
  1056. po2_bounds.size[i] = po2_bounds.size[longest_axis];
  1057. }
  1058. Transform to_bounds;
  1059. to_bounds.basis.scale(Vector3(po2_bounds.size[longest_axis], po2_bounds.size[longest_axis], po2_bounds.size[longest_axis]));
  1060. to_bounds.origin = po2_bounds.position;
  1061. Transform to_grid;
  1062. to_grid.basis.scale(Vector3(axis_cell_size[longest_axis], axis_cell_size[longest_axis], axis_cell_size[longest_axis]));
  1063. to_cell_space = to_grid * to_bounds.affine_inverse();
  1064. cell_size = po2_bounds.size[longest_axis] / axis_cell_size[longest_axis];
  1065. }
  1066. void VoxelLightBaker::end_bake() {
  1067. _fixup_plot(0, 0);
  1068. }
  1069. //create the data for visual server
  1070. PoolVector<int> VoxelLightBaker::create_gi_probe_data() {
  1071. PoolVector<int> data;
  1072. data.resize(16 + (8 + 1 + 1 + 1 + 1) * bake_cells.size()); //4 for header, rest for rest.
  1073. {
  1074. PoolVector<int>::Write w = data.write();
  1075. uint32_t *w32 = (uint32_t *)w.ptr();
  1076. w32[0] = 0; //version
  1077. w32[1] = cell_subdiv; //subdiv
  1078. w32[2] = axis_cell_size[0];
  1079. w32[3] = axis_cell_size[1];
  1080. w32[4] = axis_cell_size[2];
  1081. w32[5] = bake_cells.size();
  1082. w32[6] = leaf_voxel_count;
  1083. int ofs = 16;
  1084. for (int i = 0; i < bake_cells.size(); i++) {
  1085. for (int j = 0; j < 8; j++) {
  1086. w32[ofs++] = bake_cells[i].children[j];
  1087. }
  1088. { //albedo
  1089. uint32_t rgba = uint32_t(CLAMP(bake_cells[i].albedo[0] * 255.0, 0, 255)) << 16;
  1090. rgba |= uint32_t(CLAMP(bake_cells[i].albedo[1] * 255.0, 0, 255)) << 8;
  1091. rgba |= uint32_t(CLAMP(bake_cells[i].albedo[2] * 255.0, 0, 255)) << 0;
  1092. w32[ofs++] = rgba;
  1093. }
  1094. { //emission
  1095. Vector3 e(bake_cells[i].emission[0], bake_cells[i].emission[1], bake_cells[i].emission[2]);
  1096. float l = e.length();
  1097. if (l > 0) {
  1098. e.normalize();
  1099. l = CLAMP(l / 8.0, 0, 1.0);
  1100. }
  1101. uint32_t em = uint32_t(CLAMP(e[0] * 255, 0, 255)) << 24;
  1102. em |= uint32_t(CLAMP(e[1] * 255, 0, 255)) << 16;
  1103. em |= uint32_t(CLAMP(e[2] * 255, 0, 255)) << 8;
  1104. em |= uint32_t(CLAMP(l * 255, 0, 255));
  1105. w32[ofs++] = em;
  1106. }
  1107. //w32[ofs++]=bake_cells[i].used_sides;
  1108. { //normal
  1109. Vector3 n(bake_cells[i].normal[0], bake_cells[i].normal[1], bake_cells[i].normal[2]);
  1110. n = n * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
  1111. uint32_t norm = 0;
  1112. norm |= uint32_t(CLAMP(n.x * 255.0, 0, 255)) << 16;
  1113. norm |= uint32_t(CLAMP(n.y * 255.0, 0, 255)) << 8;
  1114. norm |= uint32_t(CLAMP(n.z * 255.0, 0, 255)) << 0;
  1115. w32[ofs++] = norm;
  1116. }
  1117. {
  1118. uint16_t alpha = MIN(uint32_t(bake_cells[i].alpha * 65535.0), 65535);
  1119. uint16_t level = bake_cells[i].level;
  1120. w32[ofs++] = (uint32_t(level) << 16) | uint32_t(alpha);
  1121. }
  1122. }
  1123. }
  1124. return data;
  1125. }
  1126. void VoxelLightBaker::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx, DebugMode p_mode) {
  1127. if (p_level == cell_subdiv - 1) {
  1128. Vector3 center = p_aabb.position + p_aabb.size * 0.5;
  1129. Transform xform;
  1130. xform.origin = center;
  1131. xform.basis.scale(p_aabb.size * 0.5);
  1132. p_multimesh->set_instance_transform(idx, xform);
  1133. Color col;
  1134. if (p_mode == DEBUG_ALBEDO) {
  1135. col = Color(bake_cells[p_idx].albedo[0], bake_cells[p_idx].albedo[1], bake_cells[p_idx].albedo[2]);
  1136. } else if (p_mode == DEBUG_LIGHT) {
  1137. for (int i = 0; i < 6; i++) {
  1138. col.r += bake_light[p_idx].accum[i][0];
  1139. col.g += bake_light[p_idx].accum[i][1];
  1140. col.b += bake_light[p_idx].accum[i][2];
  1141. col.r += bake_light[p_idx].direct_accum[i][0];
  1142. col.g += bake_light[p_idx].direct_accum[i][1];
  1143. col.b += bake_light[p_idx].direct_accum[i][2];
  1144. }
  1145. }
  1146. //Color col = Color(bake_cells[p_idx].emission[0], bake_cells[p_idx].emission[1], bake_cells[p_idx].emission[2]);
  1147. p_multimesh->set_instance_color(idx, col);
  1148. idx++;
  1149. } else {
  1150. for (int i = 0; i < 8; i++) {
  1151. uint32_t child = bake_cells[p_idx].children[i];
  1152. if (child == CHILD_EMPTY || child >= (uint32_t)max_original_cells) {
  1153. continue;
  1154. }
  1155. AABB aabb = p_aabb;
  1156. aabb.size *= 0.5;
  1157. if (i & 1) {
  1158. aabb.position.x += aabb.size.x;
  1159. }
  1160. if (i & 2) {
  1161. aabb.position.y += aabb.size.y;
  1162. }
  1163. if (i & 4) {
  1164. aabb.position.z += aabb.size.z;
  1165. }
  1166. _debug_mesh(bake_cells[p_idx].children[i], p_level + 1, aabb, p_multimesh, idx, p_mode);
  1167. }
  1168. }
  1169. }
  1170. Ref<MultiMesh> VoxelLightBaker::create_debug_multimesh(DebugMode p_mode) {
  1171. Ref<MultiMesh> mm;
  1172. ERR_FAIL_COND_V(p_mode == DEBUG_LIGHT && bake_light.size() == 0, mm);
  1173. mm.instance();
  1174. mm->set_transform_format(MultiMesh::TRANSFORM_3D);
  1175. mm->set_color_format(MultiMesh::COLOR_8BIT);
  1176. mm->set_instance_count(leaf_voxel_count);
  1177. Ref<ArrayMesh> mesh;
  1178. mesh.instance();
  1179. {
  1180. Array arr;
  1181. arr.resize(Mesh::ARRAY_MAX);
  1182. PoolVector<Vector3> vertices;
  1183. PoolVector<Color> colors;
  1184. #define ADD_VTX(m_idx) \
  1185. ; \
  1186. vertices.push_back(face_points[m_idx]); \
  1187. colors.push_back(Color(1, 1, 1, 1));
  1188. for (int i = 0; i < 6; i++) {
  1189. Vector3 face_points[4];
  1190. for (int j = 0; j < 4; j++) {
  1191. float v[3];
  1192. v[0] = 1.0;
  1193. v[1] = 1 - 2 * ((j >> 1) & 1);
  1194. v[2] = v[1] * (1 - 2 * (j & 1));
  1195. for (int k = 0; k < 3; k++) {
  1196. if (i < 3) {
  1197. face_points[j][(i + k) % 3] = v[k];
  1198. } else {
  1199. face_points[3 - j][(i + k) % 3] = -v[k];
  1200. }
  1201. }
  1202. }
  1203. //tri 1
  1204. ADD_VTX(0);
  1205. ADD_VTX(1);
  1206. ADD_VTX(2);
  1207. //tri 2
  1208. ADD_VTX(2);
  1209. ADD_VTX(3);
  1210. ADD_VTX(0);
  1211. }
  1212. arr[Mesh::ARRAY_VERTEX] = vertices;
  1213. arr[Mesh::ARRAY_COLOR] = colors;
  1214. mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  1215. }
  1216. {
  1217. Ref<SpatialMaterial> fsm;
  1218. fsm.instance();
  1219. fsm->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  1220. fsm->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  1221. fsm->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  1222. fsm->set_albedo(Color(1, 1, 1, 1));
  1223. mesh->surface_set_material(0, fsm);
  1224. }
  1225. mm->set_mesh(mesh);
  1226. int idx = 0;
  1227. _debug_mesh(0, 0, po2_bounds, mm, idx, p_mode);
  1228. return mm;
  1229. }
  1230. struct VoxelLightBakerOctree {
  1231. enum {
  1232. CHILD_EMPTY = 0xFFFFFFFF
  1233. };
  1234. uint16_t light[6][3]; //anisotropic light
  1235. float alpha;
  1236. uint32_t children[8];
  1237. };
  1238. PoolVector<uint8_t> VoxelLightBaker::create_capture_octree(int p_subdiv) {
  1239. p_subdiv = MIN(p_subdiv, cell_subdiv); // use the smaller one
  1240. Vector<uint32_t> remap;
  1241. int bc = bake_cells.size();
  1242. remap.resize(bc);
  1243. Vector<uint32_t> demap;
  1244. int new_size = 0;
  1245. for (int i = 0; i < bc; i++) {
  1246. uint32_t c = CHILD_EMPTY;
  1247. if (bake_cells[i].level < p_subdiv) {
  1248. c = new_size;
  1249. new_size++;
  1250. demap.push_back(i);
  1251. }
  1252. remap.write[i] = c;
  1253. }
  1254. Vector<VoxelLightBakerOctree> octree;
  1255. octree.resize(new_size);
  1256. for (int i = 0; i < new_size; i++) {
  1257. octree.write[i].alpha = bake_cells[demap[i]].alpha;
  1258. for (int j = 0; j < 6; j++) {
  1259. for (int k = 0; k < 3; k++) {
  1260. float l = bake_light[demap[i]].accum[j][k]; //add anisotropic light
  1261. l += bake_cells[demap[i]].emission[k]; //add emission
  1262. octree.write[i].light[j][k] = CLAMP(l * 1024, 0, 65535); //give two more bits to octree
  1263. }
  1264. }
  1265. for (int j = 0; j < 8; j++) {
  1266. uint32_t child = bake_cells[demap[i]].children[j];
  1267. octree.write[i].children[j] = child == CHILD_EMPTY ? CHILD_EMPTY : remap[child];
  1268. }
  1269. }
  1270. PoolVector<uint8_t> ret;
  1271. int ret_bytes = octree.size() * sizeof(VoxelLightBakerOctree);
  1272. ret.resize(ret_bytes);
  1273. {
  1274. PoolVector<uint8_t>::Write w = ret.write();
  1275. memcpy(w.ptr(), octree.ptr(), ret_bytes);
  1276. }
  1277. return ret;
  1278. }
  1279. float VoxelLightBaker::get_cell_size() const {
  1280. return cell_size;
  1281. }
  1282. Transform VoxelLightBaker::get_to_cell_space_xform() const {
  1283. return to_cell_space;
  1284. }
  1285. VoxelLightBaker::VoxelLightBaker() {
  1286. color_scan_cell_width = 4;
  1287. bake_texture_size = 128;
  1288. propagation = 0.85;
  1289. }