voxelizer.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. /*************************************************************************/
  2. /* voxelizer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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 "voxelizer.h"
  31. 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) {
  32. if (p_pos.is_equal_approx(p_vtx[0])) {
  33. r_uv = p_uv[0];
  34. r_normal = p_normal[0];
  35. return;
  36. }
  37. if (p_pos.is_equal_approx(p_vtx[1])) {
  38. r_uv = p_uv[1];
  39. r_normal = p_normal[1];
  40. return;
  41. }
  42. if (p_pos.is_equal_approx(p_vtx[2])) {
  43. r_uv = p_uv[2];
  44. r_normal = p_normal[2];
  45. return;
  46. }
  47. Vector3 v0 = p_vtx[1] - p_vtx[0];
  48. Vector3 v1 = p_vtx[2] - p_vtx[0];
  49. Vector3 v2 = p_pos - p_vtx[0];
  50. real_t d00 = v0.dot(v0);
  51. real_t d01 = v0.dot(v1);
  52. real_t d11 = v1.dot(v1);
  53. real_t d20 = v2.dot(v0);
  54. real_t d21 = v2.dot(v1);
  55. real_t denom = (d00 * d11 - d01 * d01);
  56. if (denom == 0) {
  57. r_uv = p_uv[0];
  58. r_normal = p_normal[0];
  59. return;
  60. }
  61. real_t v = (d11 * d20 - d01 * d21) / denom;
  62. real_t w = (d00 * d21 - d01 * d20) / denom;
  63. real_t u = 1.0f - v - w;
  64. r_uv = p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
  65. r_normal = (p_normal[0] * u + p_normal[1] * v + p_normal[2] * w).normalized();
  66. }
  67. void Voxelizer::_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) {
  68. if (p_level == cell_subdiv) {
  69. //plot the face by guessing its albedo and emission value
  70. //find best axis to map to, for scanning values
  71. int closest_axis = 0;
  72. real_t closest_dot = 0;
  73. Plane plane = Plane(p_vtx[0], p_vtx[1], p_vtx[2]);
  74. Vector3 normal = plane.normal;
  75. for (int i = 0; i < 3; i++) {
  76. Vector3 axis;
  77. axis[i] = 1.0;
  78. real_t dot = ABS(normal.dot(axis));
  79. if (i == 0 || dot > closest_dot) {
  80. closest_axis = i;
  81. closest_dot = dot;
  82. }
  83. }
  84. Vector3 axis;
  85. axis[closest_axis] = 1.0;
  86. Vector3 t1;
  87. t1[(closest_axis + 1) % 3] = 1.0;
  88. Vector3 t2;
  89. t2[(closest_axis + 2) % 3] = 1.0;
  90. t1 *= p_aabb.size[(closest_axis + 1) % 3] / real_t(color_scan_cell_width);
  91. t2 *= p_aabb.size[(closest_axis + 2) % 3] / real_t(color_scan_cell_width);
  92. Color albedo_accum;
  93. Color emission_accum;
  94. Vector3 normal_accum;
  95. float alpha = 0.0;
  96. //map to a grid average in the best axis for this face
  97. for (int i = 0; i < color_scan_cell_width; i++) {
  98. Vector3 ofs_i = real_t(i) * t1;
  99. for (int j = 0; j < color_scan_cell_width; j++) {
  100. Vector3 ofs_j = real_t(j) * t2;
  101. Vector3 from = p_aabb.position + ofs_i + ofs_j;
  102. Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis];
  103. Vector3 half = (to - from) * 0.5;
  104. //is in this cell?
  105. if (!Geometry3D::triangle_box_overlap(from + half, half, p_vtx)) {
  106. continue; //face does not span this cell
  107. }
  108. //go from -size to +size*2 to avoid skipping collisions
  109. Vector3 ray_from = from + (t1 + t2) * 0.5 - axis * p_aabb.size[closest_axis];
  110. Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis] * 2;
  111. if (normal.dot(ray_from - ray_to) < 0) {
  112. SWAP(ray_from, ray_to);
  113. }
  114. Vector3 intersection;
  115. if (!plane.intersects_segment(ray_from, ray_to, &intersection)) {
  116. if (ABS(plane.distance_to(ray_from)) < ABS(plane.distance_to(ray_to))) {
  117. intersection = plane.project(ray_from);
  118. } else {
  119. intersection = plane.project(ray_to);
  120. }
  121. }
  122. intersection = Face3(p_vtx[0], p_vtx[1], p_vtx[2]).get_closest_point_to(intersection);
  123. Vector2 uv;
  124. Vector3 lnormal;
  125. get_uv_and_normal(intersection, p_vtx, p_uv, p_normal, uv, lnormal);
  126. if (lnormal == Vector3()) { //just in case normal is not provided
  127. lnormal = normal;
  128. }
  129. int uv_x = CLAMP(int(Math::fposmod(uv.x, (real_t)1.0) * bake_texture_size), 0, bake_texture_size - 1);
  130. int uv_y = CLAMP(int(Math::fposmod(uv.y, (real_t)1.0) * bake_texture_size), 0, bake_texture_size - 1);
  131. int ofs = uv_y * bake_texture_size + uv_x;
  132. albedo_accum.r += p_material.albedo[ofs].r;
  133. albedo_accum.g += p_material.albedo[ofs].g;
  134. albedo_accum.b += p_material.albedo[ofs].b;
  135. albedo_accum.a += p_material.albedo[ofs].a;
  136. emission_accum.r += p_material.emission[ofs].r;
  137. emission_accum.g += p_material.emission[ofs].g;
  138. emission_accum.b += p_material.emission[ofs].b;
  139. normal_accum += lnormal;
  140. alpha += 1.0;
  141. }
  142. }
  143. if (alpha == 0) {
  144. //could not in any way get texture information.. so use closest point to center
  145. Face3 f(p_vtx[0], p_vtx[1], p_vtx[2]);
  146. Vector3 inters = f.get_closest_point_to(p_aabb.get_center());
  147. Vector3 lnormal;
  148. Vector2 uv;
  149. get_uv_and_normal(inters, p_vtx, p_uv, p_normal, uv, normal);
  150. if (lnormal == Vector3()) { //just in case normal is not provided
  151. lnormal = normal;
  152. }
  153. int uv_x = CLAMP(Math::fposmod(uv.x, (real_t)1.0) * bake_texture_size, 0, bake_texture_size - 1);
  154. int uv_y = CLAMP(Math::fposmod(uv.y, (real_t)1.0) * bake_texture_size, 0, bake_texture_size - 1);
  155. int ofs = uv_y * bake_texture_size + uv_x;
  156. alpha = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  157. albedo_accum.r = p_material.albedo[ofs].r * alpha;
  158. albedo_accum.g = p_material.albedo[ofs].g * alpha;
  159. albedo_accum.b = p_material.albedo[ofs].b * alpha;
  160. albedo_accum.a = p_material.albedo[ofs].a * alpha;
  161. emission_accum.r = p_material.emission[ofs].r * alpha;
  162. emission_accum.g = p_material.emission[ofs].g * alpha;
  163. emission_accum.b = p_material.emission[ofs].b * alpha;
  164. normal_accum = lnormal * alpha;
  165. } else {
  166. float accdiv = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  167. alpha *= accdiv;
  168. albedo_accum.r *= accdiv;
  169. albedo_accum.g *= accdiv;
  170. albedo_accum.b *= accdiv;
  171. albedo_accum.a *= accdiv;
  172. emission_accum.r *= accdiv;
  173. emission_accum.g *= accdiv;
  174. emission_accum.b *= accdiv;
  175. normal_accum *= accdiv;
  176. }
  177. //put this temporarily here, corrected in a later step
  178. bake_cells.write[p_idx].albedo[0] += albedo_accum.r;
  179. bake_cells.write[p_idx].albedo[1] += albedo_accum.g;
  180. bake_cells.write[p_idx].albedo[2] += albedo_accum.b;
  181. bake_cells.write[p_idx].emission[0] += emission_accum.r;
  182. bake_cells.write[p_idx].emission[1] += emission_accum.g;
  183. bake_cells.write[p_idx].emission[2] += emission_accum.b;
  184. bake_cells.write[p_idx].normal[0] += normal_accum.x;
  185. bake_cells.write[p_idx].normal[1] += normal_accum.y;
  186. bake_cells.write[p_idx].normal[2] += normal_accum.z;
  187. bake_cells.write[p_idx].alpha += alpha;
  188. } else {
  189. //go down
  190. int half = (1 << cell_subdiv) >> (p_level + 1);
  191. for (int i = 0; i < 8; i++) {
  192. AABB aabb = p_aabb;
  193. aabb.size *= 0.5;
  194. int nx = p_x;
  195. int ny = p_y;
  196. int nz = p_z;
  197. if (i & 1) {
  198. aabb.position.x += aabb.size.x;
  199. nx += half;
  200. }
  201. if (i & 2) {
  202. aabb.position.y += aabb.size.y;
  203. ny += half;
  204. }
  205. if (i & 4) {
  206. aabb.position.z += aabb.size.z;
  207. nz += half;
  208. }
  209. //make sure to not plot beyond limits
  210. if (nx < 0 || nx >= axis_cell_size[0] || ny < 0 || ny >= axis_cell_size[1] || nz < 0 || nz >= axis_cell_size[2]) {
  211. continue;
  212. }
  213. {
  214. AABB test_aabb = aabb;
  215. //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time
  216. Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test
  217. if (!Geometry3D::triangle_box_overlap(test_aabb.position + qsize, qsize, p_vtx)) {
  218. //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
  219. //does not fit in child, go on
  220. continue;
  221. }
  222. }
  223. if (bake_cells[p_idx].children[i] == CHILD_EMPTY) {
  224. //sub cell must be created
  225. uint32_t child_idx = bake_cells.size();
  226. bake_cells.write[p_idx].children[i] = child_idx;
  227. bake_cells.resize(bake_cells.size() + 1);
  228. bake_cells.write[child_idx].level = p_level + 1;
  229. bake_cells.write[child_idx].x = nx / half;
  230. bake_cells.write[child_idx].y = ny / half;
  231. bake_cells.write[child_idx].z = nz / half;
  232. }
  233. _plot_face(bake_cells[p_idx].children[i], p_level + 1, nx, ny, nz, p_vtx, p_normal, p_uv, p_material, aabb);
  234. }
  235. }
  236. }
  237. Vector<Color> Voxelizer::_get_bake_texture(Ref<Image> p_image, const Color &p_color_mul, const Color &p_color_add) {
  238. Vector<Color> ret;
  239. if (p_image.is_null() || p_image->is_empty()) {
  240. ret.resize(bake_texture_size * bake_texture_size);
  241. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  242. ret.write[i] = p_color_add;
  243. }
  244. return ret;
  245. }
  246. p_image = p_image->duplicate();
  247. if (p_image->is_compressed()) {
  248. p_image->decompress();
  249. }
  250. p_image->convert(Image::FORMAT_RGBA8);
  251. p_image->resize(bake_texture_size, bake_texture_size, Image::INTERPOLATE_CUBIC);
  252. const uint8_t *r = p_image->get_data().ptr();
  253. ret.resize(bake_texture_size * bake_texture_size);
  254. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  255. Color c;
  256. c.r = (r[i * 4 + 0] / 255.0) * p_color_mul.r + p_color_add.r;
  257. c.g = (r[i * 4 + 1] / 255.0) * p_color_mul.g + p_color_add.g;
  258. c.b = (r[i * 4 + 2] / 255.0) * p_color_mul.b + p_color_add.b;
  259. c.a = r[i * 4 + 3] / 255.0;
  260. ret.write[i] = c;
  261. }
  262. return ret;
  263. }
  264. Voxelizer::MaterialCache Voxelizer::_get_material_cache(Ref<Material> p_material) {
  265. //this way of obtaining materials is inaccurate and also does not support some compressed formats very well
  266. Ref<StandardMaterial3D> mat = p_material;
  267. Ref<Material> material = mat; //hack for now
  268. if (material_cache.has(material)) {
  269. return material_cache[material];
  270. }
  271. MaterialCache mc;
  272. if (mat.is_valid()) {
  273. Ref<Texture2D> albedo_tex = mat->get_texture(StandardMaterial3D::TEXTURE_ALBEDO);
  274. Ref<Image> img_albedo;
  275. if (albedo_tex.is_valid()) {
  276. img_albedo = albedo_tex->get_image();
  277. mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo(), Color(0, 0, 0)); // albedo texture, color is multiplicative
  278. } else {
  279. mc.albedo = _get_bake_texture(img_albedo, Color(1, 1, 1), mat->get_albedo()); // no albedo texture, color is additive
  280. }
  281. Ref<Texture2D> emission_tex = mat->get_texture(StandardMaterial3D::TEXTURE_EMISSION);
  282. Color emission_col = mat->get_emission();
  283. float emission_energy = mat->get_emission_energy();
  284. Ref<Image> img_emission;
  285. if (emission_tex.is_valid()) {
  286. img_emission = emission_tex->get_image();
  287. }
  288. if (mat->get_emission_operator() == StandardMaterial3D::EMISSION_OP_ADD) {
  289. mc.emission = _get_bake_texture(img_emission, Color(1, 1, 1) * emission_energy, emission_col * emission_energy);
  290. } else {
  291. mc.emission = _get_bake_texture(img_emission, emission_col * emission_energy, Color(0, 0, 0));
  292. }
  293. } else {
  294. Ref<Image> empty;
  295. mc.albedo = _get_bake_texture(empty, Color(0, 0, 0), Color(1, 1, 1));
  296. mc.emission = _get_bake_texture(empty, Color(0, 0, 0), Color(0, 0, 0));
  297. }
  298. material_cache[p_material] = mc;
  299. return mc;
  300. }
  301. void Voxelizer::plot_mesh(const Transform3D &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material>> &p_materials, const Ref<Material> &p_override_material) {
  302. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  303. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  304. continue; //only triangles
  305. }
  306. Ref<Material> src_material;
  307. if (p_override_material.is_valid()) {
  308. src_material = p_override_material;
  309. } else if (i < p_materials.size() && p_materials[i].is_valid()) {
  310. src_material = p_materials[i];
  311. } else {
  312. src_material = p_mesh->surface_get_material(i);
  313. }
  314. MaterialCache material = _get_material_cache(src_material);
  315. Array a = p_mesh->surface_get_arrays(i);
  316. Vector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  317. const Vector3 *vr = vertices.ptr();
  318. Vector<Vector2> uv = a[Mesh::ARRAY_TEX_UV];
  319. const Vector2 *uvr = nullptr;
  320. Vector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
  321. const Vector3 *nr = nullptr;
  322. Vector<int> index = a[Mesh::ARRAY_INDEX];
  323. if (uv.size()) {
  324. uvr = uv.ptr();
  325. }
  326. if (normals.size()) {
  327. nr = normals.ptr();
  328. }
  329. if (index.size()) {
  330. int facecount = index.size() / 3;
  331. const int *ir = index.ptr();
  332. for (int j = 0; j < facecount; j++) {
  333. Vector3 vtxs[3];
  334. Vector2 uvs[3];
  335. Vector3 normal[3];
  336. for (int k = 0; k < 3; k++) {
  337. vtxs[k] = p_xform.xform(vr[ir[j * 3 + k]]);
  338. }
  339. if (uvr) {
  340. for (int k = 0; k < 3; k++) {
  341. uvs[k] = uvr[ir[j * 3 + k]];
  342. }
  343. }
  344. if (nr) {
  345. for (int k = 0; k < 3; k++) {
  346. normal[k] = nr[ir[j * 3 + k]];
  347. }
  348. }
  349. //test against original bounds
  350. if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
  351. continue;
  352. }
  353. //plot
  354. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  355. }
  356. } else {
  357. int facecount = vertices.size() / 3;
  358. for (int j = 0; j < facecount; j++) {
  359. Vector3 vtxs[3];
  360. Vector2 uvs[3];
  361. Vector3 normal[3];
  362. for (int k = 0; k < 3; k++) {
  363. vtxs[k] = p_xform.xform(vr[j * 3 + k]);
  364. }
  365. if (uvr) {
  366. for (int k = 0; k < 3; k++) {
  367. uvs[k] = uvr[j * 3 + k];
  368. }
  369. }
  370. if (nr) {
  371. for (int k = 0; k < 3; k++) {
  372. normal[k] = nr[j * 3 + k];
  373. }
  374. }
  375. //test against original bounds
  376. if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
  377. continue;
  378. }
  379. //plot face
  380. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  381. }
  382. }
  383. }
  384. max_original_cells = bake_cells.size();
  385. }
  386. void Voxelizer::_sort() {
  387. // cells need to be sorted by level and coordinates
  388. // it is important that level has more priority (for compute), and that Z has the least,
  389. // given it may aid older implementations plot using GPU
  390. Vector<CellSort> sorted_cells;
  391. uint32_t cell_count = bake_cells.size();
  392. sorted_cells.resize(cell_count);
  393. {
  394. CellSort *sort_cellsp = sorted_cells.ptrw();
  395. const Cell *bake_cellsp = bake_cells.ptr();
  396. for (uint32_t i = 0; i < cell_count; i++) {
  397. sort_cellsp[i].x = bake_cellsp[i].x;
  398. sort_cellsp[i].y = bake_cellsp[i].y;
  399. sort_cellsp[i].z = bake_cellsp[i].z;
  400. sort_cellsp[i].level = bake_cellsp[i].level;
  401. sort_cellsp[i].index = i;
  402. }
  403. }
  404. sorted_cells.sort();
  405. //verify just in case, index 0 must be level 0
  406. ERR_FAIL_COND(sorted_cells[0].level != 0);
  407. Vector<Cell> new_bake_cells;
  408. new_bake_cells.resize(cell_count);
  409. Vector<uint32_t> reverse_map;
  410. {
  411. reverse_map.resize(cell_count);
  412. const CellSort *sort_cellsp = sorted_cells.ptr();
  413. uint32_t *reverse_mapp = reverse_map.ptrw();
  414. for (uint32_t i = 0; i < cell_count; i++) {
  415. reverse_mapp[sort_cellsp[i].index] = i;
  416. }
  417. }
  418. {
  419. const CellSort *sort_cellsp = sorted_cells.ptr();
  420. const Cell *bake_cellsp = bake_cells.ptr();
  421. const uint32_t *reverse_mapp = reverse_map.ptr();
  422. Cell *new_bake_cellsp = new_bake_cells.ptrw();
  423. for (uint32_t i = 0; i < cell_count; i++) {
  424. //copy to new cell
  425. new_bake_cellsp[i] = bake_cellsp[sort_cellsp[i].index];
  426. //remap children
  427. for (uint32_t j = 0; j < 8; j++) {
  428. if (new_bake_cellsp[i].children[j] != CHILD_EMPTY) {
  429. new_bake_cellsp[i].children[j] = reverse_mapp[new_bake_cellsp[i].children[j]];
  430. }
  431. }
  432. }
  433. }
  434. bake_cells = new_bake_cells;
  435. sorted = true;
  436. }
  437. void Voxelizer::_fixup_plot(int p_idx, int p_level) {
  438. if (p_level == cell_subdiv) {
  439. leaf_voxel_count++;
  440. float alpha = bake_cells[p_idx].alpha;
  441. bake_cells.write[p_idx].albedo[0] /= alpha;
  442. bake_cells.write[p_idx].albedo[1] /= alpha;
  443. bake_cells.write[p_idx].albedo[2] /= alpha;
  444. //transfer emission to light
  445. bake_cells.write[p_idx].emission[0] /= alpha;
  446. bake_cells.write[p_idx].emission[1] /= alpha;
  447. bake_cells.write[p_idx].emission[2] /= alpha;
  448. bake_cells.write[p_idx].normal[0] /= alpha;
  449. bake_cells.write[p_idx].normal[1] /= alpha;
  450. bake_cells.write[p_idx].normal[2] /= alpha;
  451. Vector3 n(bake_cells[p_idx].normal[0], bake_cells[p_idx].normal[1], bake_cells[p_idx].normal[2]);
  452. if (n.length() < 0.01) {
  453. //too much fight over normal, zero it
  454. bake_cells.write[p_idx].normal[0] = 0;
  455. bake_cells.write[p_idx].normal[1] = 0;
  456. bake_cells.write[p_idx].normal[2] = 0;
  457. } else {
  458. n.normalize();
  459. bake_cells.write[p_idx].normal[0] = n.x;
  460. bake_cells.write[p_idx].normal[1] = n.y;
  461. bake_cells.write[p_idx].normal[2] = n.z;
  462. }
  463. bake_cells.write[p_idx].alpha = 1.0;
  464. /*if (bake_light.size()) {
  465. for(int i=0;i<6;i++) {
  466. }
  467. }*/
  468. } else {
  469. //go down
  470. bake_cells.write[p_idx].emission[0] = 0;
  471. bake_cells.write[p_idx].emission[1] = 0;
  472. bake_cells.write[p_idx].emission[2] = 0;
  473. bake_cells.write[p_idx].normal[0] = 0;
  474. bake_cells.write[p_idx].normal[1] = 0;
  475. bake_cells.write[p_idx].normal[2] = 0;
  476. bake_cells.write[p_idx].albedo[0] = 0;
  477. bake_cells.write[p_idx].albedo[1] = 0;
  478. bake_cells.write[p_idx].albedo[2] = 0;
  479. float alpha_average = 0;
  480. for (int i = 0; i < 8; i++) {
  481. uint32_t child = bake_cells[p_idx].children[i];
  482. if (child == CHILD_EMPTY) {
  483. continue;
  484. }
  485. _fixup_plot(child, p_level + 1);
  486. alpha_average += bake_cells[child].alpha;
  487. }
  488. bake_cells.write[p_idx].alpha = alpha_average / 8.0;
  489. }
  490. }
  491. void Voxelizer::begin_bake(int p_subdiv, const AABB &p_bounds) {
  492. sorted = false;
  493. original_bounds = p_bounds;
  494. cell_subdiv = p_subdiv;
  495. bake_cells.resize(1);
  496. material_cache.clear();
  497. //find out the actual real bounds, power of 2, which gets the highest subdivision
  498. po2_bounds = p_bounds;
  499. int longest_axis = po2_bounds.get_longest_axis_index();
  500. axis_cell_size[longest_axis] = 1 << cell_subdiv;
  501. leaf_voxel_count = 0;
  502. for (int i = 0; i < 3; i++) {
  503. if (i == longest_axis) {
  504. continue;
  505. }
  506. axis_cell_size[i] = axis_cell_size[longest_axis];
  507. real_t axis_size = po2_bounds.size[longest_axis];
  508. //shrink until fit subdiv
  509. while (axis_size / 2.0 >= po2_bounds.size[i]) {
  510. axis_size /= 2.0;
  511. axis_cell_size[i] >>= 1;
  512. }
  513. po2_bounds.size[i] = po2_bounds.size[longest_axis];
  514. }
  515. Transform3D to_bounds;
  516. to_bounds.basis.scale(Vector3(po2_bounds.size[longest_axis], po2_bounds.size[longest_axis], po2_bounds.size[longest_axis]));
  517. to_bounds.origin = po2_bounds.position;
  518. Transform3D to_grid;
  519. to_grid.basis.scale(Vector3(axis_cell_size[longest_axis], axis_cell_size[longest_axis], axis_cell_size[longest_axis]));
  520. to_cell_space = to_grid * to_bounds.affine_inverse();
  521. cell_size = po2_bounds.size[longest_axis] / axis_cell_size[longest_axis];
  522. }
  523. void Voxelizer::end_bake() {
  524. if (!sorted) {
  525. _sort();
  526. }
  527. _fixup_plot(0, 0);
  528. }
  529. //create the data for rendering server
  530. int Voxelizer::get_voxel_gi_octree_depth() const {
  531. return cell_subdiv;
  532. }
  533. Vector3i Voxelizer::get_voxel_gi_octree_size() const {
  534. return Vector3i(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]);
  535. }
  536. int Voxelizer::get_voxel_gi_cell_count() const {
  537. return bake_cells.size();
  538. }
  539. Vector<uint8_t> Voxelizer::get_voxel_gi_octree_cells() const {
  540. Vector<uint8_t> data;
  541. data.resize((8 * 4) * bake_cells.size()); //8 uint32t values
  542. {
  543. uint8_t *w = data.ptrw();
  544. uint32_t *children_cells = (uint32_t *)w;
  545. const Cell *cells = bake_cells.ptr();
  546. uint32_t cell_count = bake_cells.size();
  547. for (uint32_t i = 0; i < cell_count; i++) {
  548. for (uint32_t j = 0; j < 8; j++) {
  549. children_cells[i * 8 + j] = cells[i].children[j];
  550. }
  551. }
  552. }
  553. return data;
  554. }
  555. Vector<uint8_t> Voxelizer::get_voxel_gi_data_cells() const {
  556. Vector<uint8_t> data;
  557. data.resize((4 * 4) * bake_cells.size()); //8 uint32t values
  558. {
  559. uint8_t *w = data.ptrw();
  560. uint32_t *dataptr = (uint32_t *)w;
  561. const Cell *cells = bake_cells.ptr();
  562. uint32_t cell_count = bake_cells.size();
  563. for (uint32_t i = 0; i < cell_count; i++) {
  564. { //position
  565. uint32_t x = cells[i].x;
  566. uint32_t y = cells[i].y;
  567. uint32_t z = cells[i].z;
  568. uint32_t position = x;
  569. position |= y << 11;
  570. position |= z << 21;
  571. dataptr[i * 4 + 0] = position;
  572. }
  573. { //albedo + alpha
  574. uint32_t rgba = uint32_t(CLAMP(cells[i].alpha * 255.0, 0, 255)) << 24; //a
  575. rgba |= uint32_t(CLAMP(cells[i].albedo[2] * 255.0, 0, 255)) << 16; //b
  576. rgba |= uint32_t(CLAMP(cells[i].albedo[1] * 255.0, 0, 255)) << 8; //g
  577. rgba |= uint32_t(CLAMP(cells[i].albedo[0] * 255.0, 0, 255)); //r
  578. dataptr[i * 4 + 1] = rgba;
  579. }
  580. { //emission, as rgbe9995
  581. Color emission = Color(cells[i].emission[0], cells[i].emission[1], cells[i].emission[2]);
  582. dataptr[i * 4 + 2] = emission.to_rgbe9995();
  583. }
  584. { //normal
  585. Vector3 n(bake_cells[i].normal[0], bake_cells[i].normal[1], bake_cells[i].normal[2]);
  586. n.normalize();
  587. uint32_t normal = uint32_t(uint8_t(int8_t(CLAMP(n.x * 127.0, -128, 127))));
  588. normal |= uint32_t(uint8_t(int8_t(CLAMP(n.y * 127.0, -128, 127)))) << 8;
  589. normal |= uint32_t(uint8_t(int8_t(CLAMP(n.z * 127.0, -128, 127)))) << 16;
  590. dataptr[i * 4 + 3] = normal;
  591. }
  592. }
  593. }
  594. return data;
  595. }
  596. Vector<int> Voxelizer::get_voxel_gi_level_cell_count() const {
  597. uint32_t cell_count = bake_cells.size();
  598. const Cell *cells = bake_cells.ptr();
  599. Vector<int> level_count;
  600. level_count.resize(cell_subdiv + 1); //remember, always x+1 levels for x subdivisions
  601. {
  602. int *w = level_count.ptrw();
  603. for (int i = 0; i < cell_subdiv + 1; i++) {
  604. w[i] = 0;
  605. }
  606. for (uint32_t i = 0; i < cell_count; i++) {
  607. w[cells[i].level]++;
  608. }
  609. }
  610. return level_count;
  611. }
  612. // euclidean distance computation based on:
  613. // https://prideout.net/blog/distance_fields/
  614. #define square(m_s) ((m_s) * (m_s))
  615. #define INF 1e20
  616. /* dt of 1d function using squared distance */
  617. static void edt(float *f, int stride, int n) {
  618. float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
  619. int *v = reinterpret_cast<int *>(&(d[n]));
  620. float *z = reinterpret_cast<float *>(&v[n]);
  621. int k = 0;
  622. v[0] = 0;
  623. z[0] = -INF;
  624. z[1] = +INF;
  625. for (int q = 1; q <= n - 1; q++) {
  626. float s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  627. while (s <= z[k]) {
  628. k--;
  629. s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  630. }
  631. k++;
  632. v[k] = q;
  633. z[k] = s;
  634. z[k + 1] = +INF;
  635. }
  636. k = 0;
  637. for (int q = 0; q <= n - 1; q++) {
  638. while (z[k + 1] < q) {
  639. k++;
  640. }
  641. d[q] = square(q - v[k]) + f[v[k] * stride];
  642. }
  643. for (int i = 0; i < n; i++) {
  644. f[i * stride] = d[i];
  645. }
  646. }
  647. #undef square
  648. Vector<uint8_t> Voxelizer::get_sdf_3d_image() const {
  649. Vector3i octree_size = get_voxel_gi_octree_size();
  650. uint32_t float_count = octree_size.x * octree_size.y * octree_size.z;
  651. float *work_memory = memnew_arr(float, float_count);
  652. for (uint32_t i = 0; i < float_count; i++) {
  653. work_memory[i] = INF;
  654. }
  655. uint32_t y_mult = octree_size.x;
  656. uint32_t z_mult = y_mult * octree_size.y;
  657. //plot solid cells
  658. {
  659. const Cell *cells = bake_cells.ptr();
  660. uint32_t cell_count = bake_cells.size();
  661. for (uint32_t i = 0; i < cell_count; i++) {
  662. if (cells[i].level < (cell_subdiv - 1)) {
  663. continue; //do not care about this level
  664. }
  665. work_memory[cells[i].x + cells[i].y * y_mult + cells[i].z * z_mult] = 0;
  666. }
  667. }
  668. //process in each direction
  669. //xy->z
  670. for (int i = 0; i < octree_size.x; i++) {
  671. for (int j = 0; j < octree_size.y; j++) {
  672. edt(&work_memory[i + j * y_mult], z_mult, octree_size.z);
  673. }
  674. }
  675. //xz->y
  676. for (int i = 0; i < octree_size.x; i++) {
  677. for (int j = 0; j < octree_size.z; j++) {
  678. edt(&work_memory[i + j * z_mult], y_mult, octree_size.y);
  679. }
  680. }
  681. //yz->x
  682. for (int i = 0; i < octree_size.y; i++) {
  683. for (int j = 0; j < octree_size.z; j++) {
  684. edt(&work_memory[i * y_mult + j * z_mult], 1, octree_size.x);
  685. }
  686. }
  687. Vector<uint8_t> image3d;
  688. image3d.resize(float_count);
  689. {
  690. uint8_t *w = image3d.ptrw();
  691. for (uint32_t i = 0; i < float_count; i++) {
  692. uint32_t d = uint32_t(Math::sqrt(work_memory[i]));
  693. if (d == 0) {
  694. w[i] = 0;
  695. } else {
  696. w[i] = MIN(d, 254u) + 1;
  697. }
  698. }
  699. }
  700. return image3d;
  701. }
  702. #undef INF
  703. void Voxelizer::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx) {
  704. if (p_level == cell_subdiv - 1) {
  705. Vector3 center = p_aabb.get_center();
  706. Transform3D xform;
  707. xform.origin = center;
  708. xform.basis.scale(p_aabb.size * 0.5);
  709. p_multimesh->set_instance_transform(idx, xform);
  710. Color col;
  711. col = Color(bake_cells[p_idx].albedo[0], bake_cells[p_idx].albedo[1], bake_cells[p_idx].albedo[2]);
  712. //Color col = Color(bake_cells[p_idx].emission[0], bake_cells[p_idx].emission[1], bake_cells[p_idx].emission[2]);
  713. p_multimesh->set_instance_color(idx, col);
  714. idx++;
  715. } else {
  716. for (int i = 0; i < 8; i++) {
  717. uint32_t child = bake_cells[p_idx].children[i];
  718. if (child == CHILD_EMPTY || child >= (uint32_t)max_original_cells) {
  719. continue;
  720. }
  721. AABB aabb = p_aabb;
  722. aabb.size *= 0.5;
  723. if (i & 1) {
  724. aabb.position.x += aabb.size.x;
  725. }
  726. if (i & 2) {
  727. aabb.position.y += aabb.size.y;
  728. }
  729. if (i & 4) {
  730. aabb.position.z += aabb.size.z;
  731. }
  732. _debug_mesh(bake_cells[p_idx].children[i], p_level + 1, aabb, p_multimesh, idx);
  733. }
  734. }
  735. }
  736. Ref<MultiMesh> Voxelizer::create_debug_multimesh() {
  737. Ref<MultiMesh> mm;
  738. mm.instantiate();
  739. mm->set_transform_format(MultiMesh::TRANSFORM_3D);
  740. mm->set_use_colors(true);
  741. mm->set_instance_count(leaf_voxel_count);
  742. Ref<ArrayMesh> mesh;
  743. mesh.instantiate();
  744. {
  745. Array arr;
  746. arr.resize(Mesh::ARRAY_MAX);
  747. Vector<Vector3> vertices;
  748. Vector<Color> colors;
  749. #define ADD_VTX(m_idx) \
  750. vertices.push_back(face_points[m_idx]); \
  751. colors.push_back(Color(1, 1, 1, 1));
  752. for (int i = 0; i < 6; i++) {
  753. Vector3 face_points[4];
  754. for (int j = 0; j < 4; j++) {
  755. real_t v[3];
  756. v[0] = 1.0;
  757. v[1] = 1 - 2 * ((j >> 1) & 1);
  758. v[2] = v[1] * (1 - 2 * (j & 1));
  759. for (int k = 0; k < 3; k++) {
  760. if (i < 3) {
  761. face_points[j][(i + k) % 3] = v[k];
  762. } else {
  763. face_points[3 - j][(i + k) % 3] = -v[k];
  764. }
  765. }
  766. }
  767. //tri 1
  768. ADD_VTX(0);
  769. ADD_VTX(1);
  770. ADD_VTX(2);
  771. //tri 2
  772. ADD_VTX(2);
  773. ADD_VTX(3);
  774. ADD_VTX(0);
  775. }
  776. arr[Mesh::ARRAY_VERTEX] = vertices;
  777. arr[Mesh::ARRAY_COLOR] = colors;
  778. mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  779. }
  780. {
  781. Ref<StandardMaterial3D> fsm;
  782. fsm.instantiate();
  783. fsm->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  784. fsm->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  785. fsm->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  786. fsm->set_albedo(Color(1, 1, 1, 1));
  787. mesh->surface_set_material(0, fsm);
  788. }
  789. mm->set_mesh(mesh);
  790. int idx = 0;
  791. _debug_mesh(0, 0, po2_bounds, mm, idx);
  792. return mm;
  793. }
  794. Transform3D Voxelizer::get_to_cell_space_xform() const {
  795. return to_cell_space;
  796. }
  797. Voxelizer::Voxelizer() {
  798. }