Debian Codegraph @

scene/3d/voxelizer.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* voxelizer.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "voxelizer.h"
32
33 #include "core/config/project_settings.h"
34
35 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) {
36 if (p_pos.is_equal_approx(p_vtx[0])) {
37 r_uv = p_uv[0];
38 r_normal = p_normal[0];
39 return;
40 }
41 if (p_pos.is_equal_approx(p_vtx[1])) {
42 r_uv = p_uv[1];
43 r_normal = p_normal[1];
44 return;
45 }
46 if (p_pos.is_equal_approx(p_vtx[2])) {
47 r_uv = p_uv[2];
48 r_normal = p_normal[2];
49 return;
50 }
51
52 Vector3 v0 = p_vtx[1] - p_vtx[0];
53 Vector3 v1 = p_vtx[2] - p_vtx[0];
54 Vector3 v2 = p_pos - p_vtx[0];
55
56 real_t d00 = v0.dot(v0);
57 real_t d01 = v0.dot(v1);
58 real_t d11 = v1.dot(v1);
59 real_t d20 = v2.dot(v0);
60 real_t d21 = v2.dot(v1);
61 real_t denom = (d00 * d11 - d01 * d01);
62 if (denom == 0) {
63 r_uv = p_uv[0];
64 r_normal = p_normal[0];
65 return;
66 }
67 real_t v = (d11 * d20 - d01 * d21) / denom;
68 real_t w = (d00 * d21 - d01 * d20) / denom;
69 real_t u = 1.0f - v - w;
70
71 r_uv = p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
72 r_normal = (p_normal[0] * u + p_normal[1] * v + p_normal[2] * w).normalized();
73 }
74
75 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) {
76 if (p_level == cell_subdiv) {
77 //plot the face by guessing its albedo and emission value
78
79 //find best axis to map to, for scanning values
80 int closest_axis = 0;
81 real_t closest_dot = 0;
82
83 Plane plane = Plane(p_vtx[0], p_vtx[1], p_vtx[2]);
84 Vector3 normal = plane.normal;
85
86 for (int i = 0; i < 3; i++) {
87 Vector3 axis;
88 axis[i] = 1.0;
89 real_t dot = Math::abs(normal.dot(axis));
90 if (i == 0 || dot > closest_dot) {
91 closest_axis = i;
92 closest_dot = dot;
93 }
94 }
95
96 Vector3 axis;
97 axis[closest_axis] = 1.0;
98 Vector3 t1;
99 t1[(closest_axis + 1) % 3] = 1.0;
100 Vector3 t2;
101 t2[(closest_axis + 2) % 3] = 1.0;
102
103 t1 *= p_aabb.size[(closest_axis + 1) % 3] / real_t(color_scan_cell_width);
104 t2 *= p_aabb.size[(closest_axis + 2) % 3] / real_t(color_scan_cell_width);
105
106 Color albedo_accum;
107 Color emission_accum;
108 Vector3 normal_accum;
109
110 float alpha = 0.0;
111
112 //map to a grid average in the best axis for this face
113 for (int i = 0; i < color_scan_cell_width; i++) {
114 Vector3 ofs_i = real_t(i) * t1;
115
116 for (int j = 0; j < color_scan_cell_width; j++) {
117 Vector3 ofs_j = real_t(j) * t2;
118
119 Vector3 from = p_aabb.position + ofs_i + ofs_j;
120 Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis];
121 Vector3 half = (to - from) * 0.5;
122
123 //is in this cell?
124 if (!Geometry3D::triangle_box_overlap(from + half, half, p_vtx)) {
125 continue; //face does not span this cell
126 }
127
128 //go from -size to +size*2 to avoid skipping collisions
129 Vector3 ray_from = from + (t1 + t2) * 0.5 - axis * p_aabb.size[closest_axis];
130 Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis] * 2;
131
132 if (normal.dot(ray_from - ray_to) < 0) {
133 SWAP(ray_from, ray_to);
134 }
135
136 Vector3 intersection;
137
138 if (!plane.intersects_segment(ray_from, ray_to, &intersection)) {
139 if (Math::abs(plane.distance_to(ray_from)) < Math::abs(plane.distance_to(ray_to))) {
140 intersection = plane.project(ray_from);
141 } else {
142 intersection = plane.project(ray_to);
143 }
144 }
145
146 intersection = Face3(p_vtx[0], p_vtx[1], p_vtx[2]).get_closest_point_to(intersection);
147
148 Vector2 uv;
149 Vector3 lnormal;
150 get_uv_and_normal(intersection, p_vtx, p_uv, p_normal, uv, lnormal);
151 if (lnormal == Vector3()) { //just in case normal is not provided
152 lnormal = normal;
153 }
154
155 int uv_x = CLAMP(int(Math::fposmod(uv.x, (real_t)1.0) * bake_texture_size), 0, bake_texture_size - 1);
156 int uv_y = CLAMP(int(Math::fposmod(uv.y, (real_t)1.0) * bake_texture_size), 0, bake_texture_size - 1);
157
158 int ofs = uv_y * bake_texture_size + uv_x;
159 albedo_accum.r += p_material.albedo[ofs].r;
160 albedo_accum.g += p_material.albedo[ofs].g;
161 albedo_accum.b += p_material.albedo[ofs].b;
162 albedo_accum.a += p_material.albedo[ofs].a;
163
164 emission_accum.r += p_material.emission[ofs].r;
165 emission_accum.g += p_material.emission[ofs].g;
166 emission_accum.b += p_material.emission[ofs].b;
167
168 normal_accum += lnormal;
169
170 alpha += 1.0;
171 }
172 }
173
174 if (alpha == 0) {
175 //could not in any way get texture information.. so use closest point to center
176
177 Face3 f(p_vtx[0], p_vtx[1], p_vtx[2]);
178 Vector3 inters = f.get_closest_point_to(p_aabb.get_center());
179
180 Vector3 lnormal;
181 Vector2 uv;
182 get_uv_and_normal(inters, p_vtx, p_uv, p_normal, uv, normal);
183 if (lnormal == Vector3()) { //just in case normal is not provided
184 lnormal = normal;
185 }
186
187 int uv_x = CLAMP(Math::fposmod(uv.x, (real_t)1.0) * bake_texture_size, 0, bake_texture_size - 1);
188 int uv_y = CLAMP(Math::fposmod(uv.y, (real_t)1.0) * bake_texture_size, 0, bake_texture_size - 1);
189
190 int ofs = uv_y * bake_texture_size + uv_x;
191
192 alpha = 1.0 / (color_scan_cell_width * color_scan_cell_width);
193
194 albedo_accum.r = p_material.albedo[ofs].r * alpha;
195 albedo_accum.g = p_material.albedo[ofs].g * alpha;
196 albedo_accum.b = p_material.albedo[ofs].b * alpha;
197 albedo_accum.a = p_material.albedo[ofs].a * alpha;
198
199 emission_accum.r = p_material.emission[ofs].r * alpha;
200 emission_accum.g = p_material.emission[ofs].g * alpha;
201 emission_accum.b = p_material.emission[ofs].b * alpha;
202
203 normal_accum = lnormal * alpha;
204
205 } else {
206 float accdiv = 1.0 / (color_scan_cell_width * color_scan_cell_width);
207 alpha *= accdiv;
208
209 albedo_accum.r *= accdiv;
210 albedo_accum.g *= accdiv;
211 albedo_accum.b *= accdiv;
212 albedo_accum.a *= accdiv;
213
214 emission_accum.r *= accdiv;
215 emission_accum.g *= accdiv;
216 emission_accum.b *= accdiv;
217
218 normal_accum *= accdiv;
219 }
220
221 //put this temporarily here, corrected in a later step
222 bake_cells.write[p_idx].albedo[0] += albedo_accum.r;
223 bake_cells.write[p_idx].albedo[1] += albedo_accum.g;
224 bake_cells.write[p_idx].albedo[2] += albedo_accum.b;
225 bake_cells.write[p_idx].emission[0] += emission_accum.r;
226 bake_cells.write[p_idx].emission[1] += emission_accum.g;
227 bake_cells.write[p_idx].emission[2] += emission_accum.b;
228 bake_cells.write[p_idx].normal[0] += normal_accum.x;
229 bake_cells.write[p_idx].normal[1] += normal_accum.y;
230 bake_cells.write[p_idx].normal[2] += normal_accum.z;
231 bake_cells.write[p_idx].alpha += alpha;
232
233 } else {
234 //go down
235
236 int half = (1 << cell_subdiv) >> (p_level + 1);
237 for (int i = 0; i < 8; i++) {
238 AABB aabb = p_aabb;
239 aabb.size *= 0.5;
240
241 int nx = p_x;
242 int ny = p_y;
243 int nz = p_z;
244
245 if (i & 1) {
246 aabb.position.x += aabb.size.x;
247 nx += half;
248 }
249 if (i & 2) {
250 aabb.position.y += aabb.size.y;
251 ny += half;
252 }
253 if (i & 4) {
254 aabb.position.z += aabb.size.z;
255 nz += half;
256 }
257 //make sure to not plot beyond limits
258 if (nx < 0 || nx >= axis_cell_size[0] || ny < 0 || ny >= axis_cell_size[1] || nz < 0 || nz >= axis_cell_size[2]) {
259 continue;
260 }
261
262 {
263 AABB test_aabb = aabb;
264 //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time
265 Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test
266
267 if (!Geometry3D::triangle_box_overlap(test_aabb.position + qsize, qsize, p_vtx)) {
268 //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
269 //does not fit in child, go on
270 continue;
271 }
272 }
273
274 if (bake_cells[p_idx].children[i] == CHILD_EMPTY) {
275 //sub cell must be created
276
277 uint32_t child_idx = bake_cells.size();
278 bake_cells.write[p_idx].children[i] = child_idx;
279 bake_cells.resize(bake_cells.size() + 1);
280 bake_cells.write[child_idx].level = p_level + 1;
281 bake_cells.write[child_idx].x = nx / half;
282 bake_cells.write[child_idx].y = ny / half;
283 bake_cells.write[child_idx].z = nz / half;
284 }
285
286 _plot_face(bake_cells[p_idx].children[i], p_level + 1, nx, ny, nz, p_vtx, p_normal, p_uv, p_material, aabb);
287 }
288 }
289 }
290
291 Vector<Color> Voxelizer::_get_bake_texture(Ref<Image> p_image, const Color &p_color_mul, const Color &p_color_add) {
292 Vector<Color> ret;
293
294 if (p_image.is_null() || p_image->is_empty()) {
295 ret.resize(bake_texture_size * bake_texture_size);
296 for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
297 ret.write[i] = p_color_add;
298 }
299
300 return ret;
301 }
302 p_image = p_image->duplicate();
303
304 if (p_image->is_compressed()) {
305 p_image->decompress();
306 }
307 p_image->convert(Image::FORMAT_RGBA8);
308 p_image->resize(bake_texture_size, bake_texture_size, Image::INTERPOLATE_CUBIC);
309
310 const uint8_t *r = p_image->get_data().ptr();
311 ret.resize(bake_texture_size * bake_texture_size);
312
313 for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
314 Color c;
315 Color src = Color(
316 r[i * 4 + 0] / 255.0,
317 r[i * 4 + 1] / 255.0,
318 r[i * 4 + 2] / 255.0,
319 r[i * 4 + 3] / 255.0);
320 src = src.srgb_to_linear();
321
322 c.r = src.r * p_color_mul.r + p_color_add.r;
323 c.g = src.g * p_color_mul.g + p_color_add.g;
324 c.b = src.b * p_color_mul.b + p_color_add.b;
325 c.a = src.a;
326
327 ret.write[i] = c;
328 }
329
330 return ret;
331 }
332
333 Voxelizer::MaterialCache Voxelizer::_get_material_cache(Ref<Material> p_material) {
334 // This way of obtaining materials is inaccurate and also does not support some compressed formats very well.
335 Ref<BaseMaterial3D> mat = p_material;
336
337 Ref<Material> material = mat; //hack for now
338
339 if (material_cache.has(material)) {
340 return material_cache[material];
341 }
342
343 MaterialCache mc;
344
345 if (mat.is_valid()) {
346 Ref<Texture2D> albedo_tex = mat->get_texture(BaseMaterial3D::TEXTURE_ALBEDO);
347
348 Ref<Image> img_albedo;
349 if (albedo_tex.is_valid()) {
350 img_albedo = albedo_tex->get_image();
351 mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo().srgb_to_linear(), Color(0, 0, 0)); // albedo texture, color is multiplicative
352 } else {
353 mc.albedo = _get_bake_texture(img_albedo, Color(1, 1, 1), mat->get_albedo().srgb_to_linear()); // no albedo texture, color is additive
354 }
355 if (mat->get_feature(BaseMaterial3D::FEATURE_EMISSION)) {
356 Ref<Texture2D> emission_tex = mat->get_texture(BaseMaterial3D::TEXTURE_EMISSION);
357
358 Color emission_col = mat->get_emission().srgb_to_linear();
359 float emission_energy = mat->get_emission_energy_multiplier() * exposure_normalization;
360 if (GLOBAL_GET_CACHED(bool, "rendering/lights_and_shadows/use_physical_light_units")) {
361 emission_energy *= mat->get_emission_intensity();
362 }
363
364 Ref<Image> img_emission;
365
366 if (emission_tex.is_valid()) {
367 img_emission = emission_tex->get_image();
368 }
369
370 if (mat->get_emission_operator() == BaseMaterial3D::EMISSION_OP_ADD) {
371 mc.emission = _get_bake_texture(img_emission, Color(1, 1, 1) * emission_energy, emission_col * emission_energy);
372 } else {
373 mc.emission = _get_bake_texture(img_emission, emission_col * emission_energy, Color(0, 0, 0));
374 }
375 } else {
376 Ref<Image> empty;
377 mc.emission = _get_bake_texture(empty, Color(0, 0, 0), Color(0, 0, 0));
378 }
379
380 } else {
381 Ref<Image> empty;
382
383 mc.albedo = _get_bake_texture(empty, Color(0, 0, 0), Color(1, 1, 1));
384 mc.emission = _get_bake_texture(empty, Color(0, 0, 0), Color(0, 0, 0));
385 }
386
387 material_cache[p_material] = mc;
388 return mc;
389 }
390
391 int Voxelizer::get_bake_steps(Ref<Mesh> &p_mesh) const {
392 int bake_total = 0;
393 for (int i = 0; i < p_mesh->get_surface_count(); i++) {
394 if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
395 continue; // Only triangles.
396 }
397 Array a = p_mesh->surface_get_arrays(i);
398 Vector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
399 Vector<int> index = a[Mesh::ARRAY_INDEX];
400 bake_total += (index.size() > 0 ? index.size() : vertices.size()) / 3;
401 }
402 return bake_total;
403 }
404
405 Voxelizer::BakeResult Voxelizer::plot_mesh(const Transform3D &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material>> &p_materials, const Ref<Material> &p_override_material, BakeStepFunc p_bake_step_func) {
406 ERR_FAIL_COND_V_MSG(!p_xform.is_finite(), BAKE_RESULT_INVALID_PARAMETER, "Invalid mesh bake transform.");
407
408 // Precalculate for transforming vertex normals
409 Basis normal_xform = p_xform.basis.inverse().transposed();
410
411 int bake_total = get_bake_steps(p_mesh), bake_current = 0;
412
413 for (int i = 0; i < p_mesh->get_surface_count(); i++) {
414 if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
415 continue; //only triangles
416 }
417
418 Ref<Material> src_material;
419
420 if (p_override_material.is_valid()) {
421 src_material = p_override_material;
422 } else if (i < p_materials.size() && p_materials[i].is_valid()) {
423 src_material = p_materials[i];
424 } else {
425 src_material = p_mesh->surface_get_material(i);
426 }
427 MaterialCache material = _get_material_cache(src_material);
428
429 Array a = p_mesh->surface_get_arrays(i);
430
431 Vector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
432 const Vector3 *vr = vertices.ptr();
433 Vector<Vector2> uv = a[Mesh::ARRAY_TEX_UV];
434 const Vector2 *uvr = nullptr;
435 Vector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
436 const Vector3 *nr = nullptr;
437 Vector<int> index = a[Mesh::ARRAY_INDEX];
438
439 if (uv.size()) {
440 uvr = uv.ptr();
441 }
442
443 if (normals.size()) {
444 nr = normals.ptr();
445 }
446
447 if (index.size()) {
448 int facecount = index.size() / 3;
449 const int *ir = index.ptr();
450
451 for (int j = 0; j < facecount; j++) {
452 Vector3 vtxs[3];
453 Vector2 uvs[3];
454 Vector3 normal[3];
455
456 bake_current++;
457 if (p_bake_step_func != nullptr && (bake_current & 2047) == 1) {
458 if (p_bake_step_func(bake_current, bake_total)) {
459 return BAKE_RESULT_CANCELLED;
460 }
461 }
462
463 for (int k = 0; k < 3; k++) {
464 vtxs[k] = p_xform.xform(vr[ir[j * 3 + k]]);
465 }
466
467 if (uvr) {
468 for (int k = 0; k < 3; k++) {
469 uvs[k] = uvr[ir[j * 3 + k]];
470 }
471 }
472
473 if (nr) {
474 for (int k = 0; k < 3; k++) {
475 normal[k] = normal_xform.xform(nr[ir[j * 3 + k]]).normalized();
476 }
477 }
478
479 //test against original bounds
480 if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
481 continue;
482 }
483 //plot
484 _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
485 }
486
487 } else {
488 int facecount = vertices.size() / 3;
489
490 for (int j = 0; j < facecount; j++) {
491 Vector3 vtxs[3];
492 Vector2 uvs[3];
493 Vector3 normal[3];
494
495 bake_current++;
496 if (p_bake_step_func != nullptr && (bake_current & 2047) == 1) {
497 if (p_bake_step_func(bake_current, bake_total)) {
498 return BAKE_RESULT_CANCELLED;
499 }
500 }
501
502 for (int k = 0; k < 3; k++) {
503 vtxs[k] = p_xform.xform(vr[j * 3 + k]);
504 }
505
506 if (uvr) {
507 for (int k = 0; k < 3; k++) {
508 uvs[k] = uvr[j * 3 + k];
509 }
510 }
511
512 if (nr) {
513 for (int k = 0; k < 3; k++) {
514 normal[k] = nr[j * 3 + k];
515 }
516 }
517
518 //test against original bounds
519 if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
520 continue;
521 }
522 //plot face
523 _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
524 }
525 }
526 }
527
528 max_original_cells = bake_cells.size();
529
530 return BAKE_RESULT_OK;
531 }
532
533 void Voxelizer::_sort() {
534 // cells need to be sorted by level and coordinates
535 // it is important that level has more priority (for compute), and that Z has the least,
536 // given it may aid older implementations plot using GPU
537
538 Vector<CellSort> sorted_cells;
539 uint32_t cell_count = bake_cells.size();
540 sorted_cells.resize(cell_count);
541 {
542 CellSort *sort_cellsp = sorted_cells.ptrw();
543 const Cell *bake_cellsp = bake_cells.ptr();
544
545 for (uint32_t i = 0; i < cell_count; i++) {
546 sort_cellsp[i].x = bake_cellsp[i].x;
547 sort_cellsp[i].y = bake_cellsp[i].y;
548 sort_cellsp[i].z = bake_cellsp[i].z;
549 sort_cellsp[i].level = bake_cellsp[i].level;
550 sort_cellsp[i].index = i;
551 }
552 }
553
554 sorted_cells.sort();
555
556 //verify just in case, index 0 must be level 0
557 ERR_FAIL_COND(sorted_cells[0].level != 0);
558
559 Vector<Cell> new_bake_cells;
560 new_bake_cells.resize(cell_count);
561 Vector<uint32_t> reverse_map;
562
563 {
564 reverse_map.resize(cell_count);
565 const CellSort *sort_cellsp = sorted_cells.ptr();
566 uint32_t *reverse_mapp = reverse_map.ptrw();
567
568 for (uint32_t i = 0; i < cell_count; i++) {
569 reverse_mapp[sort_cellsp[i].index] = i;
570 }
571 }
572
573 {
574 const CellSort *sort_cellsp = sorted_cells.ptr();
575 const Cell *bake_cellsp = bake_cells.ptr();
576 const uint32_t *reverse_mapp = reverse_map.ptr();
577 Cell *new_bake_cellsp = new_bake_cells.ptrw();
578
579 for (uint32_t i = 0; i < cell_count; i++) {
580 //copy to new cell
581 new_bake_cellsp[i] = bake_cellsp[sort_cellsp[i].index];
582 //remap children
583 for (uint32_t j = 0; j < 8; j++) {
584 if (new_bake_cellsp[i].children[j] != CHILD_EMPTY) {
585 new_bake_cellsp[i].children[j] = reverse_mapp[new_bake_cellsp[i].children[j]];
586 }
587 }
588 }
589 }
590
591 bake_cells = new_bake_cells;
592 sorted = true;
593 }
594
595 void Voxelizer::_fixup_plot(int p_idx, int p_level) {
596 if (p_level == cell_subdiv) {
597 leaf_voxel_count++;
598 float alpha = bake_cells[p_idx].alpha;
599
600 bake_cells.write[p_idx].albedo[0] /= alpha;
601 bake_cells.write[p_idx].albedo[1] /= alpha;
602 bake_cells.write[p_idx].albedo[2] /= alpha;
603
604 //transfer emission to light
605 bake_cells.write[p_idx].emission[0] /= alpha;
606 bake_cells.write[p_idx].emission[1] /= alpha;
607 bake_cells.write[p_idx].emission[2] /= alpha;
608
609 bake_cells.write[p_idx].normal[0] /= alpha;
610 bake_cells.write[p_idx].normal[1] /= alpha;
611 bake_cells.write[p_idx].normal[2] /= alpha;
612
613 Vector3 n(bake_cells[p_idx].normal[0], bake_cells[p_idx].normal[1], bake_cells[p_idx].normal[2]);
614 if (n.length() < 0.01) {
615 //too much fight over normal, zero it
616 bake_cells.write[p_idx].normal[0] = 0;
617 bake_cells.write[p_idx].normal[1] = 0;
618 bake_cells.write[p_idx].normal[2] = 0;
619 } else {
620 n.normalize();
621 bake_cells.write[p_idx].normal[0] = n.x;
622 bake_cells.write[p_idx].normal[1] = n.y;
623 bake_cells.write[p_idx].normal[2] = n.z;
624 }
625
626 bake_cells.write[p_idx].alpha = 1.0;
627
628 /*if (bake_light.size()) {
629 for(int i=0;i<6;i++) {
630 }
631 }*/
632
633 } else {
634 //go down
635
636 bake_cells.write[p_idx].emission[0] = 0;
637 bake_cells.write[p_idx].emission[1] = 0;
638 bake_cells.write[p_idx].emission[2] = 0;
639 bake_cells.write[p_idx].normal[0] = 0;
640 bake_cells.write[p_idx].normal[1] = 0;
641 bake_cells.write[p_idx].normal[2] = 0;
642 bake_cells.write[p_idx].albedo[0] = 0;
643 bake_cells.write[p_idx].albedo[1] = 0;
644 bake_cells.write[p_idx].albedo[2] = 0;
645
646 float alpha_average = 0;
647
648 for (int i = 0; i < 8; i++) {
649 uint32_t child = bake_cells[p_idx].children[i];
650
651 if (child == CHILD_EMPTY) {
652 continue;
653 }
654
655 _fixup_plot(child, p_level + 1);
656 alpha_average += bake_cells[child].alpha;
657 }
658
659 bake_cells.write[p_idx].alpha = alpha_average / 8.0;
660 }
661 }
662
663 void Voxelizer::begin_bake(int p_subdiv, const AABB &p_bounds, float p_exposure_normalization) {
664 sorted = false;
665 original_bounds = p_bounds;
666 cell_subdiv = p_subdiv;
667 exposure_normalization = p_exposure_normalization;
668 bake_cells.resize(1);
669 material_cache.clear();
670
671 //find out the actual real bounds, power of 2, which gets the highest subdivision
672 po2_bounds = p_bounds;
673 int longest_axis = po2_bounds.get_longest_axis_index();
674 axis_cell_size[longest_axis] = 1 << cell_subdiv;
675 leaf_voxel_count = 0;
676
677 for (int i = 0; i < 3; i++) {
678 if (i == longest_axis) {
679 continue;
680 }
681
682 axis_cell_size[i] = axis_cell_size[longest_axis];
683 real_t axis_size = po2_bounds.size[longest_axis];
684
685 //shrink until fit subdiv
686 while (axis_size / 2.0 >= po2_bounds.size[i]) {
687 axis_size /= 2.0;
688 axis_cell_size[i] >>= 1;
689 }
690
691 po2_bounds.size[i] = po2_bounds.size[longest_axis];
692 }
693
694 Transform3D to_bounds;
695 to_bounds.basis.scale(Vector3(po2_bounds.size[longest_axis], po2_bounds.size[longest_axis], po2_bounds.size[longest_axis]));
696 to_bounds.origin = po2_bounds.position;
697
698 Transform3D to_grid;
699 to_grid.basis.scale(Vector3(axis_cell_size[longest_axis], axis_cell_size[longest_axis], axis_cell_size[longest_axis]));
700
701 to_cell_space = to_grid * to_bounds.affine_inverse();
702
703 cell_size = po2_bounds.size[longest_axis] / axis_cell_size[longest_axis];
704 }
705
706 void Voxelizer::end_bake() {
707 if (!sorted) {
708 _sort();
709 }
710 _fixup_plot(0, 0);
711 }
712
713 //create the data for rendering server
714
715 int Voxelizer::get_voxel_gi_octree_depth() const {
716 return cell_subdiv;
717 }
718
719 Vector3i Voxelizer::get_voxel_gi_octree_size() const {
720 return Vector3i(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]);
721 }
722
723 int Voxelizer::get_voxel_gi_cell_count() const {
724 return bake_cells.size();
725 }
726
727 Vector<uint8_t> Voxelizer::get_voxel_gi_octree_cells() const {
728 Vector<uint8_t> data;
729 data.resize((8 * 4) * bake_cells.size()); //8 uint32t values
730 {
731 uint8_t *w = data.ptrw();
732 uint32_t *children_cells = (uint32_t *)w;
733 const Cell *cells = bake_cells.ptr();
734
735 uint32_t cell_count = bake_cells.size();
736
737 for (uint32_t i = 0; i < cell_count; i++) {
738 for (uint32_t j = 0; j < 8; j++) {
739 children_cells[i * 8 + j] = cells[i].children[j];
740 }
741 }
742 }
743
744 return data;
745 }
746
747 Vector<uint8_t> Voxelizer::get_voxel_gi_data_cells() const {
748 Vector<uint8_t> data;
749 data.resize((4 * 4) * bake_cells.size()); //8 uint32t values
750 {
751 uint8_t *w = data.ptrw();
752 uint32_t *dataptr = (uint32_t *)w;
753 const Cell *cells = bake_cells.ptr();
754
755 uint32_t cell_count = bake_cells.size();
756
757 for (uint32_t i = 0; i < cell_count; i++) {
758 { //position
759
760 uint32_t x = cells[i].x;
761 uint32_t y = cells[i].y;
762 uint32_t z = cells[i].z;
763
764 uint32_t position = x;
765 position |= y << 11;
766 position |= z << 21;
767
768 dataptr[i * 4 + 0] = position;
769 }
770
771 { //albedo + alpha
772 uint32_t rgba = uint32_t(CLAMP(cells[i].alpha * 255.0, 0, 255)) << 24; //a
773 rgba |= uint32_t(CLAMP(cells[i].albedo[2] * 255.0, 0, 255)) << 16; //b
774 rgba |= uint32_t(CLAMP(cells[i].albedo[1] * 255.0, 0, 255)) << 8; //g
775 rgba |= uint32_t(CLAMP(cells[i].albedo[0] * 255.0, 0, 255)); //r
776
777 dataptr[i * 4 + 1] = rgba;
778 }
779
780 { //emission, as rgbe9995
781 Color emission = Color(cells[i].emission[0], cells[i].emission[1], cells[i].emission[2]);
782 dataptr[i * 4 + 2] = emission.to_rgbe9995();
783 }
784
785 { //normal
786
787 Vector3 n(bake_cells[i].normal[0], bake_cells[i].normal[1], bake_cells[i].normal[2]);
788 n.normalize();
789
790 uint32_t normal = uint32_t(uint8_t(int8_t(CLAMP(n.x * 127.0, -128, 127))));
791 normal |= uint32_t(uint8_t(int8_t(CLAMP(n.y * 127.0, -128, 127)))) << 8;
792 normal |= uint32_t(uint8_t(int8_t(CLAMP(n.z * 127.0, -128, 127)))) << 16;
793
794 dataptr[i * 4 + 3] = normal;
795 }
796 }
797 }
798
799 return data;
800 }
801
802 Vector<int> Voxelizer::get_voxel_gi_level_cell_count() const {
803 uint32_t cell_count = bake_cells.size();
804 const Cell *cells = bake_cells.ptr();
805 Vector<int> level_count;
806 level_count.resize(cell_subdiv + 1); //remember, always x+1 levels for x subdivisions
807 {
808 int *w = level_count.ptrw();
809 for (int i = 0; i < cell_subdiv + 1; i++) {
810 w[i] = 0;
811 }
812
813 for (uint32_t i = 0; i < cell_count; i++) {
814 w[cells[i].level]++;
815 }
816 }
817
818 return level_count;
819 }
820
821 // euclidean distance computation based on:
822 // https://prideout.net/blog/distance_fields/
823
824 #define square(m_s) ((m_s) * (m_s))
825 #define BIG_VAL 1e20
826
827 /* dt of 1d function using squared distance */
828 static void edt(float *f, int stride, int n) {
829 float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
830 int *v = reinterpret_cast<int *>(&(d[n]));
831 float *z = reinterpret_cast<float *>(&v[n]);
832
833 int k = 0;
834 v[0] = 0;
835 z[0] = -BIG_VAL;
836 z[1] = +BIG_VAL;
837 for (int q = 1; q <= n - 1; q++) {
838 float s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
839 while (s <= z[k]) {
840 k--;
841 s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
842 }
843 k++;
844 v[k] = q;
845
846 z[k] = s;
847 z[k + 1] = +BIG_VAL;
848 }
849
850 k = 0;
851 for (int q = 0; q <= n - 1; q++) {
852 while (z[k + 1] < q) {
853 k++;
854 }
855 d[q] = square(q - v[k]) + f[v[k] * stride];
856 }
857
858 for (int i = 0; i < n; i++) {
859 f[i * stride] = d[i];
860 }
861 }
862
863 #undef square
864
865 Voxelizer::BakeResult Voxelizer::get_sdf_3d_image(Vector<uint8_t> &r_image, BakeStepFunc p_bake_step_function) const {
866 Vector3i octree_size = get_voxel_gi_octree_size();
867
868 uint32_t float_count = octree_size.x * octree_size.y * octree_size.z;
869 float *work_memory = memnew_arr(float, float_count);
870 for (uint32_t i = 0; i < float_count; i++) {
871 work_memory[i] = BIG_VAL;
872 }
873
874 uint32_t y_mult = octree_size.x;
875 uint32_t z_mult = y_mult * octree_size.y;
876
877 //plot solid cells
878 {
879 const Cell *cells = bake_cells.ptr();
880 uint32_t cell_count = bake_cells.size();
881
882 for (uint32_t i = 0; i < cell_count; i++) {
883 if (cells[i].level < cell_subdiv) {
884 continue; //do not care about this level
885 }
886
887 work_memory[cells[i].x + cells[i].y * y_mult + cells[i].z * z_mult] = 0;
888 }
889 }
890
891 //process in each direction
892
893 int bake_total = octree_size.x * 2 + octree_size.y, bake_current = 0;
894
895 //xy->z
896
897 for (int i = 0; i < octree_size.x; i++, bake_current++) {
898 if (p_bake_step_function) {
899 if (p_bake_step_function(bake_current, bake_total)) {
900 memdelete_arr(work_memory);
901 return BAKE_RESULT_CANCELLED;
902 }
903 }
904 for (int j = 0; j < octree_size.y; j++) {
905 edt(&work_memory[i + j * y_mult], z_mult, octree_size.z);
906 }
907 }
908
909 //xz->y
910
911 for (int i = 0; i < octree_size.x; i++, bake_current++) {
912 if (p_bake_step_function) {
913 if (p_bake_step_function(bake_current, bake_total)) {
914 memdelete_arr(work_memory);
915 return BAKE_RESULT_CANCELLED;
916 }
917 }
918 for (int j = 0; j < octree_size.z; j++) {
919 edt(&work_memory[i + j * z_mult], y_mult, octree_size.y);
920 }
921 }
922
923 //yz->x
924 for (int i = 0; i < octree_size.y; i++, bake_current++) {
925 if (p_bake_step_function) {
926 if (p_bake_step_function(bake_current, bake_total)) {
927 memdelete_arr(work_memory);
928 return BAKE_RESULT_CANCELLED;
929 }
930 }
931 for (int j = 0; j < octree_size.z; j++) {
932 edt(&work_memory[i * y_mult + j * z_mult], 1, octree_size.x);
933 }
934 }
935
936 r_image.resize(float_count);
937 {
938 uint8_t *w = r_image.ptrw();
939 for (uint32_t i = 0; i < float_count; i++) {
940 uint32_t d = uint32_t(Math::sqrt(work_memory[i]));
941 if (d == 0) {
942 w[i] = 0;
943 } else {
944 w[i] = MIN(d, 254u) + 1;
945 }
946 }
947 }
948
949 memdelete_arr(work_memory);
950
951 return BAKE_RESULT_OK;
952 }
953
954 #undef BIG_VAL
955
956 void Voxelizer::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx) {
957 if (p_level == cell_subdiv - 1) {
958 Vector3 center = p_aabb.get_center();
959 Transform3D xform;
960 xform.origin = center;
961 xform.basis.scale(p_aabb.size * 0.5);
962 p_multimesh->set_instance_transform(idx, xform);
963 Color col;
964 col = Color(bake_cells[p_idx].albedo[0], bake_cells[p_idx].albedo[1], bake_cells[p_idx].albedo[2]);
965 //Color col = Color(bake_cells[p_idx].emission[0], bake_cells[p_idx].emission[1], bake_cells[p_idx].emission[2]);
966 p_multimesh->set_instance_color(idx, col);
967
968 idx++;
969
970 } else {
971 for (int i = 0; i < 8; i++) {
972 uint32_t child = bake_cells[p_idx].children[i];
973
974 if (child == CHILD_EMPTY || child >= (uint32_t)max_original_cells) {
975 continue;
976 }
977
978 AABB aabb = p_aabb;
979 aabb.size *= 0.5;
980
981 if (i & 1) {
982 aabb.position.x += aabb.size.x;
983 }
984 if (i & 2) {
985 aabb.position.y += aabb.size.y;
986 }
987 if (i & 4) {
988 aabb.position.z += aabb.size.z;
989 }
990
991 _debug_mesh(bake_cells[p_idx].children[i], p_level + 1, aabb, p_multimesh, idx);
992 }
993 }
994 }
995
996 Ref<MultiMesh> Voxelizer::create_debug_multimesh() {
997 Ref<MultiMesh> mm;
998
999 mm.instantiate();
1000
1001 mm->set_transform_format(MultiMesh::TRANSFORM_3D);
1002 mm->set_use_colors(true);
1003 mm->set_instance_count(leaf_voxel_count);
1004
1005 Ref<ArrayMesh> mesh;
1006 mesh.instantiate();
1007
1008 {
1009 Array arr;
1010 arr.resize(Mesh::ARRAY_MAX);
1011
1012 Vector<Vector3> vertices;
1013 Vector<Color> colors;
1014 #define ADD_VTX(m_idx) \
1015 vertices.push_back(face_points[m_idx]); \
1016 colors.push_back(Color(1, 1, 1, 1));
1017
1018 for (int i = 0; i < 6; i++) {
1019 Vector3 face_points[4];
1020
1021 for (int j = 0; j < 4; j++) {
1022 real_t v[3];
1023 v[0] = 1.0;
1024 v[1] = 1 - 2 * ((j >> 1) & 1);
1025 v[2] = v[1] * (1 - 2 * (j & 1));
1026
1027 for (int k = 0; k < 3; k++) {
1028 if (i < 3) {
1029 face_points[j][(i + k) % 3] = v[k];
1030 } else {
1031 face_points[3 - j][(i + k) % 3] = -v[k];
1032 }
1033 }
1034 }
1035
1036 //tri 1
1037 ADD_VTX(0);
1038 ADD_VTX(1);
1039 ADD_VTX(2);
1040 //tri 2
1041 ADD_VTX(2);
1042 ADD_VTX(3);
1043 ADD_VTX(0);
1044 }
1045
1046 arr[Mesh::ARRAY_VERTEX] = vertices;
1047 arr[Mesh::ARRAY_COLOR] = colors;
1048 mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
1049 }
1050
1051 {
1052 Ref<StandardMaterial3D> fsm;
1053 fsm.instantiate();
1054 fsm->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
1055 fsm->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
1056 fsm->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
1057 fsm->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
1058 fsm->set_albedo(Color(1, 1, 1, 1));
1059
1060 mesh->surface_set_material(0, fsm);
1061 }
1062
1063 mm->set_mesh(mesh);
1064
1065 int idx = 0;
1066 _debug_mesh(0, 0, po2_bounds, mm, idx);
1067
1068 return mm;
1069 }
1070
1071 Transform3D Voxelizer::get_to_cell_space_xform() const {
1072 return to_cell_space;
1073 }
1074
1075 Voxelizer::Voxelizer() {
1076 }