-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMeshDecimationTools.cpp
More file actions
3584 lines (2746 loc) · 133 KB
/
Copy pathMeshDecimationTools.cpp
File metadata and controls
3584 lines (2746 loc) · 133 KB
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 "MeshDecimationTools.h"
//
// References:
// - Michael Garland, Paul S. Heckbert. 1997. Surface Simplification Using Quadric Error Metrics.
// - Thomas Wang. 1997. Integer Hash Function.
// - Hugues Hoppe. 1999. New Quadric Metric for Simplifying Meshes with Appearance Attributes.
// - Hugues Hoppe, Steve Marschner. 2000. Efficient Minimization of New Quadric Metric for Simplifying Meshes with Appearance Attributes.
// - Matthias Teschner, Bruno Heidelberger, Matthias Muller, Danat Pomeranets, Markus Gross. 2003. Optimized Spatial Hashing for Collision Detection of Deformable Objects.
// - Brian Karis, Rune Stubbe, Graham Wihlidal. 2021. Nanite A Deep Dive.
// - HSUEH-TI DEREK LIU, XIAOTING ZHANG, CEM YUKSEL. 2024. Simplifying Triangle Meshes in the Wild.
// - Arseny Kapoulkine. 2025. Meshoptimizer library. https://github.com/zeux/meshoptimizer. See license in THIRD_PARTY_LICENSES.md.
//
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if !defined(MDT_CACHE_LINE_SIZE)
#define MDT_CACHE_LINE_SIZE 64
#endif // !defined(MDT_CACHE_LINE_SIZE)
#if defined(_MSC_VER)
#define never_inline_function __declspec(noinline)
#define always_inline_function __forceinline
#else // !defined(_MSC_VER)
#define never_inline_function
#define always_inline_function
#endif // !defined(_MSC_VER)
#if !defined(MDT_UNUSED_VARIABLE)
#define MDT_UNUSED_VARIABLE(name) (void)(name)
#endif // !defined(MDT_UNUSED_VARIABLE)
#define compile_const constexpr static const
namespace MeshDecimationTools
{
using u8 = uint8_t;
using u32 = uint32_t;
using u64 = uint64_t;
static_assert(sizeof(u8) == 1, "Invalid u8 size.");
static_assert(sizeof(u32) == 4, "Invalid u32 size.");
static_assert(sizeof(u64) == 8, "Invalid u64 size.");
compile_const u32 u32_max = (u32)0xFFFF'FFFF;
compile_const u64 u64_max = (u64)0xFFFF'FFFF'FFFF'FFFF;
using Vector3 = MdtVector3;
compile_const u32 meshlet_max_vertex_count = MDT_MAX_MESHLET_VERTEX_COUNT;
compile_const u32 meshlet_max_face_degree = 3;
compile_const u32 meshlet_max_face_count = MDT_MAX_MESHLET_FACE_COUNT;
compile_const u32 meshlet_min_face_count = meshlet_max_face_count / 4;
compile_const float discontinuous_meshlet_max_expansion = 2.f; // Sqrt of the maximum AABB expansion when adding a discontinuous face to a meshlet.
compile_const u32 meshlet_group_max_meshlet_count = MDT_MESHLET_GROUP_SIZE;
compile_const u32 meshlet_group_min_meshlet_count = meshlet_group_max_meshlet_count / 2;
compile_const float discontinuous_meshlet_group_max_expansion = 4.f; // Sqrt of the maximum AABB expansion when adding a discontinuous meshlet to a group.
compile_const u32 continuous_lod_max_levels_of_details = MDT_MAX_CLOD_LEVEL_COUNT;
compile_const float default_geometric_error_weight = 0.5f;
compile_const float default_attribute_error_weight = 1.f;
// Based on [Kapoulkine 2025] and [Teschner 2003].
static u32 ComputePositionHash(const Vector3& v) {
const u32* key = (const u32*)&v;
u32 x = key[0];
u32 y = key[1];
u32 z = key[2];
// Replace negative zero with zero.
x = (x == 0x80000000) ? 0 : x;
y = (y == 0x80000000) ? 0 : y;
z = (z == 0x80000000) ? 0 : z;
// Scramble bits to make sure that integer coordinates have entropy in lower bits.
x ^= x >> 17;
y ^= y >> 17;
z ^= z >> 17;
// Optimized Spatial Hashing for Collision Detection of Deformable Objects.
return (x * 73856093) ^ (y * 19349663) ^ (z * 83492791);
}
// Based on [Wang 1997]. 64 bit to 32 bit Hash Functions.
static u32 ComputeEdgeKeyHash(u64 key) {
key = (~key) + (key << 18); // key = (key << 18) - key - 1;
key = key ^ (key >> 31);
key = key * 21; // key = (key + (key << 2)) + (key << 4);
key = key ^ (key >> 11);
key = key + (key << 6);
key = key ^ (key >> 22);
return (u32)key;
}
enum struct ElementType : u32 {
Vertex = 0,
Edge = 1,
Face = 2,
Count
};
struct CornerID {
u32 index = 0;
};
struct FaceID {
u32 index = 0;
compile_const ElementType element_type = ElementType::Face;
};
struct VertexID {
u32 index = 0;
compile_const ElementType element_type = ElementType::Vertex;
};
struct EdgeID {
u32 index = 0;
compile_const ElementType element_type = ElementType::Edge;
};
struct AttributesID {
u32 index = 0;
};
struct Face {
CornerID corner_list_base; // Corner list around a face.
u32 geometry_index = 0;
};
struct Edge {
VertexID vertex_0;
VertexID vertex_1;
CornerID corner_list_base; // Corner list around an edge.
};
struct CornerListIDs {
CornerID next;
CornerID prev;
};
struct Corner {
CornerListIDs corner_list_around[(u32)ElementType::Count];
FaceID face_id;
EdgeID edge_id;
VertexID vertex_id;
AttributesID attributes_id;
};
static_assert(sizeof(Corner) == 40, "Invalid Corner size.");
struct alignas(16) Vertex {
Vector3 position;
CornerID corner_list_base; // Corner list around a vertex.
};
struct alignas(MDT_CACHE_LINE_SIZE) MeshView {
Face* faces = nullptr;
Edge* edges = nullptr;
Vertex* vertices = nullptr;
Corner* corners = nullptr;
float* attributes = nullptr;
u32 face_count = 0;
u32 edge_count = 0;
u32 vertex_count = 0;
u32 corner_count = 0;
u32 attribute_count = 0;
u32 attribute_stride_dwords = 0;
Face& operator[] (FaceID face_id) { return faces[face_id.index]; }
Edge& operator[] (EdgeID edge_id) { return edges[edge_id.index]; }
Vertex& operator[] (VertexID vertex_id) { return vertices[vertex_id.index]; }
Corner& operator[] (CornerID corner_id) { return corners[corner_id.index]; }
float* operator[] (AttributesID attributes_id) { return attributes + attributes_id.index * attribute_stride_dwords; }
};
static_assert(sizeof(MeshView) == 64, "Invalid MeshView size.");
static u64 PackEdgeKey(VertexID vertex_id_0, VertexID vertex_id_1) {
// Always pack VertexIDs in ascending order to ensure that PackEdgeKey(A, B) == PackEdgeKey(B, A) and they hash to the same value.
return vertex_id_1.index > vertex_id_0.index ?
((u64)vertex_id_1.index << 32) | (u64)vertex_id_0.index :
((u64)vertex_id_0.index << 32) | (u64)vertex_id_1.index;
}
static u64 LoadEdgeKey(const Edge& edge) {
return (u64)edge.vertex_0.index | ((u64)edge.vertex_1.index << 32);
}
template<typename ElementID> ElementID GetElementID(const Corner& corner);
template<> always_inline_function VertexID GetElementID<VertexID>(const Corner& corner) { return corner.vertex_id; }
template<> always_inline_function EdgeID GetElementID<EdgeID>(const Corner& corner) { return corner.edge_id; }
template<> always_inline_function FaceID GetElementID<FaceID>(const Corner& corner) { return corner.face_id; }
template<typename ElementID>
static void CornerListInsert(MeshView mesh, ElementID element_id, CornerID new_corner_id) {
auto& corner = mesh[new_corner_id];
auto& element = mesh[element_id];
compile_const u32 element_type = (u32)ElementID::element_type;
if (element.corner_list_base.index == u32_max) {
element.corner_list_base = new_corner_id;
corner.corner_list_around[element_type].prev = new_corner_id;
corner.corner_list_around[element_type].next = new_corner_id;
} else {
auto& existing_corner = mesh[element.corner_list_base];
mesh[existing_corner.corner_list_around[element_type].prev].corner_list_around[element_type].next = new_corner_id;
corner.corner_list_around[element_type].prev = existing_corner.corner_list_around[element_type].prev;
corner.corner_list_around[element_type].next = element.corner_list_base;
existing_corner.corner_list_around[element_type].prev = new_corner_id;
}
}
template<typename ElementID>
static bool CornerListRemove(MeshView mesh, CornerID corner_id) {
compile_const u32 element_type = (u32)ElementID::element_type;
auto& corner = mesh[corner_id];
auto prev_corner_id = corner.corner_list_around[element_type].prev;
auto next_corner_id = corner.corner_list_around[element_type].next;
mesh[next_corner_id].corner_list_around[element_type].prev = prev_corner_id;
mesh[prev_corner_id].corner_list_around[element_type].next = next_corner_id;
// Remove the element if it lost it's last corner.
bool is_last_reference = (prev_corner_id.index == corner_id.index);
auto new_corner_list_base = is_last_reference ? CornerID{ u32_max } : prev_corner_id;
mesh[GetElementID<ElementID>(corner)].corner_list_base = new_corner_list_base;
corner.corner_list_around[element_type].prev.index = u32_max;
corner.corner_list_around[element_type].next.index = u32_max;
return is_last_reference;
}
// Iterate linked list around a given element type starting with the base corner id.
// Removal while iterating is allowed.
template<typename ElementID, typename Lambda>
static void IterateCornerList(MeshView mesh, CornerID corner_list_base, Lambda&& lambda) {
auto& element = mesh[GetElementID<ElementID>(mesh[corner_list_base])];
auto current_corner_id = corner_list_base;
do {
auto next_corner_id = mesh[current_corner_id].corner_list_around[(u32)ElementID::element_type].next;
lambda(current_corner_id);
current_corner_id = next_corner_id;
} while (current_corner_id.index != corner_list_base.index && element.corner_list_base.index != u32_max);
}
always_inline_function static void PatchReferencesToElement(MeshView mesh, VertexID element_0, VertexID element_1, CornerID corner_id) {
mesh[corner_id].vertex_id = element_0;
// TODO: This can be iteration over just incoming and outgoing edges of a corner.
IterateCornerList<FaceID>(mesh, corner_id, [&](CornerID corner_id) {
auto& edge = mesh[mesh[corner_id].edge_id];
if (edge.vertex_0.index == element_1.index) edge.vertex_0 = element_0;
if (edge.vertex_1.index == element_1.index) edge.vertex_1 = element_0;
MDT_ASSERT(edge.vertex_0.index != edge.vertex_1.index);
});
}
always_inline_function static void PatchReferencesToElement(MeshView mesh, EdgeID element_0, EdgeID /*element_1*/, CornerID corner_id) {
mesh[corner_id].edge_id = element_0;
}
// Merge linked lists around element_0 and element_1 and remove element_1.
// Patch up references to element_1 with a reference to element_0.
template<typename ElementID>
static ElementID CornerListMerge(MeshView mesh, ElementID element_0, ElementID element_1) {
auto base_id_0 = mesh[element_0].corner_list_base;
auto base_id_1 = mesh[element_1].corner_list_base;
compile_const ElementType element_type_t = ElementID::element_type;
compile_const u32 element_type = (u32)element_type_t;
auto remaining_element_id = ElementID{ u32_max };
if (base_id_0.index != u32_max && base_id_1.index != u32_max) {
IterateCornerList<ElementID>(mesh, base_id_1, [&](CornerID corner_id) {
PatchReferencesToElement(mesh, element_0, element_1, corner_id);
});
auto base_id_0_prev = mesh[base_id_0].corner_list_around[element_type].prev;
auto base_id_1_prev = mesh[base_id_1].corner_list_around[element_type].prev;
mesh[base_id_0].corner_list_around[element_type].prev = base_id_1_prev;
mesh[base_id_1_prev].corner_list_around[element_type].next = base_id_0;
mesh[base_id_1].corner_list_around[element_type].prev = base_id_0_prev;
mesh[base_id_0_prev].corner_list_around[element_type].next = base_id_1;
mesh[element_1].corner_list_base.index = u32_max;
remaining_element_id = element_0;
} else if (base_id_0.index != u32_max) {
remaining_element_id = element_0;
} else if (base_id_1.index != u32_max) {
remaining_element_id = element_1;
}
return remaining_element_id;
}
struct Allocator {
compile_const u32 max_memory_block_count = 48;
MdtAllocatorCallbacks callbacks;
u32 memory_block_count = 0;
void* memory_blocks[max_memory_block_count] = {};
};
static void* AllocateMemoryBlock(Allocator& allocator, void* old_memory_block, u64 size_bytes) {
MDT_ASSERT(old_memory_block != nullptr || allocator.memory_block_count < Allocator::max_memory_block_count);
MDT_ASSERT(old_memory_block == nullptr || allocator.memory_block_count > 0);
MDT_ASSERT(old_memory_block == nullptr || allocator.memory_blocks[allocator.memory_block_count - 1] == old_memory_block);
void* memory_block = allocator.callbacks.reallocate(old_memory_block, size_bytes, allocator.callbacks.user_data);
u32 memory_block_index = old_memory_block ? allocator.memory_block_count - 1 : allocator.memory_block_count++;
allocator.memory_blocks[memory_block_index] = memory_block;
return memory_block;
}
static void InitializeAllocator(Allocator& allocator, const MdtAllocatorCallbacks* callbacks) {
if (callbacks) {
allocator.callbacks = *callbacks;
} else {
allocator.callbacks.reallocate = [](void* old_memory_block, u64 size_bytes, void*) {
void* result = nullptr;
if (size_bytes == 0) {
free(old_memory_block);
} else {
result = realloc(old_memory_block, size_bytes);
}
return result;
};
}
}
static void AllocatorFreeMemoryBlocks(Allocator& allocator, u32 last_memory_block_index = 0) {
for (u32 i = allocator.memory_block_count; i > last_memory_block_index; i -= 1) {
allocator.callbacks.reallocate(allocator.memory_blocks[i - 1], 0, allocator.callbacks.user_data);
}
allocator.memory_block_count = last_memory_block_index;
}
static u32 AllocatorFindMemoryBlock(Allocator& allocator, void* old_memory_block) {
for (u32 i = allocator.memory_block_count; i > 0; i -= 1) {
if (allocator.memory_blocks[i - 1] == old_memory_block) return i - 1;
}
return u32_max;
}
#define DECLARE_ARRAY_OPERATORS() \
T& operator[] (u32 index) { MDT_ASSERT(index < count); return data[index]; } \
const T& operator[] (u32 index) const { MDT_ASSERT(index < count); return data[index]; } \
\
T* begin() { return data; } \
T* end() { return data + count; } \
const T* begin() const { return data; } \
const T* end() const { return data + count; }
// Should be used only with simple types.
template<typename T>
struct Array {
using ValueType = T;
T* data = nullptr;
u32 count = 0;
u32 capacity = 0;
DECLARE_ARRAY_OPERATORS()
};
static_assert(sizeof(Array<u32>) == 16, "Invalid Array<T> size.");
template<typename T, u32 compile_time_capacity>
struct FixedSizeArray {
using ValueType = T;
compile_const u32 capacity = compile_time_capacity;
T data[capacity] = {};
u32 count = 0;
DECLARE_ARRAY_OPERATORS()
};
static_assert(sizeof(FixedSizeArray<u32, 1>) == 8, "Invalid FixedSizeArray<T, c> size.");
template<typename T>
struct ArrayView {
using ValueType = T;
T* data = nullptr;
u32 count = 0;
DECLARE_ARRAY_OPERATORS()
};
static_assert(sizeof(ArrayView<u32>) == 16, "Invalid ArrayView<T> size.");
#undef DECLARE_ARRAY_OPERATORS
static u32 ArrayComputeNewCapacity(u32 old_capacity, u32 required_capacity = 0) {
u32 new_capacity = old_capacity ? (old_capacity + old_capacity / 2) : 16;
return new_capacity > required_capacity ? new_capacity : required_capacity;
}
template<typename T>
static void ArrayReserve(Array<T>& array, Allocator& allocator, u32 capacity) {
if (array.capacity >= capacity) return;
array.data = (T*)AllocateMemoryBlock(allocator, array.data, capacity * sizeof(T));
array.capacity = capacity;
}
template<typename T>
static void ArrayResize(Array<T>& array, Allocator& allocator, u32 new_count) { // Doesn't initialize new elements.
ArrayReserve(array, allocator, new_count);
array.count = new_count;
}
template<typename T>
static void ArrayResizeMemset(Array<T>& array, Allocator& allocator, u32 new_count, u8 pattern) { // Fills new elements with a byte pattern.
ArrayResize(array, allocator, new_count);
memset(array.data, pattern, new_count * sizeof(T));
}
template<typename ArrayT>
always_inline_function static void ArrayAppend(ArrayT& array, const typename ArrayT::ValueType& value) {
MDT_ASSERT(array.count < array.capacity);
array.data[array.count++] = value;
}
template<typename T>
never_inline_function static void ArrayGrow(Array<T>& array, Allocator& allocator, u32 new_capacity) {
u32 old_memory_block_index = AllocatorFindMemoryBlock(allocator, array.data);
void* memory_block = allocator.callbacks.reallocate(array.data, new_capacity * sizeof(T), allocator.callbacks.user_data);
u32 memory_block_index = old_memory_block_index != u32_max ? old_memory_block_index : allocator.memory_block_count++;
allocator.memory_blocks[memory_block_index] = memory_block;
array.data = (T*)memory_block;
array.capacity = new_capacity;
}
template<typename T>
static void ArrayAppendMaybeGrow(Array<T>& array, Allocator& allocator, const T& value) {
if (array.count >= array.capacity) ArrayGrow(array, allocator, ArrayComputeNewCapacity(array.capacity, array.count + 1));
array.data[array.count++] = value;
}
template<typename ArrayT>
static void ArrayEraseSwap(ArrayT& array, u32 index) {
MDT_ASSERT(index < array.count);
array.data[index] = array.data[array.count - 1];
array.count -= 1;
}
template<typename ArrayT>
static typename ArrayT::ValueType& ArrayLastElement(ArrayT& array) {
MDT_ASSERT(array.count != 0);
return array.data[array.count - 1];
}
template<typename ArrayT>
static ArrayView<typename ArrayT::ValueType> CreateArrayView(ArrayT array, u32 begin_index, u32 end_index) {
return { array.data + begin_index, end_index - begin_index };
}
template<typename ArrayT>
static ArrayView<typename ArrayT::ValueType> CreateArrayView(ArrayT& array) {
return { array.data, array.count };
}
//
// Based on [Kapoulkine 2025].
// See also https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/
//
struct VertexHashTable {
Array<VertexID> vertex_ids;
};
static VertexID HashTableAddOrFind(VertexHashTable& table, Array<Vertex>& vertices, const Vector3& position) {
u32 table_size = table.vertex_ids.count;
u32 mod_mask = table_size - 1u;
u32 hash = ComputePositionHash(position);
u32 index = (hash & mod_mask);
for (u32 i = 0; i <= mod_mask; i += 1) {
auto vertex_id = table.vertex_ids[index];
if (vertex_id.index == u32_max) {
auto new_vertex_id = VertexID{ vertices.count };
table.vertex_ids[index] = new_vertex_id;
Vertex vertex;
vertex.position = position;
vertex.corner_list_base.index = u32_max;
ArrayAppend(vertices, vertex);
return new_vertex_id;
}
auto existing_position = vertices[vertex_id.index].position;
if (existing_position.x == position.x && existing_position.y == position.y && existing_position.z == position.z) {
return vertex_id;
}
index = (index + i + 1) & mod_mask;
}
return VertexID{ u32_max };
}
struct EdgeHashTable {
Array<EdgeID> edge_ids;
};
static EdgeID HashTableAddOrFind(EdgeHashTable& table, Array<Edge>& edges, u64 edge_key) {
u32 table_size = table.edge_ids.count;
u32 mod_mask = table_size - 1u;
u32 hash = ComputeEdgeKeyHash(edge_key);
u32 index = (hash & mod_mask);
for (u32 i = 0; i <= mod_mask; i += 1) {
auto edge_id = table.edge_ids[index];
if (edge_id.index == u32_max) {
auto new_edge_id = EdgeID{ edges.count };
table.edge_ids[index] = new_edge_id;
Edge edge;
edge.vertex_0.index = (u32)(edge_key >> 0);
edge.vertex_1.index = (u32)(edge_key >> 32);
edge.corner_list_base.index = u32_max;
ArrayAppend(edges, edge);
return new_edge_id;
}
if (LoadEdgeKey(edges[edge_id.index]) == edge_key) {
return edge_id;
}
index = (index + i + 1) & mod_mask;
}
return EdgeID{ u32_max };
}
struct EdgeDuplicateMap {
struct KeyValue {
u64 edge_key;
EdgeID edge_id;
};
KeyValue* keys_values = nullptr;
u32 capacity = 0;
u32 count = 0;
KeyValue* begin() { return keys_values; }
KeyValue* end() { return keys_values + capacity; }
};
static void HashTableClear(EdgeDuplicateMap& table) {
memset(table.keys_values, 0xFF, table.capacity * sizeof(EdgeDuplicateMap::KeyValue));
table.count = 0;
}
static EdgeID HashTableAddOrFind(EdgeDuplicateMap& table, Allocator& heap_allocator, u64 edge_key, EdgeID edge_id);
never_inline_function static void HashTableGrow(EdgeDuplicateMap& table, Allocator& heap_allocator, u32 new_capacity) {
auto* old_keys_values = table.keys_values;
u32 old_memory_block_index = AllocatorFindMemoryBlock(heap_allocator, old_keys_values);
u32 old_capacity = table.capacity;
void* memory_block = heap_allocator.callbacks.reallocate(nullptr, new_capacity * sizeof(EdgeDuplicateMap::KeyValue), heap_allocator.callbacks.user_data);
u32 memory_block_index = old_memory_block_index != u32_max ? old_memory_block_index : heap_allocator.memory_block_count++;
heap_allocator.memory_blocks[memory_block_index] = memory_block;
table.keys_values = (EdgeDuplicateMap::KeyValue*)memory_block;
table.capacity = new_capacity;
HashTableClear(table);
for (auto key_value: ArrayView<EdgeDuplicateMap::KeyValue>{ old_keys_values, old_capacity }) {
if (key_value.edge_key != u64_max) HashTableAddOrFind(table, heap_allocator, key_value.edge_key, key_value.edge_id);
}
heap_allocator.callbacks.reallocate(old_keys_values, 0, heap_allocator.callbacks.user_data);
}
static EdgeID HashTableAddOrFind(EdgeDuplicateMap& table, Allocator& heap_allocator, u64 edge_key, EdgeID edge_id) {
u32 table_size = table.capacity;
compile_const u32 load_factor_percent = 85;
if ((table.count + 1) * 100 >= table_size * load_factor_percent) {
HashTableGrow(table, heap_allocator, table.capacity * 2);
table_size = table.capacity;
}
u32 mod_mask = table_size - 1u;
u32 hash = ComputeEdgeKeyHash(edge_key);
u32 index = (hash & mod_mask);
for (u32 i = 0; i <= mod_mask; i += 1) {
auto key_value = table.keys_values[index];
if (key_value.edge_key == u64_max) {
table.count += 1;
table.keys_values[index] = { edge_key, edge_id };
return edge_id;
}
if (key_value.edge_key == edge_key) {
return key_value.edge_id;
}
index = (index + i + 1) & mod_mask;
}
return EdgeID{ u32_max };
}
static u32 ComputeHashTableSize(u32 max_element_count) {
u32 hash_table_size = 1;
while (hash_table_size < max_element_count + max_element_count / 4) {
hash_table_size = hash_table_size * 2;
}
return hash_table_size;
}
static MeshView BuildEditableMesh(Allocator& allocator, const MdtTriangleGeometryDesc* geometry_descs, u32 geometry_desc_count, u32 vertex_stride_bytes) {
u32 vertex_stride_dwords = vertex_stride_bytes / sizeof(u32);
u32 attribute_stride_dwords = vertex_stride_dwords - 3;
if (vertex_stride_dwords < 3 || attribute_stride_dwords > MDT_MAX_ATTRIBUTE_STRIDE_DWORDS) return {};
u32 vertices_count = 0;
u32 indices_count = 0;
for (u32 geometry_index = 0; geometry_index < geometry_desc_count; geometry_index += 1) {
auto& desc = geometry_descs[geometry_index];
vertices_count += desc.vertex_count;
indices_count += desc.index_count;
}
u32 triangle_count = (indices_count / 3);
Array<Face> faces;
Array<Edge> edges;
Array<Vertex> vertices;
Array<Corner> corners;
Array<float> attributes;
ArrayReserve(vertices, allocator, vertices_count);
ArrayResize(corners, allocator, indices_count);
ArrayReserve(faces, allocator, triangle_count);
ArrayReserve(edges, allocator, indices_count);
ArrayResize(attributes, allocator, vertices_count * attribute_stride_dwords);
MeshView mesh;
mesh.faces = faces.data;
mesh.edges = edges.data;
mesh.vertices = vertices.data;
mesh.corners = corners.data;
mesh.attributes = attributes.data;
mesh.face_count = faces.capacity;
mesh.edge_count = edges.capacity;
mesh.vertex_count = vertices.capacity;
mesh.corner_count = corners.count;
mesh.attribute_count = vertices_count;
mesh.attribute_stride_dwords = attribute_stride_dwords;
u32 allocator_high_water = allocator.memory_block_count;
Array<VertexID> src_vertex_index_to_vertex_id;
ArrayResize(src_vertex_index_to_vertex_id, allocator, vertices_count);
VertexHashTable vertex_table;
ArrayResizeMemset(vertex_table.vertex_ids, allocator, ComputeHashTableSize(vertices_count), 0xFF);
EdgeHashTable edge_table;
ArrayResizeMemset(edge_table.edge_ids, allocator, ComputeHashTableSize(indices_count), 0xFF);
for (u32 geometry_index = 0, base_vertex_index = 0; geometry_index < geometry_desc_count; geometry_index += 1) {
auto& desc = geometry_descs[geometry_index];
for (u32 geometry_vertex_index = 0; geometry_vertex_index < desc.vertex_count; geometry_vertex_index += 1) {
u32 vertex_index = base_vertex_index + geometry_vertex_index;
auto* vertex = &desc.vertices[geometry_vertex_index * vertex_stride_dwords];
memcpy(mesh[AttributesID{ vertex_index }], vertex + 3, attribute_stride_dwords * sizeof(u32));
auto vertex_id = HashTableAddOrFind(vertex_table, vertices, *(Vector3*)vertex);
src_vertex_index_to_vertex_id[vertex_index] = vertex_id;
}
base_vertex_index += desc.vertex_count;
}
mesh.vertex_count = vertices.count;
for (u32 geometry_index = 0, base_vertex_index = 0; geometry_index < geometry_desc_count; geometry_index += 1) {
auto& desc = geometry_descs[geometry_index];
u32 geometry_triangle_count = (desc.index_count / 3);
for (u32 triangle_index = 0; triangle_index < geometry_triangle_count; triangle_index += 1) {
u32 indices[3] = {
base_vertex_index + desc.indices[triangle_index * 3 + 0],
base_vertex_index + desc.indices[triangle_index * 3 + 1],
base_vertex_index + desc.indices[triangle_index * 3 + 2],
};
VertexID vertex_ids[3] = {
src_vertex_index_to_vertex_id[indices[0]],
src_vertex_index_to_vertex_id[indices[1]],
src_vertex_index_to_vertex_id[indices[2]],
};
u64 edge_keys[3] = {
PackEdgeKey(vertex_ids[0], vertex_ids[1]),
PackEdgeKey(vertex_ids[1], vertex_ids[2]),
PackEdgeKey(vertex_ids[2], vertex_ids[0]),
};
bool has_duplicate_vertices =
vertex_ids[0].index == vertex_ids[1].index ||
vertex_ids[0].index == vertex_ids[2].index ||
vertex_ids[1].index == vertex_ids[2].index;
// Skip primitives that reduce to a single line or a point. PerformEdgeCollapse(...) can't reliably handle them.
if (has_duplicate_vertices) continue;
auto face_id = FaceID{ faces.count };
Face face;
face.corner_list_base.index = u32_max;
face.geometry_index = geometry_index;
ArrayAppend(faces, face);
for (u32 corner_index = 0; corner_index < 3; corner_index += 1) {
auto corner_id = CornerID{ face_id.index * 3 + corner_index };
auto edge_id = HashTableAddOrFind(edge_table, edges, edge_keys[corner_index]);
auto& corner = mesh[corner_id];
corner.face_id = face_id;
corner.edge_id = edge_id;
corner.vertex_id = vertex_ids[corner_index];
corner.attributes_id = { indices[corner_index] };
CornerListInsert<VertexID>(mesh, corner.vertex_id, corner_id);
CornerListInsert<EdgeID>(mesh, corner.edge_id, corner_id);
CornerListInsert<FaceID>(mesh, corner.face_id, corner_id);
}
}
base_vertex_index += desc.vertex_count;
}
mesh.edge_count = edges.count;
mesh.face_count = faces.count;
mesh.corner_count = faces.count * 3;
AllocatorFreeMemoryBlocks(allocator, allocator_high_water);
return mesh;
}
struct EdgeCollapseResult {
VertexID remaining_vertex_id;
u32 removed_face_count = 0;
};
static EdgeCollapseResult PerformEdgeCollapse(MeshView mesh, EdgeID edge_id, Allocator& heap_allocator, EdgeDuplicateMap& edge_duplicate_map, Array<EdgeID>& removed_edge_array) {
auto& edge = mesh[edge_id];
MDT_ASSERT(edge.vertex_0.index != edge.vertex_1.index);
MDT_ASSERT(edge.corner_list_base.index != u32_max);
MDT_ASSERT(mesh[edge.vertex_0].corner_list_base.index != u32_max);
MDT_ASSERT(mesh[edge.vertex_1].corner_list_base.index != u32_max);
MDT_ASSERT(mesh[edge.vertex_0].corner_list_base.index != mesh[edge.vertex_1].corner_list_base.index);
removed_edge_array.count = 0;
u32 removed_face_count = 0;
IterateCornerList<EdgeID>(mesh, edge.corner_list_base, [&](CornerID corner_id) {
auto& corner = mesh[corner_id];
auto& face = mesh[corner.face_id];
IterateCornerList<FaceID>(mesh, face.corner_list_base, [&](CornerID corner_id) {
CornerListRemove<VertexID>(mesh, corner_id);
bool edge_removed = CornerListRemove<EdgeID>(mesh, corner_id);
bool face_removed = CornerListRemove<FaceID>(mesh, corner_id);
if (edge_removed) ArrayAppendMaybeGrow(removed_edge_array, heap_allocator, mesh[corner_id].edge_id);
removed_face_count += (u32)face_removed;
});
});
auto remaining_vertex_id = CornerListMerge<VertexID>(mesh, edge.vertex_0, edge.vertex_1);
if (remaining_vertex_id.index != u32_max) {
auto remaining_base_id = mesh[remaining_vertex_id].corner_list_base;
IterateCornerList<VertexID>(mesh, remaining_base_id, [&](CornerID corner_id) {
// TODO: This can be iteration over just incoming and outgoing edges of a corner.
IterateCornerList<FaceID>(mesh, corner_id, [&](CornerID corner_id) {
auto edge_id_1 = mesh[corner_id].edge_id;
auto& edge_1 = mesh[edge_id_1];
auto edge_id_0 = HashTableAddOrFind(edge_duplicate_map, heap_allocator, PackEdgeKey(edge_1.vertex_0, edge_1.vertex_1), edge_id_1);
if (edge_id_0.index != edge_id_1.index) {
CornerListMerge<EdgeID>(mesh, edge_id_0, edge_id_1);
ArrayAppendMaybeGrow(removed_edge_array, heap_allocator, edge_id_1);
}
});
});
IterateCornerList<VertexID>(mesh, remaining_base_id, [&](CornerID corner_id_0) {
IterateCornerList<FaceID>(mesh, corner_id_0, [&](CornerID corner_id_1) {
if (remaining_base_id.index == corner_id_1.index) return;
IterateCornerList<VertexID>(mesh, corner_id_1, [&](CornerID corner_id_2) {
if (corner_id_1.index == corner_id_2.index) return;
IterateCornerList<FaceID>(mesh, corner_id_2, [&](CornerID corner_id) {
auto edge_id = mesh[corner_id].edge_id;
auto& edge = mesh[edge_id];
HashTableAddOrFind(edge_duplicate_map, heap_allocator, PackEdgeKey(edge.vertex_0, edge.vertex_1), edge_id);
});
});
});
});
}
EdgeCollapseResult result;
result.remaining_vertex_id = remaining_vertex_id;
result.removed_face_count = removed_face_count;
return result;
}
//
// Basic geometric quadric. For reference see [Garland and Heckbert 1997], [Hugues Hoppe 1999].
// Notation is based on [Hugues Hoppe 1999].
//
struct Quadric {
//
// Symmetric matrix A:
// (a00, a01, a02)
// (a01, a11, a12)
// (a02, a12, a22)
//
float a00 = 0.f;
float a11 = 0.f;
float a22 = 0.f;
float a01 = 0.f;
float a02 = 0.f;
float a12 = 0.f;
Vector3 b = { 0.f, 0.f, 0.f };
float c = 0.f;
float weight = 0.f;
};
static_assert(sizeof(Quadric) == sizeof(float) * 11, "Invalid Quadric size.");
struct QuadricAttributeGradient {
Vector3 g = { 0.f, 0.f, 0.f };
float d = 0.f;
};
struct QuadricWithAttributes : Quadric {
#if MDT_ENABLE_ATTRIBUTE_SUPPORT
QuadricAttributeGradient attributes[MDT_MAX_ATTRIBUTE_STRIDE_DWORDS]; // Note that this array is used as a 'flexible array'.
// Quadric with attributes cannot be copied by value as it's variable size (i.e. it might be missing trailing attributes).
QuadricWithAttributes() { memset(this, 0, sizeof(QuadricWithAttributes)); }
QuadricWithAttributes(const QuadricWithAttributes&) = delete;
QuadricWithAttributes& operator= (const QuadricWithAttributes&) = delete;
QuadricWithAttributes& operator= (QuadricWithAttributes&&) = delete;
#endif // MDT_ENABLE_ATTRIBUTE_SUPPORT
};
static_assert(sizeof(QuadricWithAttributes) == sizeof(Quadric) + sizeof(QuadricAttributeGradient) * MDT_MAX_ATTRIBUTE_STRIDE_DWORDS, "Invalid QuadricWithAttributes size.");
//
// Matt Pharr's blog. 2019. Accurate Differences of Products with Kahan's Algorithm.
//
always_inline_function static float DifferenceOfProducts(float a, float b, float c, float d) {
float cd = c * d;
float err = fmaf(c, -d, cd);
float dop = fmaf(a, b, -cd);
return dop + err;
}
always_inline_function static Vector3 operator+ (const Vector3& lh, const Vector3& rh) { return Vector3{ lh.x + rh.x, lh.y + rh.y, lh.z + rh.z }; }
always_inline_function static Vector3 operator- (const Vector3& lh, const Vector3& rh) { return Vector3{ lh.x - rh.x, lh.y - rh.y, lh.z - rh.z }; }
always_inline_function static Vector3 operator* (const Vector3& lh, float rh) { return Vector3{ lh.x * rh, lh.y * rh, lh.z * rh }; }
always_inline_function static Vector3 operator+ (const Vector3& lh, float rh) { return Vector3{ lh.x + rh, lh.y + rh, lh.z + rh }; }
always_inline_function static Vector3 operator- (const Vector3& lh, float rh) { return Vector3{ lh.x - rh, lh.y - rh, lh.z - rh }; }
always_inline_function static float DotProduct(const Vector3& lh, const Vector3& rh) { return lh.x * rh.x + lh.y * rh.y + lh.z * rh.z; }
always_inline_function static float Length(const Vector3& v) { return sqrtf(DotProduct(v, v)); }
always_inline_function static Vector3 CrossProduct(const Vector3& lh, const Vector3& rh) { return Vector3{ lh.y * rh.z - lh.z * rh.y, lh.z * rh.x - lh.x * rh.z, lh.x * rh.y - lh.y * rh.x }; }
always_inline_function static float LoadElementByIndex(const Vector3& vector, u32 index) { return (&vector.x)[index]; }
always_inline_function static Vector3 VectorMax(const Vector3& lh, const Vector3& rh) {
Vector3 result;
result.x = lh.x > rh.x ? lh.x : rh.x;
result.y = lh.y > rh.y ? lh.y : rh.y;
result.z = lh.z > rh.z ? lh.z : rh.z;
return result;
}
always_inline_function static Vector3 VectorMin(const Vector3& lh, const Vector3& rh) {
Vector3 result;
result.x = lh.x < rh.x ? lh.x : rh.x;
result.y = lh.y < rh.y ? lh.y : rh.y;
result.z = lh.z < rh.z ? lh.z : rh.z;
return result;
}
template<typename T>
always_inline_function T Clamp(T value, T min, T max) {
if (value < min) value = min;
if (value > max) value = max;
return value;
}
static void AccumulateQuadric(Quadric& accumulator, const Quadric& quadric) {
accumulator.a00 += quadric.a00;
accumulator.a11 += quadric.a11;
accumulator.a22 += quadric.a22;
accumulator.a01 += quadric.a01;
accumulator.a02 += quadric.a02;
accumulator.a12 += quadric.a12;
accumulator.b.x += quadric.b.x;
accumulator.b.y += quadric.b.y;
accumulator.b.z += quadric.b.z;
accumulator.c += quadric.c;
accumulator.weight += quadric.weight;
}
static void AccumulateQuadricWithAttributes(QuadricWithAttributes& accumulator, const QuadricWithAttributes& quadric, u32 attribute_stride_dwords) {
AccumulateQuadric(accumulator, quadric);
#if MDT_ENABLE_ATTRIBUTE_SUPPORT
for (u32 i = 0; i < attribute_stride_dwords; i += 1) {
auto& attribute_accumulator = accumulator.attributes[i];
auto& attribute_quadric = quadric.attributes[i];
attribute_accumulator.g.x += attribute_quadric.g.x;
attribute_accumulator.g.y += attribute_quadric.g.y;
attribute_accumulator.g.z += attribute_quadric.g.z;
attribute_accumulator.d += attribute_quadric.d;