-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtetrapal.c
4477 lines (3528 loc) · 138 KB
/
tetrapal.c
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 "tetrapal.h"
#include <math.h>
/* Allocator functions. */
#if defined(TETRAPAL_MALLOC) && defined(TETRAPAL_REALLOC) && defined(TETRAPAL_FREE)
/* User has defined all of their own allocator functions. */
#elif !defined(TETRAPAL_MALLOC) && !defined(TETRAPAL_REALLOC) && !defined(TETRAPAL_FREE)
#include <stdlib.h> /* free(), malloc(), realloc(). */
#define TETRAPAL_MALLOC(size) malloc(size)
#define TETRAPAL_REALLOC(ptr, size) realloc(ptr, size)
#define TETRAPAL_FREE(ptr) free(ptr)
#else
#error "Either all or none of MALLOC, REALLOC, and FREE must be defined!"
#endif
/* Dev-only debug macro. */
//#define TETRAPAL_DEBUG
#ifdef TETRAPAL_DEBUG
#include <stdio.h>
#include <assert.h>
#define TETRAPAL_ASSERT(condition, message) assert(condition && message)
#else
#define TETRAPAL_ASSERT(condition, message)
#endif
#ifndef NULL
#define NULL ((void*)0)
#endif
/* Maximum value of any unsigned integer type. */
#define max_of_unsigned(T) ((T)(~(T)0))
/* True/false macro constants. */
#define true 1
#define false 0
/* Typedefs for internal use. */
typedef float coord_t; /* Type representing a floating-point coordinate. */
typedef signed long vertex_t; /* Type representing a global vertex index. */
typedef unsigned long simplex_t; /* Type representing the global simplex index. */
typedef unsigned char facet_t; /* Type representing the cavity facet global index. */
typedef unsigned char local_t; /* Type representing a local index. */
typedef signed long error_t; /* Type representing an error code. */
typedef unsigned char flags_t; /* Type representing a set of bit-flags. */
typedef unsigned long random_t; /* Type representing a random integer. */
typedef unsigned long long digit_t; /* Type representing a digit; used for exact airthmetic. */
typedef unsigned char bool; /* Type representing a boolean. */
/* Internal constants. */
static const vertex_t VERTEX_INFINITE = -1; /* Value representing the infinite vertex. */
static const simplex_t SIMPLEX_NULL = max_of_unsigned(simplex_t); /* Value representing a null or invalid simplex. */
static const facet_t FACET_NULL = max_of_unsigned(facet_t); /* Value representing a null or invalid facet. */
static const local_t LOCAL_NULL = max_of_unsigned(local_t); /* Value representing a null or invalid local index. */
static const random_t RANDOM_MAX = 0xffff; /* Maximum value of a randomly generated integer. */
static const double ARRAY_GROWTH_FACTOR = 1.618; /* Amount to resize arrays when capacity is reached. */
static const double CAVITY_TABLE_MAX_LOAD = 0.7; /* Maximum load factor of the cavity hash table. */
static const facet_t CAVITY_TABLE_FREE = max_of_unsigned(facet_t); /* Value representing a free element in the cavity hash table. */
/* Internal error codes. */
typedef enum
{
ERROR_NONE,
ERROR_OUT_OF_MEMORY,
ERROR_INVALID_ARGUMENT,
} ErrorCode;
/* Internal hard-coded maximum value of a given coordinate.
Input points are expected to be given in the range [0.0, 1.0], and are then scaled by this amount.
This value has been chosen because it allows for accurate representation of linear sRGB values without loss of precision.
Additionally, knowing the maximum possible bit length of a coordinate makes exact computation of geometric predicates simpler.
Do NOT increase this value if you want the triangulation to remain robust. */
static const coord_t TETRAPAL_PRECISION = (1u << 16u) - 1u;
/********************************/
/* Vector Maths */
/********************************/
/* Calculate the dot product of [a] and [b] in 3D. */
static inline coord_t dot_3d(const coord_t a[3], const coord_t b[3]);
/* Calculate the dot product of [a] and [b] in 2D. */
static inline coord_t dot_2d(const coord_t a[2], const coord_t b[2]);
/* Subtract [b] from [a] in 3D. */
static inline void sub_3d(const coord_t a[3], const coord_t b[3], coord_t result[3]);
/* Subtract [b] from [a] in 2D. */
static inline void sub_2d(const coord_t a[2], const coord_t b[2], coord_t result[2]);
/* Multiply the 3D vector [a] by the scalar [s]. */
static inline void mul_3d(const coord_t a[3], const coord_t s, coord_t result[3]);
/* Calculate the 3D cross product of [a] against [b]. */
static inline void cross_3d(const coord_t a[3], const coord_t b[3], coord_t result[3]);
/* Normalise [a] in 3D. */
static inline void normalise_3d(const coord_t a[3], coord_t result[3]);
/* Determine the circumcentre of the triangle [a, b, c] in 2D space. */
static void circumcentre_2d(const coord_t a[2], const coord_t b[2], const coord_t c[2], coord_t* result);
/* Determine the circumcentre of the tetrahedron [a, b, c, d]. */
static void circumcentre_3d(const coord_t a[3], const coord_t b[3], const coord_t c[3], const coord_t d[3], coord_t* result);
/* Get the midpoint between [a] and [b] in 2D space. */
static inline void midpoint_2d(const coord_t a[2], const coord_t b[2], coord_t result[2]);
/* Get the midpoint between [a] and [b] in 3D space. */
static inline void midpoint_3d(const coord_t a[3], const coord_t b[3], coord_t result[3]);
/* Calculate the squared distance between [a] and [b] in 1D space. */
static inline coord_t distance_squared_1d(const coord_t a[1], const coord_t b[1]);
/* Calculate the squared distance between [a] and [b] in 2D space. */
static inline coord_t distance_squared_2d(const coord_t a[2], const coord_t b[2]);
/* Calculate the squared distance between [a] and [b] in 3D space. */
static inline coord_t distance_squared_3d(const coord_t a[3], const coord_t b[3]);
/********************************/
/* 128-Bit Integer */
/********************************/
/* Simulation of a 128-bit signed integer type for higher precision integer arithmetic. */
typedef struct
{
digit_t digits[2];
char sign;
} int128_t;
/* Create a new zero-initialised int128. */
static inline int128_t int128_zero();
/* Create a new int128 from the product of two doubles. */
static inline int128_t int128_from_product(const double a, const double b);
/* Add two int128 types together. */
static inline int128_t int128_add(const int128_t a, const int128_t b);
/* Subtract two int128 types from each other. */
static inline int128_t int128_sub(const int128_t a, const int128_t b);
/* Return the absolute (positive) value of [a]. */
static inline int128_t int128_abs(const int128_t a);
/* Return the negative value of [a]. */
static inline int128_t int128_neg(const int128_t a);
/* Return the additive inverse of [a] (flip the sign if it is not zero). */
static inline int128_t int128_inv(const int128_t a);
/* Test whether the absolute value of [a] is less than the absolute value of [b]. */
static inline bool int128_lt_abs(const int128_t a, const int128_t b);
/********************************/
/* Geometric Predicates */
/********************************/
/*
Robust geometric predicates are calculated by taking advantage of the fact that the
input coordinates consist of integer values whose maximum representable bit length is
known in advance.
Because of this, it is possible to determine conservative error bounds for each
predicate before runtime, assuming arithmetic is performed using double precision floats.
For most predicates the maximum error is 0, and no specialised exact arithmetic is ever needed.
Otherwise, the error bounds acts as a static filter that only performs exact arithmetic
when the magnitude of the approximate result exceeds the maximum error.
*/
static const double MAX_ERROR_INCIRCLE = 73728.0;
static const double MAX_ERROR_INSPHERE = 51539607552.0;
/* Check if the 3D coordinates [a] and [b] are coincident. */
static inline bool is_coincident_3d(const coord_t a[3], const coord_t b[3]);
/* Check if the 3D coordinates [a], [b] and [c] are colinear. */
static bool is_colinear_3d(const coord_t a[3], const coord_t b[3], const coord_t c[3]);
/* Check if the 3D coordinates [a], [b], [c] and [d] are coplanar. */
static inline bool is_coplanar_3d(const coord_t a[3], const coord_t b[3], const coord_t c[3], const coord_t d[3]);
/* Evaluate the signed area of the triangle [a, b, c] in 2D space. */
static coord_t orient_2d(const coord_t a[2], const coord_t b[2], const coord_t c[2]);
/* Evaluate the signed volume of the tetrahedron [a, b, c, d] in 3D space. */
static coord_t orient_3d(const coord_t a[3], const coord_t b[3], const coord_t c[3], const coord_t d[3]);
/* Test whether the point [e] lies inside or outside the sphere circumscribing the positively oriented triangle. [a, b, c]. */
static coord_t incircle_2d(const coord_t a[2], const coord_t b[2], const coord_t c[2], const coord_t d[2]);
/* Test whether the point [d] lies inside or outside the sphere circumscribing the positively oriented tetrahedron. [a, b, c, d]. */
static coord_t insphere_3d(const coord_t a[3], const coord_t b[3], const coord_t c[3], const coord_t d[3], const coord_t e[3]);
#ifdef TETRAPAL_DEBUG
/* Return the bit-length of the absolute value of a. */
static inline size_t bit_length(const coord_t a);
#endif
/********************************/
/* Stack */
/********************************/
typedef struct
{
size_t count;
size_t capacity;
simplex_t* data;
} Stack;
/* Allocate and initialise stack data. */
static error_t stack_init(Stack* stack, size_t reserve);
/* Free all data allocated by the stack. */
static void stack_free(Stack* stack);
/* Clear all items from the stack. */
static void stack_clear(Stack* stack);
/* Insert an item in the stack. Returns non-zero on failure. */
static error_t stack_insert(Stack* stack, simplex_t t);
/* Check if the stack is at capacity, resizing if necessary. */
static error_t stack_check_capacity(Stack* stack);
/* Remove the item at the top of the stack. */
static void stack_pop(Stack* stack);
/* Get the item at the top of the stack. */
static simplex_t stack_top(const Stack* stack);
/* Check if the stack contains an item. */
static bool stack_contains(const Stack* stack, simplex_t t);
/* Check whether or not the stack is empty. */
static bool stack_is_empty(const Stack* stack);
/********************************/
/* KD Tree */
/********************************/
/* Perform in-place balancing of a [k]-d tree given a buffer of vertex indices. */
static error_t kdtree_balance(Tetrapal* tetrapal, const size_t begin, const size_t end, const size_t depth);
/* Perform an approximate nearest-neighbour search for the given coordinate (i.e. return the first leaf node visited).
This function returns the index of the node in the tree, NOT the vertex index itself! */
static size_t kdtree_find_approximate(const Tetrapal* tetrapal, const coord_t* p);
/* Return the vertex index at node [i] in the tree. */
static inline vertex_t kdtree_get_vertex(const Tetrapal* tetrapal, const size_t i);
/* Partially sort the buffer in the range [begin, end] inclusive so that the middle value is the median. */
static void kdtree_sort_median(Tetrapal* tetrapal, const size_t begin, const size_t end, const size_t depth);
#ifdef TETRAPAL_DEBUG
/* Print the KD Tree. */
static void kdtree_print(const Tetrapal* tetrapal);
/* Recursive helper function for printing the KD Tree. */
static void kdtree_print_recurse(const Tetrapal* tetrapal, size_t begin, size_t end, size_t depth);
#endif
/********************************/
/* Cavity */
/********************************/
typedef struct
{
struct
{
size_t count; /* Number of facets in the cavity. */
size_t capacity; /* Capacity of the facet arrays. */
vertex_t* incident_vertex; /* Facet index to incident vertex global index. */
simplex_t* adjacent_simplex; /* Facet index to adjacent simplex global index. */
local_t* boundary_facet; /* Facet index to adjacent simplex facet local index. */
} facets;
struct
{
size_t capacity; /* Capacity of the hash table. */
size_t count; /* Number of elements in the table. */
vertex_t* edge;
facet_t* facet;
} table;
} Cavity;
/* Allocate and initialise cavity data. */
static error_t cavity_init(Cavity* cavity, size_t reserve);
/* Free all data allocated by the cavity. */
static void cavity_free(Cavity* cavity);
/* Insert a facet [a, b, c] into the cavity adjacent to a boundary simplex [t] at local facet index [i]. */
static facet_t cavity_insert(Cavity* cavity, vertex_t a, vertex_t b, vertex_t c, simplex_t t, local_t i);
/* Check if the cavity is at capacity, resizing if necessary. */
static error_t cavity_check_capacity(Cavity* cavity);
/* Insert the directed edge [a, b] corresponding to facet [f] into the hash table.
Returns non-zero on failure. */
static error_t cavity_insert_edge(Cavity* cavity, vertex_t a, vertex_t b, facet_t f);
/* Check if the cavity hash table is at capacity, resizing if necessary. */
static error_t cavity_table_check_capacity(Cavity* cavity);
/* Generate a hash given the directed egde [a, b]. */
static size_t cavity_edge_hash(vertex_t a, vertex_t b);
/* Reset the cavity data. */
static void cavity_clear(Cavity* cavity);
/* Return the facet keyed on the directed edge [a, b]. */
static facet_t cavity_find(Cavity* cavity, vertex_t a, vertex_t b);
/* Set [t] to be the simplex adjacent to the cavity facet [f]. */
static void cavity_set_adjacent_simplex(Cavity* cavity, facet_t f, simplex_t t);
/* Return the vertex incident to the facet [f] at local index [i]. */
static vertex_t cavity_get_incident_vertex(Cavity* cavity, facet_t f, local_t i);
/* Return the simplex adjacent to the facet [f]. */
static simplex_t cavity_get_adjacent_simplex(Cavity* cavity, facet_t f);
/* Get the local index of a facet [f] wrt the facet's adjacent boundary simplex. */
static local_t cavity_get_adjacent_simplex_facet(Cavity* cavity, facet_t f);
#ifdef TETRAPAL_DEBUG
/* Print all facet data. */
static void cavity_print_facet_data(Cavity* cavity);
#endif
/********************************/
/* Tetrapal Core */
/********************************/
struct Tetrapal
{
size_t dimensions; /* Number of dimensions spanned by the triangulation. */
struct
{
size_t count; /* Number of vertices. */
size_t capacity; /* Size of the vertex buffer. */
coord_t basis[2][3]; /* 3D Coordinates representing the basis vectors for 2D and 1D embedded triangulations. */
coord_t* coordinates; /* Vertex coordinates. */
simplex_t* incident_simplex; /* Vertex global index to incident simplex global index. */
vertex_t* tree; /* KD Tree of the coordinates in the triangulation. */
} vertices;
struct
{
size_t count; /* Number of simplices. */
size_t capacity; /* Size of the simplex arrays. */
vertex_t* incident_vertex; /* Simplex global index to incident vertex global index. */
simplex_t* adjacent_simplex; /* Simplex global index to adjacent simplex global index. */
simplex_t last; /* The most recently created finite simplex. */
/* Array of flags for every simplex. */
union
{
flags_t all; /* Convenient union to clear all flags. */
struct
{
flags_t
is_free : 1, /* Whether the simplex has been freed/deleted. */
is_infinite : 1; /* Whether the simplex is infinite. */
} bit;
} *flags;
struct
{
size_t count; /* Number of deleted simplices. */
size_t capacity; /* Size of the deleted simplices array. */
simplex_t* simplices; /* Global indices of the deleted simplices. */
} deleted;
} simplices;
Cavity cavity;
Stack stack;
};
/* Log a new vertex in the triangulation. */
static vertex_t new_vertex(Tetrapal* tetrapal, const coord_t* p);
/* Frees an existing tetrahedron [t]. */
static error_t free_simplex(Tetrapal* tetrapal, simplex_t t);
/* Set the adjacent simplex [a] with respect to simplex [t] at local facet index [i]. */
static inline void set_adjacent_simplex(Tetrapal* tetrapal, simplex_t t, simplex_t a, local_t i);
/* Get the vertex incident to simplex [t] at local vertex index [i]. */
static inline vertex_t get_incident_vertex(const Tetrapal* tetrapal, simplex_t t, local_t i);
/* Get the simplex adjacent to simplex [t] at local facet index [i]. */
static inline simplex_t get_adjacent_simplex(const Tetrapal* tetrapal, simplex_t t, local_t i);
/* Get a simplex incident to vertex [v]. */
static inline simplex_t get_incident_simplex(const Tetrapal* tetrapal, vertex_t v);
/* Get the circumcentre for a given simplex [t]. */
static inline void get_circumcentre(const Tetrapal* tetrapal, simplex_t t, coord_t* result);
/* Get a const pointer to the coordinates of vertex [v]. */
static inline const coord_t* get_coordinates(const Tetrapal* tetrapal, vertex_t v);
/* Get the normal vector of the facet at [i] of simplex [t]. */
static void get_facet_normal(const Tetrapal* tetrapal, simplex_t t, local_t i, coord_t result[3]);
/* Get the local vertex index from [t] corresponding to the global vertex index [v]. */
static inline local_t find_vertex(const Tetrapal* tetrapal, simplex_t t, vertex_t v);
/* Get the local facet index from [t] that is shared by [adj]. */
static inline local_t find_adjacent(const Tetrapal* tetrapal, simplex_t t, simplex_t adj);
/* Get the local facet index from [t] via the directed edge [a, b]. */
static inline local_t find_facet_from_edge(const Tetrapal* tetrapal, simplex_t t, vertex_t a, vertex_t b);
/* Check whether or not a given simplex has an infinite vertex. */
static inline bool is_infinite_simplex(const Tetrapal* tetrapal, simplex_t t);
/* Check whether or not the simplex [t] has been freed/deleted. */
static inline bool is_free_simplex(const Tetrapal* tetrapal, simplex_t t);
/* Check whether a given point is coincident with one of the vertices of simplex [t]. */
static inline bool is_coincident_simplex(const Tetrapal* tetrapal, simplex_t t, const float point[3]);
/* Get the size of a simplex in the triangulation (dimensions + 1). */
static inline local_t simplex_size(const Tetrapal* tetrapal);
/* Check whether the simplex buffers need to be resized, reallocating if so.
Returns non-zero on failure. */
static error_t check_simplices_capacity(Tetrapal* tetrapal);
/* Check whether the deleted simplex array needs to be resized, reallocating if so.
Returns non-zero on failure. */
static error_t check_deleted_capacity(Tetrapal* tetrapal);
/* Find the first d-simplex to start the triangulation with. Returns the number of dimensions spanned by the point set. */
static size_t find_first_simplex(Tetrapal* tetrapal, const float* points, const int size, vertex_t v[4]);
/* Generate a random integer from 0 to RANDOM_MAX given a seed value. The seed will be progressed. */
static inline random_t random(random_t* seed);
/* Get a random integer from 0 to (range - 1) inclusive. */
static inline random_t random_range(random_t* seed, random_t range);
/* Swap two vertex indices. */
static inline void swap_vertex(vertex_t* a, vertex_t* b);
/* Swap two local indices. */
static inline void swap_local(local_t* a, local_t* b);
#ifdef TETRAPAL_DEBUG
/* Check that simplex [t] encloses or touches the query point. */
static bool is_enclosing_simplex(Tetrapal* tetrapal, simplex_t t, const float point[3]);
/* Check combinatorial data for inconsistencies or corruption. */
static void check_combinatorics(Tetrapal* tetrapal);
/* Print all simplex data. */
static void print_simplex_data(Tetrapal* tetrapal);
/* Print all vertex data. */
static void print_vertex_data(Tetrapal* tetrapal);
/* Print the size in memory of all data. */
static void print_memory(Tetrapal* tetrapal);
#endif
/********************************/
/* 3D Triangulation */
/********************************/
/* Table of local vertex indices such that the facet [i][0], [i][1], [i][2] is opposite [i].
[i], [i][0], [i][1], [i][2] always form a positively-oriented tetrahedron. */
static const local_t facet_opposite_vertex[4][3] =
{
{1, 2, 3},
{0, 3, 2},
{3, 0, 1},
{2, 1, 0}
};
/* Table of local facet indices such that the directed edge [i, j] belongs to the local facet at [i][j].
Useful for visiting the ring of tetrahedra around an edge. */
static const local_t facet_from_edge[4][4] =
{
{ (local_t)(-1), 2, 3, 1 },
{ 3, (local_t)(-1), 0, 2 },
{ 1, 3, (local_t)(-1), 0 },
{ 2, 0, 1, (local_t)(-1) }
};
/* Initialise the 3D triangulation, creating the first simplex and setting up internal state. */
static error_t triangulate_3d(Tetrapal* tetrapal, vertex_t v[4], const float* points, const int size);
/* Insert a vertex [v] into the 3D triangulation. */
static error_t insert_3d(Tetrapal* tetrapal, vertex_t v);
/* Locate the simplex enclosing the input point, or an infinite simplex if it is outside the convex hull.
If it fails, returns a null simplex. */
static simplex_t locate_3d(const Tetrapal* tetrapal, const coord_t point[3]);
/* Determine the conflict zone of a given point via depth-first search from [t], which must enclose the vertex [v].
Frees conflicting simplices and retriangulates the cavity.
Returns a simplex that was created during triangulation, or a null simplex if it failed. */
static simplex_t stellate_3d(Tetrapal* tetrapal, vertex_t v, simplex_t t);
/* Check whether a given point is in conflict with the simplex [t]. */
static bool conflict_3d(const Tetrapal* tetrapal, simplex_t t, const coord_t point[3]);
/* Interpolate an input point as the weighted sum of up to four existing points in the triangulation. */
static size_t interpolate_3d(const Tetrapal* tetrapal, const coord_t point[3], int indices[4], float weights[4], simplex_t* t);
/* Return the nearest neighbour of an input point. */
static vertex_t nearest_3d(const Tetrapal* tetrapal, const coord_t point[3]);
/* Scale a given input point in the range [0.0, 1.0] by the value defined by TETRAPAL_PRECISION.
Input points beyond the expected range will be clamped before being transformed. */
static inline void transform_3d(const float in[3], coord_t out[3]);
/* Create a new tetrahedron [a, b, c, d] with positive orientation. Returns the global index of the new tetrahedron. */
static simplex_t new_tetrahedron(Tetrapal* tetrapal, vertex_t a, vertex_t b, vertex_t c, vertex_t d);
/********************************/
/* 2D Triangulation */
/********************************/
/* Table of local edge indices such that the edge [i][0], [i][1] is opposite vertex [i].
[i], [i][0], [i][1] always form a positively-oriented triangle. */
static const local_t edge_opposite_vertex[3][2] =
{
{1, 2},
{2, 0},
{0, 1},
};
/* Initialise the 2D triangulation, creating the first simplex and setting up internal state. */
static error_t triangulate_2d(Tetrapal* tetrapal, vertex_t v[3], const float* points, const int size);
/* Insert a vertex [v] into the 2D triangulation. */
static error_t insert_2d(Tetrapal* tetrapal, vertex_t v);
/* Locate the simplex enclosing the input point, or an infinite simplex if it is outside the convex hull.
If it fails, returns a null simplex. */
static simplex_t locate_2d(const Tetrapal* tetrapal, const coord_t point[2]);
/* Determine the conflict zone of a given point via depth-first search from [t], which must enclose the vertex [v].
Frees conflicting simplices and retriangulates the cavity.
Returns a simplex that was created during triangulation, or a null simplex if it failed. */
static simplex_t stellate_2d(Tetrapal* tetrapal, vertex_t v, simplex_t t);
/* Check whether a given point is in conflict with the simplex [t]. */
static bool conflict_2d(const Tetrapal* tetrapal, simplex_t t, const coord_t point[2]);
/* Interpolate an input point as the weighted sum of up to three existing points in the triangulation. */
static size_t interpolate_2d(const Tetrapal* tetrapal, const coord_t point[2], int indices[3], float weights[3], simplex_t* t);
/* Return the nearest neighbour of an input point. */
static vertex_t nearest_2d(const Tetrapal* tetrapal, const coord_t point[2]);
/* Transform 3D coordinates in the range [0.0, 1.0] to the local 2D coordinate system of the triangulation. */
static inline void transform_2d(const Tetrapal* tetrapal, const float point[3], coord_t out[2]);
/* Create a new triangle [a, b, c] with positive orientation. Returns the global index of the new triangle. */
static simplex_t new_triangle(Tetrapal* tetrapal, vertex_t a, vertex_t b, vertex_t c);
/********************************************/
/* 1D Triangulation (Binary Tree) */
/********************************************/
/* Initialise the 1D triangulation, i.e. build the binary tree. */
static error_t triangulate_1d(Tetrapal* tetrapal, const float* points, const int size);
/* Transform 3D coordinates in the range [0.0, 1.0] to the local 1D coordinate system of the triangulation. */
static inline void transform_1d(const Tetrapal* tetrapal, const float point[3], coord_t out[1]);
/* Interpolate an input point as the weighted sum of up to two existing points in the triangulation. */
static size_t interpolate_1d(const Tetrapal* tetrapal, const coord_t point[1], int indices[2], float weights[2]);
/* Return the nearest neighbour of an input point. */
static vertex_t nearest_1d(const Tetrapal* tetrapal, const coord_t point[1]);
/********************************************/
/* 0D Triangulation (Single Vertex) */
/********************************************/
/* Initialise the 0D triangulation. */
static error_t triangulate_0d(Tetrapal* tetrapal);
/* 'Interpolate' an input point in a 0d triangulation (returns the 0 vertex). */
static size_t interpolate_0d(int indices[1], float weights[1]);
/* Return the 0 vertex. */
static vertex_t nearest_0d();
/********************************************/
/* Natural Neighbour Interpolation */
/********************************************/
/* Helper function to accumulate the weight for a given vertex index. */
static inline error_t natural_neighbour_accumulate(vertex_t index, coord_t weight, int* indices, float* weights, int size, size_t* count);
/* Get the natural neighbour coordinats of an input point within a 2D triangulation. */
static size_t natural_neighbour_2d(const Tetrapal* tetrapal, coord_t point[2], int* indices, float* weights, int size);
/* Get the natural neighbour coordinats of an input point within a 3D triangulation. */
static size_t natural_neighbour_3d(const Tetrapal* tetrapal, coord_t point[3], int* indices, float* weights, int size);
/********************************************************************************************/
/********************************************************************************************/
/* IMPLEMENTATION */
/********************************************************************************************/
/********************************************************************************************/
/********************************/
/* Vector Maths */
/********************************/
static inline coord_t dot_3d(const coord_t a[3], const coord_t b[3])
{
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
static inline coord_t dot_2d(const coord_t a[2], const coord_t b[2])
{
return a[0] * b[0] + a[1] * b[1];
}
static inline void sub_3d(const coord_t a[3], const coord_t b[3], coord_t result[3])
{
result[0] = a[0] - b[0];
result[1] = a[1] - b[1];
result[2] = a[2] - b[2];
}
static inline void sub_2d(const coord_t a[2], const coord_t b[2], coord_t result[2])
{
result[0] = a[0] - b[0];
result[1] = a[1] - b[1];
}
static inline void mul_3d(const coord_t a[3], const coord_t s, coord_t result[3])
{
result[0] = a[0] * s;
result[1] = a[1] * s;
result[2] = a[2] * s;
}
static inline void cross_3d(const coord_t a[3], const coord_t b[3], coord_t result[3])
{
result[0] = a[1] * b[2] - a[2] * b[1];
result[1] = a[2] * b[0] - a[0] * b[2];
result[2] = a[0] * b[1] - a[1] * b[0];
}
static inline void normalise_3d(const coord_t a[3], coord_t result[3])
{
coord_t length = sqrtf(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]);
result[0] = a[0] / length;
result[1] = a[1] / length;
result[2] = a[2] / length;
}
static void circumcentre_2d(const coord_t a[2], const coord_t b[2], const coord_t c[2], coord_t* result)
{
/* Adapted from Shewchuk via https://ics.uci.edu/~eppstein/junkyard/circumcenter.html */
/* Use coordinates relative to point `a' of the triangle. */
double ab[2] = { (double)b[0] - (double)a[0], (double)b[1] - (double)a[1] };
double ac[2] = { (double)c[0] - (double)a[0], (double)c[1] - (double)a[1] };
/* Squares of lengths of the edges incident to `a'. */
double ab_len = ab[0] * ab[0] + ab[1] * ab[1];
double ac_len = ac[0] * ac[0] + ac[1] * ac[1];
/* Calculate the denominator of the formulae. */
double area = ab[0] * ac[1] - ab[1] * ac[0];
double denominator = 0.5 / area;
/* Calculate offset (from `a') of circumcenter. */
double offset[2] =
{
(ac[1] * ab_len - ab[1] * ac_len) * denominator,
(ab[0] * ac_len - ac[0] * ab_len) * denominator
};
result[0] = (coord_t)offset[0] + a[0];
result[1] = (coord_t)offset[1] + a[1];
}
static void circumcentre_3d(const coord_t a[3], const coord_t b[3], const coord_t c[3], const coord_t d[3], coord_t* result)
{
/* Adapted from Shewchuk via https://ics.uci.edu/~eppstein/junkyard/circumcenter.html */
/* Use coordinates relative to point `a' of the tetrahedron. */
double ab[3] = { (double)b[0] - (double)a[0], (double)b[1] - (double)a[1], (double)b[2] - (double)a[2] };
double ac[3] = { (double)c[0] - (double)a[0], (double)c[1] - (double)a[1], (double)c[2] - (double)a[2] };
double ad[3] = { (double)d[0] - (double)a[0], (double)d[1] - (double)a[1], (double)d[2] - (double)a[2] };
/* Squares of lengths of the edges incident to `a'. */
double ab_len = ab[0] * ab[0] + ab[1] * ab[1] + ab[2] * ab[2];
double ac_len = ac[0] * ac[0] + ac[1] * ac[1] + ac[2] * ac[2];
double ad_len = ad[0] * ad[0] + ad[1] * ad[1] + ad[2] * ad[2];
/* Cross products of these edges. */
double acxad[3] = { ac[1] * ad[2] - ac[2] * ad[1], ac[2] * ad[0] - ac[0] * ad[2], ac[0] * ad[1] - ac[1] * ad[0] };
double adxab[3] = { ad[1] * ab[2] - ad[2] * ab[1], ad[2] * ab[0] - ad[0] * ab[2], ad[0] * ab[1] - ad[1] * ab[0] };
double abxac[3] = { ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0] };
/* Calculate the denominator of the formulae. */
double area = ab[0] * acxad[0] + ab[1] * acxad[1] + ab[2] * acxad[2];
double denominator = 0.5 / area;
/* Calculate offset (from `a') of circumcenter. */
double offset[3] =
{
(ab_len * acxad[0] + ac_len * adxab[0] + ad_len * abxac[0]) * denominator,
(ab_len * acxad[1] + ac_len * adxab[1] + ad_len * abxac[1]) * denominator,
(ab_len * acxad[2] + ac_len * adxab[2] + ad_len * abxac[2]) * denominator
};
result[0] = (coord_t)offset[0] + a[0];
result[1] = (coord_t)offset[1] + a[1];
result[2] = (coord_t)offset[2] + a[2];
}
static inline void midpoint_2d(const coord_t a[2], const coord_t b[2], coord_t result[2])
{
result[0] = (a[0] + b[0]) / 2;
result[1] = (a[1] + b[1]) / 2;
}
static inline void midpoint_3d(const coord_t a[3], const coord_t b[3], coord_t result[3])
{
result[0] = (a[0] + b[0]) / 2;
result[1] = (a[1] + b[1]) / 2;
result[2] = (a[2] + b[2]) / 2;
}
static inline coord_t distance_squared_1d(const coord_t a[1], const coord_t b[1])
{
coord_t ab = b[0] - a[0];
return ab * ab;
}
static inline coord_t distance_squared_2d(const coord_t a[2], const coord_t b[2])
{
coord_t ab[2] = { b[0] - a[0], b[1] - a[1] };
return ab[0] * ab[0] + ab[1] * ab[1];
}
static inline coord_t distance_squared_3d(const coord_t a[3], const coord_t b[3])
{
coord_t ab[3] = { b[0] - a[0], b[1] - a[1], b[2] - a[2] };
return ab[0] * ab[0] + ab[1] * ab[1] + ab[2] * ab[2];
}
/********************************/
/* 128-Bit Integer */
/********************************/
static inline int128_t int128_zero()
{
int128_t result;
result.digits[0] = result.digits[1] = result.sign = 0;
return result;
}
static inline int128_t int128_from_product(const double a, const double b)
{
int128_t result = int128_zero();
digit_t mask = (1uLL << 32) - 1;
digit_t tmp[3];
/* Exit early if any of the operands are zero. */
if (a == 0 || b == 0)
return result;
/* Get the sign of the product. */
result.sign = (a < 0) == (b < 0) ? 1 : -1;
/* Get the magnitude of the two doubles and seperate into higher and lower parts. */
digit_t a_digit = (digit_t)fabs(a);
digit_t b_digit = (digit_t)fabs(b);
digit_t a_hi = a_digit >> 32;
digit_t a_lo = a_digit & mask;
digit_t b_hi = b_digit >> 32;
digit_t b_lo = b_digit & mask;
/* Get products. */
result.digits[0] = a_hi * b_hi;
result.digits[1] = a_lo * b_lo;
tmp[0] = a_hi * b_lo;
tmp[1] = a_lo * b_hi;
/* Add upper products. */
result.digits[0] += tmp[0] >> 32;
result.digits[0] += tmp[1] >> 32;
/* Add lower products. */
tmp[0] = (tmp[0] & mask) + (tmp[1] & mask);
tmp[1] = (tmp[0] & mask) << 32;
result.digits[1] += tmp[1];
result.digits[0] += tmp[0] >> 32;
result.digits[0] += result.digits[1] < tmp[1];
return result;
}
static inline int128_t int128_add(const int128_t a, const int128_t b)
{
/* Test edge cases. */
if (a.sign == 0) /* [a] is zero. */
return b;
if (b.sign == 0) /* [b] is zero. */
return a;
if (a.sign < b.sign) /* [a] is negative and [b] is positive. */
return int128_sub(b, int128_abs(a));
if (a.sign > b.sign) /* [a] is positive and [b] is negative.*/
return int128_sub(a, int128_abs(b));
/* Otherwise, add as normal, retaining the sign. */
int128_t result = int128_zero();
result.digits[1] = a.digits[1] + b.digits[1];
result.digits[0] = a.digits[0] + b.digits[0];
result.digits[0] += result.digits[1] < a.digits[1]; /* Add carry.*/
TETRAPAL_ASSERT(result.digits[0] >= a.digits[0], "Addition overflow!\n");
result.sign = a.sign;
return result;
}
static inline int128_t int128_sub(const int128_t a, const int128_t b)
{
/* Test edge cases. */
if (a.sign == 0) /* [a] is zero.*/
return int128_inv(b);
if (b.sign == 0) /* [b] is zero.*/
return a;
if (a.sign < b.sign) /* [a] is negative and [b] is positive. */
return int128_neg(int128_add(b, int128_abs(a)));
if (a.sign > b.sign) /* [a] is positive and [b] is negative. */
return int128_add(a, int128_abs(b));
if (a.sign < 0 && b.sign < 0) /* [a] and [b] are both negative. */
return int128_add(a, int128_abs(b));
if (a.digits[0] == b.digits[0] && a.digits[1] == b.digits[1]) /* [a] and [b] are equal. */
return int128_zero();
if (int128_lt_abs(a, b) == true) /* [a] is less than [b]. */
return int128_neg(int128_sub(b, a));
/* Subtract. */
int128_t result = int128_zero();
result.digits[1] = a.digits[1] - b.digits[1];
result.digits[0] = a.digits[0] - b.digits[0];
result.digits[0] -= result.digits[1] > a.digits[1]; /* Subtract borrow.*/
TETRAPAL_ASSERT(result.digits[0] <= a.digits[0], "Subtraction underflow!\n");
result.sign = a.sign;
return result;
}
static inline int128_t int128_abs(const int128_t a)
{
int128_t result = a;
result.sign = a.sign != 0 ? 1 : 0;
return result;
}
static inline int128_t int128_neg(const int128_t a)
{
int128_t result = a;
result.sign = a.sign != 0 ? -1 : 0;
return result;
}
static inline int128_t int128_inv(const int128_t a)
{
int128_t result = a;
result.sign = a.sign < 0 ? 1 : (a.sign > 0 ? -1 : 0);
return result;
}
static inline bool int128_lt_abs(const int128_t a, const int128_t b)
{
return
a.digits[0] < b.digits[0] ? true :
a.digits[0] > b.digits[0] ? false :
a.digits[1] < b.digits[1] ? true : false;
}
/********************************/
/* Geometric Predicates */
/********************************/
static inline bool is_coincident_3d(const coord_t a[3], const coord_t b[3])
{
return (a[0] == b[0] && a[1] == b[1] && a[2] == b[2]) ? true : false;
}
static bool is_colinear_3d(const coord_t a[3], const coord_t b[3], const coord_t c[3])
{
/* Assuming a maximum bit length of 16 for each coordinate, the result can be computed exactly with doubles. */
/* Bit length here is still 16, because the minimum value of an input coordinate is always 0. */
double ab[3] = { (double)b[0] - (double)a[0], (double)b[1] - (double)a[1], (double)b[2] - (double)a[2] };
double ac[3] = { (double)c[0] - (double)a[0], (double)c[1] - (double)a[1], (double)c[2] - (double)a[2] };
/* Bit length of cross product is at most 16 + 16 + 1 = 33. */
double cross[3] =
{
ab[1] * ac[2] - ab[2] * ac[1],
ab[2] * ac[0] - ab[0] * ac[2],
ab[0] * ac[1] - ab[1] * ac[0]
};
/* Cross product is guaranteed to be exact, so simply check that all components are zero. */
return (cross[0] == 0 && cross[1] == 0 && cross[2] == 0) ? true : false;
}
static inline bool is_coplanar_3d(const coord_t a[3], const coord_t b[3], const coord_t c[3], const coord_t d[3])
{
return (orient_3d(a, b, c, d) == 0) ? true : false;
}
static coord_t orient_2d(const coord_t a[2], const coord_t b[2], const coord_t c[2])
{
/* Bit length here is still 16, because the absolute difference between any two 2D coordinates is <= 16 bits. */
double ab[2] = { (double)b[0] - (double)a[0], (double)b[1] - (double)a[1] };
double ac[2] = { (double)c[0] - (double)a[0], (double)c[1] - (double)a[1] };
/* Bit length of determinant is at most 16 * 2 + 1 = 33. */
double det = ab[0] * ac[1] - ab[1] * ac[0];
return (coord_t)det;
}
static coord_t orient_3d(const coord_t a[3], const coord_t b[3], const coord_t c[3], const coord_t d[3])
{
/* Assuming a maximum bit length of 16 for each coordinate, the result can be computed exactly with doubles. */
/* Bit length here is still 16, because the minimum value of an input coordinate is always 0. */
double bc[3] = { (double)c[0] - (double)b[0], (double)c[1] - (double)b[1], (double)c[2] - (double)b[2] };
double bd[3] = { (double)d[0] - (double)b[0], (double)d[1] - (double)b[1], (double)d[2] - (double)b[2] };
double ba[3] = { (double)a[0] - (double)b[0], (double)a[1] - (double)b[1], (double)a[2] - (double)b[2] };
/* Bit length of cross product is at most 16 + 16 + 1 = 33. */
double cross[3] =
{
bc[1] * bd[2] - bc[2] * bd[1],
bc[2] * bd[0] - bc[0] * bd[2],
bc[0] * bd[1] - bc[1] * bd[0]
};
/* Bit length of determinant is at most 33 + 16 + 2 = 51. */
double det = cross[0] * ba[0] + cross[1] * ba[1] + cross[2] * ba[2];
/* 51 <= 53, so no extended precision is required. */
return (coord_t)det;
}
static coord_t incircle_2d(const coord_t a[2], const coord_t b[2], const coord_t c[2], const coord_t d[2])
{
/* maxbitlen = 16. */
double da[2] = { (double)a[0] - (double)d[0], (double)a[1] - (double)d[1] };
double db[2] = { (double)b[0] - (double)d[0], (double)b[1] - (double)d[1] };
double dc[2] = { (double)c[0] - (double)d[0], (double)c[1] - (double)d[1] };
/* maxbitlen = 33. */
double abdet = da[0] * db[1] - db[0] * da[1];
double bcdet = db[0] * dc[1] - dc[0] * db[1];
double cadet = dc[0] * da[1] - da[0] * dc[1];
double alift = da[0] * da[0] + da[1] * da[1];