voxelizer.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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. int children_found = 0;
  481. for (int i = 0; i < 8; i++) {
  482. uint32_t child = bake_cells[p_idx].children[i];
  483. if (child == CHILD_EMPTY) {
  484. continue;
  485. }
  486. _fixup_plot(child, p_level + 1);
  487. alpha_average += bake_cells[child].alpha;
  488. children_found++;
  489. }
  490. bake_cells.write[p_idx].alpha = alpha_average / 8.0;
  491. }
  492. }
  493. void Voxelizer::begin_bake(int p_subdiv, const AABB &p_bounds) {
  494. sorted = false;
  495. original_bounds = p_bounds;
  496. cell_subdiv = p_subdiv;
  497. bake_cells.resize(1);
  498. material_cache.clear();
  499. //find out the actual real bounds, power of 2, which gets the highest subdivision
  500. po2_bounds = p_bounds;
  501. int longest_axis = po2_bounds.get_longest_axis_index();
  502. axis_cell_size[longest_axis] = 1 << cell_subdiv;
  503. leaf_voxel_count = 0;
  504. for (int i = 0; i < 3; i++) {
  505. if (i == longest_axis) {
  506. continue;
  507. }
  508. axis_cell_size[i] = axis_cell_size[longest_axis];
  509. real_t axis_size = po2_bounds.size[longest_axis];
  510. //shrink until fit subdiv
  511. while (axis_size / 2.0 >= po2_bounds.size[i]) {
  512. axis_size /= 2.0;
  513. axis_cell_size[i] >>= 1;
  514. }
  515. po2_bounds.size[i] = po2_bounds.size[longest_axis];
  516. }
  517. Transform3D to_bounds;
  518. to_bounds.basis.scale(Vector3(po2_bounds.size[longest_axis], po2_bounds.size[longest_axis], po2_bounds.size[longest_axis]));
  519. to_bounds.origin = po2_bounds.position;
  520. Transform3D to_grid;
  521. to_grid.basis.scale(Vector3(axis_cell_size[longest_axis], axis_cell_size[longest_axis], axis_cell_size[longest_axis]));
  522. to_cell_space = to_grid * to_bounds.affine_inverse();
  523. cell_size = po2_bounds.size[longest_axis] / axis_cell_size[longest_axis];
  524. }
  525. void Voxelizer::end_bake() {
  526. if (!sorted) {
  527. _sort();
  528. }
  529. _fixup_plot(0, 0);
  530. }
  531. //create the data for rendering server
  532. int Voxelizer::get_voxel_gi_octree_depth() const {
  533. return cell_subdiv;
  534. }
  535. Vector3i Voxelizer::get_voxel_gi_octree_size() const {
  536. return Vector3i(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]);
  537. }
  538. int Voxelizer::get_voxel_gi_cell_count() const {
  539. return bake_cells.size();
  540. }
  541. Vector<uint8_t> Voxelizer::get_voxel_gi_octree_cells() const {
  542. Vector<uint8_t> data;
  543. data.resize((8 * 4) * bake_cells.size()); //8 uint32t values
  544. {
  545. uint8_t *w = data.ptrw();
  546. uint32_t *children_cells = (uint32_t *)w;
  547. const Cell *cells = bake_cells.ptr();
  548. uint32_t cell_count = bake_cells.size();
  549. for (uint32_t i = 0; i < cell_count; i++) {
  550. for (uint32_t j = 0; j < 8; j++) {
  551. children_cells[i * 8 + j] = cells[i].children[j];
  552. }
  553. }
  554. }
  555. return data;
  556. }
  557. Vector<uint8_t> Voxelizer::get_voxel_gi_data_cells() const {
  558. Vector<uint8_t> data;
  559. data.resize((4 * 4) * bake_cells.size()); //8 uint32t values
  560. {
  561. uint8_t *w = data.ptrw();
  562. uint32_t *dataptr = (uint32_t *)w;
  563. const Cell *cells = bake_cells.ptr();
  564. uint32_t cell_count = bake_cells.size();
  565. for (uint32_t i = 0; i < cell_count; i++) {
  566. { //position
  567. uint32_t x = cells[i].x;
  568. uint32_t y = cells[i].y;
  569. uint32_t z = cells[i].z;
  570. uint32_t position = x;
  571. position |= y << 11;
  572. position |= z << 21;
  573. dataptr[i * 4 + 0] = position;
  574. }
  575. { //albedo + alpha
  576. uint32_t rgba = uint32_t(CLAMP(cells[i].alpha * 255.0, 0, 255)) << 24; //a
  577. rgba |= uint32_t(CLAMP(cells[i].albedo[2] * 255.0, 0, 255)) << 16; //b
  578. rgba |= uint32_t(CLAMP(cells[i].albedo[1] * 255.0, 0, 255)) << 8; //g
  579. rgba |= uint32_t(CLAMP(cells[i].albedo[0] * 255.0, 0, 255)); //r
  580. dataptr[i * 4 + 1] = rgba;
  581. }
  582. { //emission, as rgbe9995
  583. Color emission = Color(cells[i].emission[0], cells[i].emission[1], cells[i].emission[2]);
  584. dataptr[i * 4 + 2] = emission.to_rgbe9995();
  585. }
  586. { //normal
  587. Vector3 n(bake_cells[i].normal[0], bake_cells[i].normal[1], bake_cells[i].normal[2]);
  588. n.normalize();
  589. uint32_t normal = uint32_t(uint8_t(int8_t(CLAMP(n.x * 127.0, -128, 127))));
  590. normal |= uint32_t(uint8_t(int8_t(CLAMP(n.y * 127.0, -128, 127)))) << 8;
  591. normal |= uint32_t(uint8_t(int8_t(CLAMP(n.z * 127.0, -128, 127)))) << 16;
  592. dataptr[i * 4 + 3] = normal;
  593. }
  594. }
  595. }
  596. return data;
  597. }
  598. Vector<int> Voxelizer::get_voxel_gi_level_cell_count() const {
  599. uint32_t cell_count = bake_cells.size();
  600. const Cell *cells = bake_cells.ptr();
  601. Vector<int> level_count;
  602. level_count.resize(cell_subdiv + 1); //remember, always x+1 levels for x subdivisions
  603. {
  604. int *w = level_count.ptrw();
  605. for (int i = 0; i < cell_subdiv + 1; i++) {
  606. w[i] = 0;
  607. }
  608. for (uint32_t i = 0; i < cell_count; i++) {
  609. w[cells[i].level]++;
  610. }
  611. }
  612. return level_count;
  613. }
  614. // euclidean distance computation based on:
  615. // https://prideout.net/blog/distance_fields/
  616. #define square(m_s) ((m_s) * (m_s))
  617. #define INF 1e20
  618. /* dt of 1d function using squared distance */
  619. static void edt(float *f, int stride, int n) {
  620. float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
  621. int *v = (int *)&(d[n]);
  622. float *z = (float *)&v[n];
  623. int k = 0;
  624. v[0] = 0;
  625. z[0] = -INF;
  626. z[1] = +INF;
  627. for (int q = 1; q <= n - 1; q++) {
  628. float s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  629. while (s <= z[k]) {
  630. k--;
  631. s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  632. }
  633. k++;
  634. v[k] = q;
  635. z[k] = s;
  636. z[k + 1] = +INF;
  637. }
  638. k = 0;
  639. for (int q = 0; q <= n - 1; q++) {
  640. while (z[k + 1] < q) {
  641. k++;
  642. }
  643. d[q] = square(q - v[k]) + f[v[k] * stride];
  644. }
  645. for (int i = 0; i < n; i++) {
  646. f[i * stride] = d[i];
  647. }
  648. }
  649. #undef square
  650. Vector<uint8_t> Voxelizer::get_sdf_3d_image() const {
  651. Vector3i octree_size = get_voxel_gi_octree_size();
  652. uint32_t float_count = octree_size.x * octree_size.y * octree_size.z;
  653. float *work_memory = memnew_arr(float, float_count);
  654. for (uint32_t i = 0; i < float_count; i++) {
  655. work_memory[i] = INF;
  656. }
  657. uint32_t y_mult = octree_size.x;
  658. uint32_t z_mult = y_mult * octree_size.y;
  659. //plot solid cells
  660. {
  661. const Cell *cells = bake_cells.ptr();
  662. uint32_t cell_count = bake_cells.size();
  663. for (uint32_t i = 0; i < cell_count; i++) {
  664. if (cells[i].level < (cell_subdiv - 1)) {
  665. continue; //do not care about this level
  666. }
  667. work_memory[cells[i].x + cells[i].y * y_mult + cells[i].z * z_mult] = 0;
  668. }
  669. }
  670. //process in each direction
  671. //xy->z
  672. for (int i = 0; i < octree_size.x; i++) {
  673. for (int j = 0; j < octree_size.y; j++) {
  674. edt(&work_memory[i + j * y_mult], z_mult, octree_size.z);
  675. }
  676. }
  677. //xz->y
  678. for (int i = 0; i < octree_size.x; i++) {
  679. for (int j = 0; j < octree_size.z; j++) {
  680. edt(&work_memory[i + j * z_mult], y_mult, octree_size.y);
  681. }
  682. }
  683. //yz->x
  684. for (int i = 0; i < octree_size.y; i++) {
  685. for (int j = 0; j < octree_size.z; j++) {
  686. edt(&work_memory[i * y_mult + j * z_mult], 1, octree_size.x);
  687. }
  688. }
  689. Vector<uint8_t> image3d;
  690. image3d.resize(float_count);
  691. {
  692. uint8_t *w = image3d.ptrw();
  693. for (uint32_t i = 0; i < float_count; i++) {
  694. uint32_t d = uint32_t(Math::sqrt(work_memory[i]));
  695. if (d == 0) {
  696. w[i] = 0;
  697. } else {
  698. w[i] = MIN(d, 254u) + 1;
  699. }
  700. }
  701. }
  702. return image3d;
  703. }
  704. #undef INF
  705. void Voxelizer::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx) {
  706. if (p_level == cell_subdiv - 1) {
  707. Vector3 center = p_aabb.get_center();
  708. Transform3D xform;
  709. xform.origin = center;
  710. xform.basis.scale(p_aabb.size * 0.5);
  711. p_multimesh->set_instance_transform(idx, xform);
  712. Color col;
  713. col = Color(bake_cells[p_idx].albedo[0], bake_cells[p_idx].albedo[1], bake_cells[p_idx].albedo[2]);
  714. //Color col = Color(bake_cells[p_idx].emission[0], bake_cells[p_idx].emission[1], bake_cells[p_idx].emission[2]);
  715. p_multimesh->set_instance_color(idx, col);
  716. idx++;
  717. } else {
  718. for (int i = 0; i < 8; i++) {
  719. uint32_t child = bake_cells[p_idx].children[i];
  720. if (child == CHILD_EMPTY || child >= (uint32_t)max_original_cells) {
  721. continue;
  722. }
  723. AABB aabb = p_aabb;
  724. aabb.size *= 0.5;
  725. if (i & 1) {
  726. aabb.position.x += aabb.size.x;
  727. }
  728. if (i & 2) {
  729. aabb.position.y += aabb.size.y;
  730. }
  731. if (i & 4) {
  732. aabb.position.z += aabb.size.z;
  733. }
  734. _debug_mesh(bake_cells[p_idx].children[i], p_level + 1, aabb, p_multimesh, idx);
  735. }
  736. }
  737. }
  738. Ref<MultiMesh> Voxelizer::create_debug_multimesh() {
  739. Ref<MultiMesh> mm;
  740. mm.instantiate();
  741. mm->set_transform_format(MultiMesh::TRANSFORM_3D);
  742. mm->set_use_colors(true);
  743. mm->set_instance_count(leaf_voxel_count);
  744. Ref<ArrayMesh> mesh;
  745. mesh.instantiate();
  746. {
  747. Array arr;
  748. arr.resize(Mesh::ARRAY_MAX);
  749. Vector<Vector3> vertices;
  750. Vector<Color> colors;
  751. #define ADD_VTX(m_idx) \
  752. vertices.push_back(face_points[m_idx]); \
  753. colors.push_back(Color(1, 1, 1, 1));
  754. for (int i = 0; i < 6; i++) {
  755. Vector3 face_points[4];
  756. for (int j = 0; j < 4; j++) {
  757. real_t v[3];
  758. v[0] = 1.0;
  759. v[1] = 1 - 2 * ((j >> 1) & 1);
  760. v[2] = v[1] * (1 - 2 * (j & 1));
  761. for (int k = 0; k < 3; k++) {
  762. if (i < 3) {
  763. face_points[j][(i + k) % 3] = v[k];
  764. } else {
  765. face_points[3 - j][(i + k) % 3] = -v[k];
  766. }
  767. }
  768. }
  769. //tri 1
  770. ADD_VTX(0);
  771. ADD_VTX(1);
  772. ADD_VTX(2);
  773. //tri 2
  774. ADD_VTX(2);
  775. ADD_VTX(3);
  776. ADD_VTX(0);
  777. }
  778. arr[Mesh::ARRAY_VERTEX] = vertices;
  779. arr[Mesh::ARRAY_COLOR] = colors;
  780. mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  781. }
  782. {
  783. Ref<StandardMaterial3D> fsm;
  784. fsm.instantiate();
  785. fsm->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  786. fsm->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  787. fsm->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  788. fsm->set_albedo(Color(1, 1, 1, 1));
  789. mesh->surface_set_material(0, fsm);
  790. }
  791. mm->set_mesh(mesh);
  792. int idx = 0;
  793. _debug_mesh(0, 0, po2_bounds, mm, idx);
  794. return mm;
  795. }
  796. Transform3D Voxelizer::get_to_cell_space_xform() const {
  797. return to_cell_space;
  798. }
  799. Voxelizer::Voxelizer() {
  800. }