voxelizer.cpp 28 KB

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