-
-
Notifications
You must be signed in to change notification settings - Fork 226
/
voxel_mesher_cubes.cpp
1298 lines (1094 loc) · 38.6 KB
/
voxel_mesher_cubes.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "voxel_mesher_cubes.h"
#include "../../storage/voxel_buffer.h"
#include "../../util/godot/classes/array_mesh.h"
#include "../../util/godot/classes/base_material_3d.h"
#include "../../util/godot/classes/geometry_2d.h"
#include "../../util/godot/classes/image.h"
#include "../../util/godot/classes/shader_material.h"
#include "../../util/godot/core/packed_arrays.h"
#include "../../util/godot/core/string.h"
#include "../../util/math/conv.h"
#include "../../util/profiling.h"
#include "../../util/string/format.h"
// TODO Binary greedy mesher optimization
// https://www.youtube.com/watch?v=qnGoGq7DWMc
namespace zylann::voxel {
namespace {
// Table of indices for vertices of cube faces
// 2-----3
// | |
// | |
// 0-----1
// [axis][front/back][i]
const uint8_t g_indices_lut[3][2][6] = {
// X
{
// Front
{ 0, 3, 2, 0, 1, 3 },
// Back
{ 0, 2, 3, 0, 3, 1 },
},
// Y
{
// Front
{ 0, 2, 3, 0, 3, 1 },
// Back
{ 0, 3, 2, 0, 1, 3 },
},
// Z
{
// Front
{ 0, 3, 2, 0, 1, 3 },
// Back
{ 0, 2, 3, 0, 3, 1 },
}
};
const uint8_t g_face_axes_lut[Vector3iUtil::AXIS_COUNT][2] = {
// X
{ Vector3i::AXIS_Y, Vector3i::AXIS_Z },
// Y
{ Vector3i::AXIS_X, Vector3i::AXIS_Z },
// Z
{ Vector3i::AXIS_X, Vector3i::AXIS_Y }
};
// Not named `Side` because Godot already defines that in global space
enum FaceSide {
FACE_SIDE_FRONT = 0,
FACE_SIDE_BACK,
FACE_SIDE_NONE // Either means there is no face, or it was consumed
};
} // namespace
// Returns:
// 0 if alpha is zero,
// 1 if alpha is neither zero neither max,
// 2 if alpha is max
inline uint8_t get_alpha_index(Color8 c) {
return (c.a == 0xff) + (c.a > 0);
}
template <typename Voxel_T, typename Color_F>
void build_voxel_mesh_as_simple_cubes(
FixedArray<VoxelMesherCubes::Arrays, VoxelMesherCubes::MATERIAL_COUNT> &out_arrays_per_material,
const Span<const Voxel_T> voxel_buffer,
const Vector3i block_size,
Color_F color_func
) {
//
ERR_FAIL_COND(
block_size.x < static_cast<int>(2 * VoxelMesherCubes::PADDING) ||
block_size.y < static_cast<int>(2 * VoxelMesherCubes::PADDING) ||
block_size.z < static_cast<int>(2 * VoxelMesherCubes::PADDING)
);
const Vector3i min_pos = Vector3iUtil::create(VoxelMesherCubes::PADDING);
const Vector3i max_pos = block_size - Vector3iUtil::create(VoxelMesherCubes::PADDING);
const unsigned int row_size = block_size.y;
const unsigned int deck_size = block_size.x * row_size;
// Note: voxel buffers are indexed in ZXY order
FixedArray<uint32_t, Vector3iUtil::AXIS_COUNT> neighbor_offset_d_lut;
neighbor_offset_d_lut[Vector3i::AXIS_X] = block_size.y;
neighbor_offset_d_lut[Vector3i::AXIS_Y] = 1;
neighbor_offset_d_lut[Vector3i::AXIS_Z] = block_size.x * block_size.y;
FixedArray<uint32_t, VoxelMesherCubes::MATERIAL_COUNT> index_offsets;
fill(index_offsets, uint32_t(0));
// For each axis
for (unsigned int za = 0; za < Vector3iUtil::AXIS_COUNT; ++za) {
const unsigned int xa = g_face_axes_lut[za][0];
const unsigned int ya = g_face_axes_lut[za][1];
// For each deck
for (unsigned int d = min_pos[za] - VoxelMesherCubes::PADDING; d < (unsigned int)max_pos[za]; ++d) {
// For each cell of the deck, gather face info
for (unsigned int fy = min_pos[ya]; fy < (unsigned int)max_pos[ya]; ++fy) {
for (unsigned int fx = min_pos[xa]; fx < (unsigned int)max_pos[xa]; ++fx) {
FixedArray<unsigned int, Vector3iUtil::AXIS_COUNT> pos;
pos[xa] = fx;
pos[ya] = fy;
pos[za] = d;
const unsigned int voxel_index = pos[Vector3i::AXIS_Y] + pos[Vector3i::AXIS_X] * row_size +
pos[Vector3i::AXIS_Z] * deck_size;
const Voxel_T raw_color0 = voxel_buffer[voxel_index];
const Voxel_T raw_color1 = voxel_buffer[voxel_index + neighbor_offset_d_lut[za]];
const Color8 color0 = color_func(raw_color0);
const Color8 color1 = color_func(raw_color1);
// TODO Change this
const uint8_t ai0 = get_alpha_index(color0);
const uint8_t ai1 = get_alpha_index(color1);
Color8 color;
FaceSide side;
if (ai0 == ai1) {
continue;
} else if (ai0 > ai1) {
color = color0;
side = FACE_SIDE_BACK;
} else {
color = color1;
side = FACE_SIDE_FRONT;
}
// Commit face to the mesh
const uint8_t material_index = color.a < 255;
VoxelMesherCubes::Arrays &arrays = out_arrays_per_material[material_index];
const int vx0 = fx - VoxelMesherCubes::PADDING;
const int vy0 = fy - VoxelMesherCubes::PADDING;
const int vx1 = vx0 + 1;
const int vy1 = vy0 + 1;
Vector3f v0;
v0[xa] = vx0;
v0[ya] = vy0;
v0[za] = d;
Vector3f v1;
v1[xa] = vx1;
v1[ya] = vy0;
v1[za] = d;
Vector3f v2;
v2[xa] = vx0;
v2[ya] = vy1;
v2[za] = d;
Vector3f v3;
v3[xa] = vx1;
v3[ya] = vy1;
v3[za] = d;
Vector3f n;
n[za] = side == FACE_SIDE_FRONT ? -1 : 1;
// 2-----3
// | |
// | |
// 0-----1
arrays.positions.push_back(v0);
arrays.positions.push_back(v1);
arrays.positions.push_back(v2);
arrays.positions.push_back(v3);
// TODO Any way to not need Color anywhere? It's wasteful
const Color colorf = color;
arrays.colors.push_back(colorf);
arrays.colors.push_back(colorf);
arrays.colors.push_back(colorf);
arrays.colors.push_back(colorf);
arrays.normals.push_back(n);
arrays.normals.push_back(n);
arrays.normals.push_back(n);
arrays.normals.push_back(n);
const unsigned int index_offset = index_offsets[material_index];
CRASH_COND(za >= 3 || side >= 2);
const uint8_t *lut = g_indices_lut[za][side];
for (unsigned int i = 0; i < 6; ++i) {
arrays.indices.push_back(index_offset + lut[i]);
}
index_offsets[material_index] += 4;
}
}
}
}
}
template <typename Voxel_T, typename Color_F>
void build_voxel_mesh_as_greedy_cubes(
FixedArray<VoxelMesherCubes::Arrays, VoxelMesherCubes::MATERIAL_COUNT> &out_arrays_per_material,
const Span<const Voxel_T> voxel_buffer,
const Vector3i block_size,
StdVector<uint8_t> &mask_memory_pool,
Color_F color_func
) {
//
ERR_FAIL_COND(
block_size.x < static_cast<int>(2 * VoxelMesherCubes::PADDING) ||
block_size.y < static_cast<int>(2 * VoxelMesherCubes::PADDING) ||
block_size.z < static_cast<int>(2 * VoxelMesherCubes::PADDING)
);
struct MaskValue {
Voxel_T color;
uint8_t side;
inline bool operator==(const MaskValue &other) const {
return color == other.color && side == other.side;
}
inline bool operator!=(const MaskValue &other) const {
return color != other.color || side != other.side;
}
};
const Vector3i min_pos = Vector3iUtil::create(VoxelMesherCubes::PADDING);
const Vector3i max_pos = block_size - Vector3iUtil::create(VoxelMesherCubes::PADDING);
const unsigned int row_size = block_size.y;
const unsigned int deck_size = block_size.x * row_size;
// Note: voxel buffers are indexed in ZXY order
FixedArray<uint32_t, Vector3iUtil::AXIS_COUNT> neighbor_offset_d_lut;
neighbor_offset_d_lut[Vector3i::AXIS_X] = block_size.y;
neighbor_offset_d_lut[Vector3i::AXIS_Y] = 1;
neighbor_offset_d_lut[Vector3i::AXIS_Z] = block_size.x * block_size.y;
FixedArray<uint32_t, VoxelMesherCubes::MATERIAL_COUNT> index_offsets;
fill(index_offsets, uint32_t(0));
// For each axis
for (unsigned int za = 0; za < Vector3iUtil::AXIS_COUNT; ++za) {
const unsigned int xa = g_face_axes_lut[za][0];
const unsigned int ya = g_face_axes_lut[za][1];
const unsigned int mask_size_x = (max_pos[xa] - min_pos[xa]);
const unsigned int mask_size_y = (max_pos[ya] - min_pos[ya]);
const unsigned int mask_area = mask_size_x * mask_size_y;
// Using the vector as memory pool
mask_memory_pool.resize(mask_area * sizeof(MaskValue));
Span<MaskValue> mask(reinterpret_cast<MaskValue *>(mask_memory_pool.data()), 0, mask_area);
// For each deck
for (unsigned int d = min_pos[za] - VoxelMesherCubes::PADDING; d < (unsigned int)max_pos[za]; ++d) {
// For each cell of the deck, gather face info
for (unsigned int fy = min_pos[ya]; fy < (unsigned int)max_pos[ya]; ++fy) {
for (unsigned int fx = min_pos[xa]; fx < (unsigned int)max_pos[xa]; ++fx) {
FixedArray<unsigned int, Vector3iUtil::AXIS_COUNT> pos;
pos[xa] = fx;
pos[ya] = fy;
pos[za] = d;
const unsigned int voxel_index = pos[Vector3i::AXIS_Y] + pos[Vector3i::AXIS_X] * row_size +
pos[Vector3i::AXIS_Z] * deck_size;
const Voxel_T raw_color0 = voxel_buffer[voxel_index];
const Voxel_T raw_color1 = voxel_buffer[voxel_index + neighbor_offset_d_lut[za]];
const Color8 color0 = color_func(raw_color0);
const Color8 color1 = color_func(raw_color1);
const uint8_t ai0 = get_alpha_index(color0);
const uint8_t ai1 = get_alpha_index(color1);
MaskValue mv;
if (ai0 == ai1) {
mv.side = FACE_SIDE_NONE;
} else if (ai0 > ai1) {
mv.color = raw_color0;
mv.side = FACE_SIDE_BACK;
} else {
mv.color = raw_color1;
mv.side = FACE_SIDE_FRONT;
}
mask[(fx - VoxelMesherCubes::PADDING) + (fy - VoxelMesherCubes::PADDING) * mask_size_x] = mv;
}
}
struct L {
static inline bool is_range_equal(
const Span<MaskValue> &mask,
unsigned int xmin,
unsigned int xmax,
MaskValue v
) {
for (unsigned int x = xmin; x < xmax; ++x) {
if (mask[x] != v) {
return false;
}
}
return true;
}
};
// Greedy quads
for (unsigned int fy = 0; fy < mask_size_y; ++fy) {
for (unsigned int fx = 0; fx < mask_size_x; ++fx) {
const unsigned int mask_index = fx + fy * mask_size_x;
const MaskValue m = mask[mask_index];
if (m.side == FACE_SIDE_NONE) {
continue;
}
// Check if the next faces are the same along X
unsigned int rx = fx + 1;
while (rx < mask_size_x && mask[rx + fy * mask_size_x] == m) {
++rx;
}
// Check if the next rows of faces are the same along Y
unsigned int ry = fy + 1;
while (ry < mask_size_y && L::is_range_equal(mask, fx + ry * mask_size_x, rx + ry * mask_size_x, m)
) {
++ry;
}
// Commit face to the mesh
const Color colorf = color_func(m.color);
const uint8_t material_index = colorf.a < 0.999f;
VoxelMesherCubes::Arrays &arrays = out_arrays_per_material[material_index];
Vector3f v0;
v0[xa] = fx;
v0[ya] = fy;
v0[za] = d;
Vector3f v1;
v1[xa] = rx;
v1[ya] = fy;
v1[za] = d;
Vector3f v2;
v2[xa] = fx;
v2[ya] = ry;
v2[za] = d;
Vector3f v3;
v3[xa] = rx;
v3[ya] = ry;
v3[za] = d;
Vector3f n;
n[za] = m.side == FACE_SIDE_FRONT ? -1 : 1;
// 2-----3
// | |
// | |
// 0-----1
arrays.positions.push_back(v0);
arrays.positions.push_back(v1);
arrays.positions.push_back(v2);
arrays.positions.push_back(v3);
arrays.colors.push_back(colorf);
arrays.colors.push_back(colorf);
arrays.colors.push_back(colorf);
arrays.colors.push_back(colorf);
arrays.normals.push_back(n);
arrays.normals.push_back(n);
arrays.normals.push_back(n);
arrays.normals.push_back(n);
const unsigned int index_offset = index_offsets[material_index];
CRASH_COND(za >= 3 || m.side >= 2);
const uint8_t *lut = g_indices_lut[za][m.side];
for (unsigned int i = 0; i < 6; ++i) {
arrays.indices.push_back(index_offset + lut[i]);
}
index_offsets[material_index] += 4;
for (unsigned int j = fy; j < ry; ++j) {
for (unsigned int i = fx; i < rx; ++i) {
mask[i + j * mask_size_x].side = FACE_SIDE_NONE;
}
}
}
}
}
}
}
template <typename Voxel_T, typename Color_F>
void build_voxel_mesh_as_greedy_cubes_atlased(
FixedArray<VoxelMesherCubes::Arrays, VoxelMesherCubes::MATERIAL_COUNT> &out_arrays_per_material,
VoxelMesherCubes::GreedyAtlasData &out_greedy_atlas_data,
const Span<Voxel_T> voxel_buffer,
const Vector3i block_size,
StdVector<uint8_t> &mask_memory_pool,
Color_F color_func
) {
//
ZN_PROFILE_SCOPE();
ERR_FAIL_COND(
block_size.x < static_cast<int>(2 * VoxelMesherCubes::PADDING) ||
block_size.y < static_cast<int>(2 * VoxelMesherCubes::PADDING) ||
block_size.z < static_cast<int>(2 * VoxelMesherCubes::PADDING)
);
struct MaskValue {
uint8_t side;
uint8_t material_index;
inline bool operator==(const MaskValue &other) const {
return side == other.side && material_index == other.material_index;
}
inline bool operator!=(const MaskValue &other) const {
return side != other.side || material_index != other.material_index;
}
};
out_greedy_atlas_data.clear();
const Vector3i min_pos = Vector3iUtil::create(VoxelMesherCubes::PADDING);
const Vector3i max_pos = block_size - Vector3iUtil::create(VoxelMesherCubes::PADDING);
const unsigned int row_size = block_size.y;
const unsigned int deck_size = block_size.x * row_size;
// Note: voxel buffers are indexed in ZXY order
FixedArray<uint32_t, Vector3iUtil::AXIS_COUNT> neighbor_offset_d_lut;
neighbor_offset_d_lut[Vector3i::AXIS_X] = block_size.y;
neighbor_offset_d_lut[Vector3i::AXIS_Y] = 1;
neighbor_offset_d_lut[Vector3i::AXIS_Z] = block_size.x * block_size.y;
FixedArray<uint32_t, VoxelMesherCubes::MATERIAL_COUNT> index_offsets;
fill(index_offsets, uint32_t(0));
// For each axis
for (unsigned int za = 0; za < Vector3iUtil::AXIS_COUNT; ++za) {
const unsigned int xa = g_face_axes_lut[za][0];
const unsigned int ya = g_face_axes_lut[za][1];
const unsigned int mask_size_x = (max_pos[xa] - min_pos[xa]);
const unsigned int mask_size_y = (max_pos[ya] - min_pos[ya]);
const unsigned int mask_area = mask_size_x * mask_size_y;
// Using the vector as memory pool
const unsigned int mask_memory_size = mask_area * sizeof(MaskValue);
mask_memory_pool.resize(mask_memory_size + mask_area * sizeof(Color8));
// `mask` and `colors` are grids covering one deck
Span<MaskValue> mask(reinterpret_cast<MaskValue *>(mask_memory_pool.data()), 0, mask_area);
Span<Color8> colors(reinterpret_cast<Color8 *>(mask_memory_pool.data() + mask_memory_size), 0, mask_area);
// For each deck
for (unsigned int d = min_pos[za] - VoxelMesherCubes::PADDING; d < (unsigned int)max_pos[za]; ++d) {
// For each cell of the deck, gather face info
for (unsigned int fy = min_pos[ya]; fy < (unsigned int)max_pos[ya]; ++fy) {
for (unsigned int fx = min_pos[xa]; fx < (unsigned int)max_pos[xa]; ++fx) {
FixedArray<unsigned int, Vector3iUtil::AXIS_COUNT> pos;
pos[xa] = fx;
pos[ya] = fy;
pos[za] = d;
const unsigned int voxel_index = pos[Vector3i::AXIS_Y] + pos[Vector3i::AXIS_X] * row_size +
pos[Vector3i::AXIS_Z] * deck_size;
const Voxel_T raw_color0 = voxel_buffer[voxel_index];
const Voxel_T raw_color1 = voxel_buffer[voxel_index + neighbor_offset_d_lut[za]];
const Color8 color0 = color_func(raw_color0);
const Color8 color1 = color_func(raw_color1);
const uint8_t ai0 = get_alpha_index(color0);
const uint8_t ai1 = get_alpha_index(color1);
MaskValue mv;
Color8 color;
if (ai0 == ai1) {
mv.side = FACE_SIDE_NONE;
} else if (ai0 > ai1) {
color = color0;
mv.side = FACE_SIDE_BACK;
mv.material_index = color.a < 0.999f;
} else {
color = color1;
mv.side = FACE_SIDE_FRONT;
mv.material_index = color.a < 0.999f;
}
const unsigned int mask_index =
(fx - VoxelMesherCubes::PADDING) + (fy - VoxelMesherCubes::PADDING) * mask_size_x;
mask[mask_index] = mv;
colors[mask_index] = color;
}
}
struct L {
static inline bool is_range_equal(
const Span<MaskValue> &mask,
unsigned int xmin,
unsigned int xmax,
MaskValue v
) {
for (unsigned int x = xmin; x < xmax; ++x) {
if (mask[x] != v) {
return false;
}
}
return true;
}
};
// Greedy quads
for (unsigned int fy = 0; fy < mask_size_y; ++fy) {
for (unsigned int fx = 0; fx < mask_size_x; ++fx) {
const unsigned int mask_index = fx + fy * mask_size_x;
const MaskValue m = mask[mask_index];
if (m.side == FACE_SIDE_NONE) {
continue;
}
// Check if the next faces are the same along X
unsigned int rx = fx + 1;
while (rx < mask_size_x && mask[rx + fy * mask_size_x] == m) {
++rx;
}
// Check if the next rows of faces are the same along Y
unsigned int ry = fy + 1;
while (ry < mask_size_y && L::is_range_equal(mask, fx + ry * mask_size_x, rx + ry * mask_size_x, m)
) {
++ry;
}
// Commit face to the mesh
const uint8_t material_index = m.material_index;
VoxelMesherCubes::Arrays &arrays = out_arrays_per_material[material_index];
Vector3f v0;
v0[xa] = fx;
v0[ya] = fy;
v0[za] = d;
Vector3f v1;
v1[xa] = rx;
v1[ya] = fy;
v1[za] = d;
Vector3f v2;
v2[xa] = fx;
v2[ya] = ry;
v2[za] = d;
Vector3f v3;
v3[xa] = rx;
v3[ya] = ry;
v3[za] = d;
Vector3f n;
n[za] = m.side == FACE_SIDE_FRONT ? -1 : 1;
// 2-----3
// | |
// | |
// 0-----1
arrays.positions.push_back(v0);
arrays.positions.push_back(v1);
arrays.positions.push_back(v2);
arrays.positions.push_back(v3);
VoxelMesherCubes::GreedyAtlasData::ImageInfo image_info;
image_info.first_vertex_index = arrays.uvs.size();
arrays.uvs.resize(arrays.uvs.size() + 4); // Values will be assigned in a second pass
arrays.normals.push_back(n);
arrays.normals.push_back(n);
arrays.normals.push_back(n);
arrays.normals.push_back(n);
image_info.size_x = rx - fx;
image_info.size_y = ry - fy;
image_info.first_color_index = out_greedy_atlas_data.colors.size();
out_greedy_atlas_data.colors.resize(
out_greedy_atlas_data.colors.size() + image_info.size_x * image_info.size_y
);
const unsigned int index_offset = index_offsets[material_index];
CRASH_COND(za >= 3 || m.side >= 2);
const uint8_t *lut = g_indices_lut[za][m.side];
for (unsigned int i = 0; i < 6; ++i) {
arrays.indices.push_back(index_offset + lut[i]);
}
index_offsets[material_index] += 4;
unsigned int im_i = image_info.first_color_index;
for (unsigned int my = fy; my < ry; ++my) {
const unsigned int i0 = fx + my * mask_size_x;
{
unsigned int i = i0;
for (unsigned int mx = fx; mx < rx; ++mx) {
mask[i].side = FACE_SIDE_NONE;
++i;
}
}
{
unsigned int i = i0;
for (unsigned int mx = fx; mx < rx; ++mx) {
out_greedy_atlas_data.colors[im_i] = colors[i];
++im_i;
++i;
}
}
// TODO Actually that code only missed an offset to its destination for each row?
// Copy colors row by row
// memcpy(out_greedy_atlas_data.colors.data() + image_info.first_color_index,
// colors.data() + i0,
// image_info.size_x * sizeof(Color8));
}
// TODO Optimization: if colors are uniform, we could allocate a shared single pixel instead.
// This would reduce texture size and packing cost
image_info.surface_index = material_index;
out_greedy_atlas_data.images.push_back(image_info);
}
}
}
}
}
Ref<Image> make_greedy_atlas(
const VoxelMesherCubes::GreedyAtlasData &atlas_data,
Span<VoxelMesherCubes::Arrays> surfaces
) {
//
ERR_FAIL_COND_V(atlas_data.images.size() == 0, Ref<Image>());
ZN_PROFILE_SCOPE();
// Pack rectangles
StdVector<Vector2i> result_points;
Vector2i result_size;
{
ZN_PROFILE_SCOPE_NAMED("Packing");
StdVector<Vector2i> sizes;
sizes.resize(atlas_data.images.size());
for (unsigned int i = 0; i < atlas_data.images.size(); ++i) {
const VoxelMesherCubes::GreedyAtlasData::ImageInfo &im = atlas_data.images[i];
sizes[i] = Vector2i(im.size_x, im.size_y);
}
zylann::godot::geometry_2d_make_atlas(to_span(sizes), result_points, result_size);
}
// DEBUG
// Ref<Image> debug_im;
// debug_im.instance();
// debug_im->create(result_size.x, result_size.y, false, Image::FORMAT_RGBA8);
// debug_im->fill(Color(0, 0, 0));
// for (unsigned int i = 0; i < atlas_data.images.size(); ++i) {
// const Vector2i dst_pos = result_points[i];
// const VoxelMesherCubes::GreedyAtlasData::ImageInfo &im = atlas_data.images[i];
// Ref<Image> tmp;
// tmp.instance();
// tmp->create(im.size_x, im.size_y, false, debug_im->get_format());
// tmp->fill(Color(Math::randf(), Math::randf(), Math::randf()));
// debug_im->blit_rect(tmp, Rect2(0, 0, tmp->get_width(), tmp->get_height()), Vector2f(dst_pos));
// }
// debug_im->save_png("debug_atlas_packing.png");
// Update UVs
const Vector2f uv_scale(1.f / float(result_size.x), 1.f / float(result_size.y));
for (unsigned int i = 0; i < atlas_data.images.size(); ++i) {
const VoxelMesherCubes::GreedyAtlasData::ImageInfo &im = atlas_data.images[i];
VoxelMesherCubes::Arrays &surface = surfaces[im.surface_index];
ERR_FAIL_COND_V(im.first_vertex_index + 4 > surface.uvs.size(), Ref<Image>());
const unsigned int vi = im.first_vertex_index;
const Vector2f pos(to_vec2f(result_points[i]));
// 2-----3
// | |
// | |
// 0-----1
surface.uvs[vi] = pos * uv_scale;
surface.uvs[vi + 1] = (pos + Vector2f(im.size_x, 0)) * uv_scale;
surface.uvs[vi + 2] = (pos + Vector2f(0, im.size_y)) * uv_scale;
surface.uvs[vi + 3] = (pos + Vector2f(im.size_x, im.size_y)) * uv_scale;
}
// Create image
PackedByteArray im_data;
im_data.resize(result_size.x * result_size.y * sizeof(Color8));
{
Span<Color8> dst_data = Span<Color8>(reinterpret_cast<Color8 *>(im_data.ptrw()), result_size.x * result_size.y);
// For all rectangles
for (unsigned int i = 0; i < atlas_data.images.size(); ++i) {
const VoxelMesherCubes::GreedyAtlasData::ImageInfo &im = atlas_data.images[i];
const Vector2i dst_pos = result_points[i];
Span<const Color8> src_data =
to_span_from_position_and_size(atlas_data.colors, im.first_color_index, im.size_x * im.size_y);
// Blit rectangle
for (unsigned int y = 0; y < im.size_y; ++y) {
for (unsigned int x = 0; x < im.size_x; ++x) {
const unsigned int src_i = x + y * im.size_x;
const unsigned int dst_i = (dst_pos.x + x) + (dst_pos.y + y) * result_size.x;
dst_data[dst_i] = src_data[src_i];
}
}
}
}
Ref<Image> image = Image::create_from_data(result_size.x, result_size.y, false, Image::FORMAT_RGBA8, im_data);
return image;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VoxelMesherCubes::VoxelMesherCubes() {
set_padding(PADDING, PADDING);
}
VoxelMesherCubes::~VoxelMesherCubes() {}
VoxelMesherCubes::Cache &VoxelMesherCubes::get_tls_cache() {
static thread_local Cache cache;
return cache;
}
void VoxelMesherCubes::build(VoxelMesher::Output &output, const VoxelMesher::Input &input) {
ZN_PROFILE_SCOPE();
const int channel = VoxelBuffer::CHANNEL_COLOR;
Cache &cache = get_tls_cache();
for (unsigned int i = 0; i < cache.arrays_per_material.size(); ++i) {
Arrays &a = cache.arrays_per_material[i];
a.clear();
}
const VoxelBuffer &voxels = input.voxels;
// Iterate 3D padded data to extract voxel faces.
// This is the most intensive job in this class, so all required data should be as fit as possible.
// The buffer we receive MUST be dense (i.e not compressed, and channels allocated).
// That means we can use raw pointers to voxel data inside instead of using the higher-level getters,
// and then save a lot of time.
if (voxels.get_channel_compression(channel) == VoxelBuffer::COMPRESSION_UNIFORM) {
// All voxels have the same type.
// If it's all air, nothing to do. If it's all cubes, nothing to do either.
return;
} else if (voxels.get_channel_compression(channel) != VoxelBuffer::COMPRESSION_NONE) {
// No other form of compression is allowed
ERR_PRINT("VoxelMesherCubes received unsupported voxel compression");
return;
}
Span<const uint8_t> raw_channel;
if (!voxels.get_channel_as_bytes_read_only(channel, raw_channel)) {
// Case supposedly handled before...
ERR_PRINT("Something wrong happened");
return;
}
const Vector3i block_size = voxels.get_size();
const VoxelBuffer::Depth channel_depth = voxels.get_channel_depth(channel);
Parameters params;
{
RWLockRead rlock(_parameters_lock);
params = _parameters;
}
// Note, we don't lock the palette because its data has fixed-size
Ref<Image> atlas_image;
switch (params.color_mode) {
case COLOR_RAW:
switch (channel_depth) {
case VoxelBuffer::DEPTH_8_BIT:
if (params.greedy_meshing) {
build_voxel_mesh_as_greedy_cubes(
cache.arrays_per_material,
raw_channel,
block_size,
cache.mask_memory_pool,
Color8::from_u8
);
} else {
build_voxel_mesh_as_simple_cubes(
cache.arrays_per_material, raw_channel, block_size, Color8::from_u8
);
}
break;
case VoxelBuffer::DEPTH_16_BIT:
if (params.greedy_meshing) {
build_voxel_mesh_as_greedy_cubes(
cache.arrays_per_material,
raw_channel.reinterpret_cast_to<const uint16_t>(),
block_size,
cache.mask_memory_pool,
Color8::from_u16
);
} else {
build_voxel_mesh_as_simple_cubes(
cache.arrays_per_material,
raw_channel.reinterpret_cast_to<const uint16_t>(),
block_size,
Color8::from_u16
);
}
break;
case VoxelBuffer::DEPTH_32_BIT:
if (params.greedy_meshing) {
build_voxel_mesh_as_greedy_cubes(
cache.arrays_per_material,
raw_channel.reinterpret_cast_to<const uint32_t>(),
block_size,
cache.mask_memory_pool,
Color8::from_u32
);
} else {
build_voxel_mesh_as_simple_cubes(
cache.arrays_per_material,
raw_channel.reinterpret_cast_to<const uint32_t>(),
block_size,
Color8::from_u32
);
}
break;
default:
ERR_PRINT("Unsupported voxel depth");
return;
}
break;
case COLOR_MESHER_PALETTE: {
ERR_FAIL_COND_MSG(params.palette.is_null(), "Palette mode is used but no palette was specified");
struct GetColorFromPalette {
VoxelColorPalette &palette;
Color8 operator()(uint64_t i) const {
// Note: even though this code may run in a thread, I'm not locking the palette at all because
// it stores colors in a fixed-size array, and reading the wrong color won't cause any serious
// problem. It's not supposed to change often in game anyways. If it does, better use shader mode.
return palette.get_color8(i);
}
};
const GetColorFromPalette get_color_from_palette{ **params.palette };
switch (channel_depth) {
case VoxelBuffer::DEPTH_8_BIT:
if (params.greedy_meshing) {
if (params.store_colors_in_texture) {
build_voxel_mesh_as_greedy_cubes_atlased(
cache.arrays_per_material,
cache.greedy_atlas_data,
raw_channel,
block_size,
cache.mask_memory_pool,
get_color_from_palette
);
atlas_image =
make_greedy_atlas(cache.greedy_atlas_data, to_span(cache.arrays_per_material));
} else {
build_voxel_mesh_as_greedy_cubes(
cache.arrays_per_material,
raw_channel,
block_size,
cache.mask_memory_pool,
get_color_from_palette
);
}
} else {
build_voxel_mesh_as_simple_cubes(
cache.arrays_per_material, raw_channel, block_size, get_color_from_palette
);
}
break;
case VoxelBuffer::DEPTH_16_BIT:
if (params.greedy_meshing) {
build_voxel_mesh_as_greedy_cubes(
cache.arrays_per_material,
raw_channel.reinterpret_cast_to<const uint16_t>(),
block_size,
cache.mask_memory_pool,
get_color_from_palette
);
} else {
build_voxel_mesh_as_simple_cubes(
cache.arrays_per_material,
raw_channel.reinterpret_cast_to<const uint16_t>(),
block_size,
get_color_from_palette
);
}
break;
default:
ERR_PRINT("Unsupported voxel depth");
return;
}
} break;
case COLOR_SHADER_PALETTE: {
ERR_FAIL_COND_MSG(params.palette.is_null(), "Palette mode is used but no palette was specified");
struct GetIndexFromPalette {
VoxelColorPalette &palette;
Color8 operator()(uint64_t i) const {
// Still providing alpha because it allows to separate the opaque and transparent surfaces
return Color8(i, 0, 0, palette.get_color8(i).a);
}
};
const GetIndexFromPalette get_index_from_palette{ **params.palette };
switch (channel_depth) {
case VoxelBuffer::DEPTH_8_BIT:
if (params.greedy_meshing) {
build_voxel_mesh_as_greedy_cubes(
cache.arrays_per_material,
raw_channel,
block_size,
cache.mask_memory_pool,
get_index_from_palette
);
} else {
build_voxel_mesh_as_simple_cubes(
cache.arrays_per_material, raw_channel, block_size, get_index_from_palette
);
}
break;
case VoxelBuffer::DEPTH_16_BIT:
if (params.greedy_meshing) {
build_voxel_mesh_as_greedy_cubes(
cache.arrays_per_material,
raw_channel.reinterpret_cast_to<const uint16_t>(),
block_size,
cache.mask_memory_pool,
get_index_from_palette
);
} else {
build_voxel_mesh_as_simple_cubes(
cache.arrays_per_material,
raw_channel.reinterpret_cast_to<const uint16_t>(),
block_size,
get_index_from_palette
);
}
break;
default:
ERR_PRINT("Unsupported voxel depth");
return;
}
} break;
default:
CRASH_NOW();
break;
}
if (input.lod_index > 0) {
// TODO This is very crude LOD, there will be cracks at the borders.
// One way would be to not cull faces on chunk borders if any neighbor face is air
const float lod_scale = 1 << input.lod_index;
for (unsigned int material_index = 0; material_index < cache.arrays_per_material.size(); ++material_index) {
Arrays &arrays = cache.arrays_per_material[material_index];
for (unsigned int i = 0; i < arrays.positions.size(); ++i) {
arrays.positions[i] *= lod_scale;
}
}
}
// TODO We could return a single byte array and use Mesh::add_surface down the line?