-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathBoundedSurface.h
More file actions
5229 lines (4816 loc) · 216 KB
/
Copy pathBoundedSurface.h
File metadata and controls
5229 lines (4816 loc) · 216 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
// Copyright 2019-2026 CERN and copyright holders of ALICE O2.
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
// All rights not expressly granted are reserved.
//
// This software is distributed under the terms of the GNU General Public
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
/// \author Sandro Wenzel <sandro.wenzel@cern.ch>
/// \since 2026-07
/// \file BoundedSurface.h
/// \brief Private analytic bounded surfaces, trim wires and closure checks behind O2BVHSurfaceSolid.
#ifndef ALICEO2_CADSUPPORT_BOUNDEDSURFACE_H_
#define ALICEO2_CADSUPPORT_BOUNDEDSURFACE_H_
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <limits>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
namespace o2::cad::surface
{
/// \name Numerical conventions: the tolerances shared by all bounded-surface code
/// @{
inline constexpr double kTolerance = 1.e-9; ///< generic length tolerance
inline constexpr double kToleranceSq = kTolerance * kTolerance;
inline constexpr double kAreaTolerance = 1.e-18; ///< degenerate (zero) parametric area
inline constexpr double kRayTolerance = 1.e-9; ///< minimum positive ray parameter t
inline constexpr double kIntersectionTolerance = 1.e-7; ///< clustering of near-equal intersections
inline constexpr double kClosureQuantum = 1.e-7; ///< vertex quantization for closure matching
/// Wire-closure tolerance, a 3D length in cm through the surface metric: the CAD extractor's endpoint precision.
inline constexpr double kWireJoinTolerance = 1.e-6;
/// The wire-join band for a model with a declared tolerance: that tolerance when looser than kWireJoinTolerance, else the floor.
inline constexpr double wireJoinToleranceFor(double modelTolerance)
{
return modelTolerance > kWireJoinTolerance ? modelTolerance : kWireJoinTolerance;
}
/// Chord flatness of the adaptive B-spline sampler, in the curve's parametric units; a B-spline trim is this polyline.
inline constexpr double kBSplineFlatness = 1.e-5;
inline constexpr double kBSplineFlatnessSq = kBSplineFlatness * kBSplineFlatness;
/// Rim-matching distance in cm when the model states no tolerance: the extractor precision, as kWireJoinTolerance.
inline constexpr double kRimMatchTolerance = 1.e-6;
/// Widening of the BVH leaf boxes before the outward float rounding; it dominates every navigation length tolerance.
inline constexpr double kBVHBoxTolerance = 1.e-3;
/// Zero threshold of solveQuarticReal's branch tests, in machine epsilons relative to the normalised terms: dimensionless.
inline constexpr double kQuarticEpsilon = 32. * 2.220446049250313e-16;
/// @}
/// A 2D point/vector in a surface's parametric (u, v) domain.
struct Vec2 {
double uCoord = 0.;
double vCoord = 0.;
};
/// A 3D point/vector in the solid's local frame.
struct Vec3 {
double xCoord = 0.;
double yCoord = 0.;
double zCoord = 0.;
};
inline Vec3 operator+(const Vec3& firstVector, const Vec3& secondVector)
{
return {firstVector.xCoord + secondVector.xCoord, firstVector.yCoord + secondVector.yCoord,
firstVector.zCoord + secondVector.zCoord};
}
inline Vec3 operator-(const Vec3& firstVector, const Vec3& secondVector)
{
return {firstVector.xCoord - secondVector.xCoord, firstVector.yCoord - secondVector.yCoord,
firstVector.zCoord - secondVector.zCoord};
}
inline Vec3 operator*(const Vec3& vector, double scale)
{
return {vector.xCoord * scale, vector.yCoord * scale, vector.zCoord * scale};
}
inline Vec3 operator*(double scale, const Vec3& vector)
{
return vector * scale;
}
inline Vec2 operator-(const Vec2& firstPoint, const Vec2& secondPoint)
{
return {firstPoint.uCoord - secondPoint.uCoord, firstPoint.vCoord - secondPoint.vCoord};
}
/// The 3D length squared of parametric displacement \a delta under the first fundamental form (\a gUU, \a gUV, \a gVV).
inline double parametricLengthSq(double gUU, double gUV, double gVV, const Vec2& delta)
{
return gUU * delta.uCoord * delta.uCoord + 2. * gUV * delta.uCoord * delta.vCoord +
gVV * delta.vCoord * delta.vCoord;
}
/// How a wire converts a parametric separation into a 3D length: the owning surface's first fundamental form, or the identity.
struct ParametricMetric {
using Evaluate = void (*)(const void* context, const Vec2& uv, double& gUU, double& gUV, double& gVV);
Evaluate evaluate = nullptr;
const void* context = nullptr;
/// The 3D length squared spanned by the parametric displacement \a delta starting at \a uv.
double lengthSq(const Vec2& uv, const Vec2& delta) const
{
if (evaluate == nullptr) {
return delta.uCoord * delta.uCoord + delta.vCoord * delta.vCoord;
}
double gUU = 1.;
double gUV = 0.;
double gVV = 1.;
evaluate(context, uv, gUU, gUV, gVV);
return parametricLengthSq(gUU, gUV, gVV, delta);
}
/// The 3D distance squared between two nearby parametric points, with the form evaluated at \a from.
double distanceSq(const Vec2& from, const Vec2& to) const { return lengthSq(from, to - from); }
/// The largest 3D length a unit parametric displacement spans at \a uv: the square root of the larger eigenvalue.
double maxScale(const Vec2& uv) const
{
if (evaluate == nullptr) {
return 1.;
}
double gUU = 1.;
double gUV = 0.;
double gVV = 1.;
evaluate(context, uv, gUU, gUV, gVV);
const double trace = gUU + gVV;
const double determinant = gUU * gVV - gUV * gUV;
// the eigenvalues of a symmetric 2x2 form, guarded against a slightly negative discriminant
const double discriminant = std::max(0., trace * trace - 4. * determinant);
return std::sqrt(std::max(0., 0.5 * (trace + std::sqrt(discriminant))));
}
};
/// A ParametricMetric that defers to \a surface, which must outlive it. Every use here is a
/// surface building its own wires inside initialize(), so that holds by construction.
template <typename Surface>
inline ParametricMetric parametricMetricOf(const Surface& surface)
{
return {[](const void* context, const Vec2& uv, double& gUU, double& gUV, double& gVV) {
static_cast<const Surface*>(context)->parametricMetric(uv, gUU, gUV, gVV);
},
&surface};
}
inline double dot(const Vec3& firstVector, const Vec3& secondVector)
{
return firstVector.xCoord * secondVector.xCoord + firstVector.yCoord * secondVector.yCoord +
firstVector.zCoord * secondVector.zCoord;
}
inline Vec3 cross(const Vec3& firstVector, const Vec3& secondVector)
{
return {firstVector.yCoord * secondVector.zCoord - firstVector.zCoord * secondVector.yCoord,
firstVector.zCoord * secondVector.xCoord - firstVector.xCoord * secondVector.zCoord,
firstVector.xCoord * secondVector.yCoord - firstVector.yCoord * secondVector.xCoord};
}
inline double normSq(const Vec3& vector)
{
return dot(vector, vector);
}
inline double norm(const Vec3& vector)
{
return std::sqrt(normSq(vector));
}
inline Vec3 normalized(const Vec3& vector)
{
const double vectorNorm = norm(vector);
if (vectorNorm <= kTolerance) {
return {};
}
return vector * (1. / vectorNorm);
}
inline double component(const Vec3& vector, int dimension)
{
if (dimension == 0) {
return vector.xCoord;
}
if (dimension == 1) {
return vector.yCoord;
}
return vector.zCoord;
}
inline void assignComponent(Vec3& vector, int dimension, double value)
{
if (dimension == 0) {
vector.xCoord = value;
} else if (dimension == 1) {
vector.yCoord = value;
} else {
vector.zCoord = value;
}
}
inline bool finite(const Vec2& point)
{
return std::isfinite(point.uCoord) && std::isfinite(point.vCoord);
}
inline bool finite(const Vec3& point)
{
return std::isfinite(point.xCoord) && std::isfinite(point.yCoord) && std::isfinite(point.zCoord);
}
inline double distanceSq(const Vec2& firstPoint, const Vec2& secondPoint)
{
const double deltaU = firstPoint.uCoord - secondPoint.uCoord;
const double deltaV = firstPoint.vCoord - secondPoint.vCoord;
return deltaU * deltaU + deltaV * deltaV;
}
inline double distanceSq(const Vec3& firstPoint, const Vec3& secondPoint)
{
return normSq(firstPoint - secondPoint);
}
inline double cross2D(const Vec2& firstVector, const Vec2& secondVector)
{
return firstVector.uCoord * secondVector.vCoord - firstVector.vCoord * secondVector.uCoord;
}
inline double pointSegmentDistanceSq(const Vec2& point, const Vec2& segmentStart, const Vec2& segmentEnd)
{
const Vec2 segmentVector = segmentEnd - segmentStart;
const double segmentLengthSq = segmentVector.uCoord * segmentVector.uCoord + segmentVector.vCoord * segmentVector.vCoord;
if (segmentLengthSq <= kToleranceSq) {
return distanceSq(point, segmentStart);
}
const double pointProjection = ((point.uCoord - segmentStart.uCoord) * segmentVector.uCoord +
(point.vCoord - segmentStart.vCoord) * segmentVector.vCoord) /
segmentLengthSq;
const double clampedProjection = std::max(0., std::min(1., pointProjection));
const Vec2 closestPoint{segmentStart.uCoord + clampedProjection * segmentVector.uCoord,
segmentStart.vCoord + clampedProjection * segmentVector.vCoord};
return distanceSq(point, closestPoint);
}
inline double pointSegmentDistanceSq(const Vec3& point, const Vec3& segmentStart, const Vec3& segmentEnd)
{
const Vec3 segmentVector = segmentEnd - segmentStart;
const double segmentLengthSq = normSq(segmentVector);
if (segmentLengthSq <= kToleranceSq) {
return distanceSq(point, segmentStart);
}
const double pointProjection = dot(point - segmentStart, segmentVector) / segmentLengthSq;
const double clampedProjection = std::max(0., std::min(1., pointProjection));
const Vec3 closestPoint = segmentStart + segmentVector * clampedProjection;
return distanceSq(point, closestPoint);
}
/// \name First fundamental forms by surface family, shared by the surfaces and the sidecar reader
/// @{
/// Plane: the frame axes carry the domain's units and need be neither unit nor orthogonal, which
/// makes this the only family with a cross term.
inline void planeParametricMetric(const Vec3& axisU, const Vec3& axisV, double& gUU, double& gUV, double& gVV)
{
gUU = dot(axisU, axisU);
gUV = dot(axisU, axisV);
gVV = dot(axisV, axisV);
}
/// Cylinder, (u, v) = (phi[rad], h[cm]).
inline void cylinderParametricMetric(double radius, double& gUU, double& gUV, double& gVV)
{
gUU = radius * radius;
gUV = 0.;
gVV = 1.;
}
/// Cone, (u, v) = (phi[rad], h[cm]). \a radiusAtHeight is r(v), which reaches zero at an apex;
/// a step in h also walks along the slope, hence gVV > 1.
inline void coneParametricMetric(double radiusAtHeight, double slope, double& gUU, double& gUV, double& gVV)
{
gUU = radiusAtHeight * radiusAtHeight;
gUV = 0.;
gVV = 1. + slope * slope;
}
/// Sphere, (u, v) = (phi[rad], theta[rad]). The azimuthal scale is the radius of the parallel at
/// \a theta, so it vanishes at either pole.
inline void sphereParametricMetric(double radius, double theta, double& gUU, double& gUV, double& gVV)
{
const double parallelRadius = radius * std::sin(theta);
gUU = parallelRadius * parallelRadius;
gUV = 0.;
gVV = radius * radius;
}
/// Torus, (u, v) = (phiRing[rad], phiTube[rad]). The ring scale runs from R - r to R + r.
inline void torusParametricMetric(double majorRadius, double minorRadius, double phiTube, double& gUU, double& gUV,
double& gVV)
{
const double ringRadius = majorRadius + minorRadius * std::cos(phiTube);
gUU = ringRadius * ringRadius;
gUV = 0.;
gVV = minorRadius * minorRadius;
}
/// @}
inline bool sameIntersection(double firstDistance, double secondDistance)
{
return std::abs(firstDistance - secondDistance) <=
kIntersectionTolerance * std::max(1., std::max(std::abs(firstDistance), std::abs(secondDistance)));
}
/// One ray/surface intersection: the ray parameter and the outward normal; a quadric patch can give several per ray.
struct RayHit {
double distance = 0.;
Vec3 normal;
/// The hit lies within the trim's on-boundary band, so its inside/outside side is a tie-break, not data.
bool onTrimBoundary = false;
};
/// One straight line segment of a polygon wire, in a surface's parametric (u, v) domain.
struct SurfaceEdge {
Vec2 start;
Vec2 end;
Vec2 direction() const { return end - start; }
double lengthSq() const
{
const Vec2 delta = end - start;
return delta.uCoord * delta.uCoord + delta.vCoord * delta.vCoord;
}
bool degenerate() const { return lengthSq() <= kToleranceSq; }
/// Squared distance from a parametric point to this edge.
double distanceSq(const Vec2& point) const { return pointSegmentDistanceSq(point, start, end); }
/// Closest point on this edge to \a point. Returns the projected point and its clamped
/// parameter \a parameter in [0, 1] (0 at start, 1 at end). Degenerate edges return start.
Vec2 closestPoint(const Vec2& point, double& parameter) const
{
const Vec2 segmentVector = end - start;
const double segmentLengthSq = segmentVector.uCoord * segmentVector.uCoord +
segmentVector.vCoord * segmentVector.vCoord;
if (segmentLengthSq <= kToleranceSq) {
parameter = 0.;
return start;
}
const double projection = ((point.uCoord - start.uCoord) * segmentVector.uCoord +
(point.vCoord - start.vCoord) * segmentVector.vCoord) /
segmentLengthSq;
parameter = std::max(0., std::min(1., projection));
return {start.uCoord + parameter * segmentVector.uCoord, start.vCoord + parameter * segmentVector.vCoord};
}
/// Accumulate the edge endpoints into a parametric axis-aligned bounding box.
void extendBounds(Vec2& lower, Vec2& upper) const
{
lower.uCoord = std::min({lower.uCoord, start.uCoord, end.uCoord});
lower.vCoord = std::min({lower.vCoord, start.vCoord, end.vCoord});
upper.uCoord = std::max({upper.uCoord, start.uCoord, end.uCoord});
upper.vCoord = std::max({upper.vCoord, start.vCoord, end.vCoord});
}
};
/// Classification of a parametric point against a closed wire.
enum class WireClassification { Outside,
Boundary,
Inside };
/// The role a wire plays for a bounded surface. Outer wires bound the material, inner wires
/// (holes) subtract from it. The role fixes the expected winding relative to the surface normal.
enum class WireRole { Outer,
Inner };
/// Outcome of wire construction / validation. Valid and Reversed are both usable results;
/// Reversed additionally signals that the orientation had to be normalized (a logged repair).
enum class WireStatus {
Valid, ///< well-formed and already correctly oriented
Reversed, ///< well-formed but re-oriented to match its role (simple, logged repair)
NonFinite, ///< a vertex/edge contained a non-finite coordinate
Open, ///< an explicit edge list did not form a closed loop
TooFewVertices, ///< fewer than three distinct vertices after cleanup
DegenerateVertex, ///< a non-adjacent vertex coincided (self-touching / pinched loop)
ZeroArea ///< the loop encloses no area
};
/// Human-readable description of a wire status, for logging.
inline const char* wireStatusMessage(WireStatus status)
{
switch (status) {
case WireStatus::Valid:
return "valid";
case WireStatus::Reversed:
return "orientation normalized to match wire role";
case WireStatus::NonFinite:
return "wire contains a non-finite vertex";
case WireStatus::Open:
return "wire edges do not form a closed loop";
case WireStatus::TooFewVertices:
return "wire needs at least three distinct vertices";
case WireStatus::DegenerateVertex:
return "wire has a coincident (pinched) vertex";
case WireStatus::ZeroArea:
return "wire has zero area";
}
return "unknown wire status";
}
/// kTolerance as a parametric separation at \a uv: the floor of every trim's on-boundary band.
inline double trimLengthFloor(const ParametricMetric& metric, const Vec2& uv)
{
const double scale = metric.maxScale(uv);
return scale > kTolerance ? kTolerance / scale : 0.;
}
/// One closed, oriented polygon loop in a surface's parametric domain: outer loops wind counter-clockwise, holes clockwise.
struct SurfaceWire {
std::vector<Vec2> vertices;
WireRole role = WireRole::Outer;
/// For each stored segment its input segment, or -1 once a vertex was dropped; sidecar v3 edge identities key on it.
std::vector<int> sourceEdge;
int edgeCount() const { return static_cast<int>(vertices.size()); }
/// The stored segment that came from input segment \a inputIndex, or -1 if there is none.
int storedIndexOfSource(int inputIndex) const
{
for (size_t index = 0; index < sourceEdge.size(); ++index) {
if (sourceEdge[index] == inputIndex) {
return static_cast<int>(index);
}
}
return -1;
}
SurfaceEdge edge(int index) const
{
const int count = edgeCount();
return {vertices[index % count], vertices[(index + 1) % count]};
}
/// Build and validate the wire from an implicitly closed vertex ring; \a metric turns separations into 3D lengths.
bool initialize(const std::vector<Vec2>& inputVertices, WireRole wireRole, WireStatus& status,
const ParametricMetric& metric = {})
{
role = wireRole;
vertices.clear();
vertices.reserve(inputVertices.size());
bool droppedAVertex = false;
for (const auto& vertex : inputVertices) {
if (!finite(vertex)) {
status = WireStatus::NonFinite;
return false;
}
if (vertices.empty() || metric.distanceSq(vertices.back(), vertex) > kToleranceSq) {
vertices.push_back(vertex);
} else {
droppedAVertex = true;
}
}
// drop an explicit closing duplicate (first == last)
if (vertices.size() > 1 && metric.distanceSq(vertices.front(), vertices.back()) <= kToleranceSq) {
vertices.pop_back();
droppedAVertex = true;
}
if (vertices.size() < 3) {
status = WireStatus::TooFewVertices;
return false;
}
// reject self-touching loops (non-adjacent coincident vertices)
for (size_t firstIndex = 0; firstIndex < vertices.size(); ++firstIndex) {
for (size_t secondIndex = firstIndex + 1; secondIndex < vertices.size(); ++secondIndex) {
if (metric.distanceSq(vertices[firstIndex], vertices[secondIndex]) <= kToleranceSq) {
status = WireStatus::DegenerateVertex;
return false;
}
}
}
const double area = signedArea();
if (std::abs(area) <= kAreaTolerance) {
status = WireStatus::ZeroArea;
return false;
}
// segment i is input segment i unless a vertex was dropped; then it is unknown
const int storedCount = static_cast<int>(vertices.size());
sourceEdge.assign(static_cast<size_t>(storedCount), -1);
if (!droppedAVertex) {
for (int index = 0; index < storedCount; ++index) {
sourceEdge[static_cast<size_t>(index)] = index;
}
}
// outer wires must wind CCW (positive area), inner wires CW (negative area)
const bool wantPositiveArea = (role == WireRole::Outer);
if ((area > 0.) != wantPositiveArea) {
std::reverse(vertices.begin(), vertices.end());
// reversing the ring maps old vertex k to new index n-1-k, so new segment j spans old
// vertices n-1-j and n-2-j, i.e. it is old segment n-2-j traversed backwards
std::vector<int> reversedSource(static_cast<size_t>(storedCount), -1);
for (int index = 0; index < storedCount; ++index) {
reversedSource[static_cast<size_t>(index)] =
sourceEdge[static_cast<size_t>((storedCount - 2 - index % storedCount + 2 * storedCount) % storedCount)];
}
sourceEdge.swap(reversedSource);
status = WireStatus::Reversed;
return true;
}
status = WireStatus::Valid;
return true;
}
/// Build and validate the wire from an ordered edge list, joining within \a joinTolerance through \a metric, as CurveWire does.
bool initializeFromEdges(const std::vector<SurfaceEdge>& edges, WireRole wireRole, WireStatus& status,
const ParametricMetric& metric = {}, double joinTolerance = kWireJoinTolerance)
{
if (edges.size() < 3) {
status = WireStatus::TooFewVertices;
return false;
}
for (size_t edgeIndex = 0; edgeIndex < edges.size(); ++edgeIndex) {
if (!finite(edges[edgeIndex].start) || !finite(edges[edgeIndex].end)) {
status = WireStatus::NonFinite;
return false;
}
const Vec2& nextStart = edges[(edgeIndex + 1) % edges.size()].start;
if (metric.distanceSq(edges[edgeIndex].end, nextStart) > joinTolerance * joinTolerance) {
status = WireStatus::Open;
return false;
}
}
std::vector<Vec2> ringVertices;
ringVertices.reserve(edges.size());
for (const auto& singleEdge : edges) {
ringVertices.push_back(singleEdge.start);
}
return initialize(ringVertices, wireRole, status, metric);
}
double signedArea() const
{
double area = 0.;
for (size_t vertexIndex = 0; vertexIndex < vertices.size(); ++vertexIndex) {
const auto& currentVertex = vertices[vertexIndex];
const auto& nextVertex = vertices[(vertexIndex + 1) % vertices.size()];
area += currentVertex.uCoord * nextVertex.vCoord - nextVertex.uCoord * currentVertex.vCoord;
}
return 0.5 * area;
}
/// Accumulate this wire's vertices into a parametric axis-aligned bounding box. This is
/// independent of any concrete surface so cylinders, spheres and cones can reuse it.
void parametricBounds(Vec2& lower, Vec2& upper) const
{
for (const auto& vertex : vertices) {
lower.uCoord = std::min(lower.uCoord, vertex.uCoord);
lower.vCoord = std::min(lower.vCoord, vertex.vCoord);
upper.uCoord = std::max(upper.uCoord, vertex.uCoord);
upper.vCoord = std::max(upper.vCoord, vertex.vCoord);
}
}
/// The de-duplicated vertex ring, closed back to its first vertex.
std::vector<Vec2> sampledBoundary() const
{
std::vector<Vec2> samples;
if (vertices.empty()) {
return samples;
}
samples.reserve(vertices.size() + 1);
samples.insert(samples.end(), vertices.begin(), vertices.end());
samples.push_back(vertices.front());
return samples;
}
/// Classify against the polygon with an on-boundary half-width of \a band, in parametric units.
WireClassification classify(const Vec2& point, double band) const
{
const double bandSq = band * band;
bool inside = false;
for (size_t vertexIndex = 0; vertexIndex < vertices.size(); ++vertexIndex) {
const auto& segmentStart = vertices[vertexIndex];
const auto& segmentEnd = vertices[(vertexIndex + 1) % vertices.size()];
if (pointSegmentDistanceSq(point, segmentStart, segmentEnd) <= bandSq) {
return WireClassification::Boundary;
}
const bool crossesScanline = (segmentStart.vCoord > point.vCoord) != (segmentEnd.vCoord > point.vCoord);
if (crossesScanline) {
const double intersectionU = segmentStart.uCoord + (point.vCoord - segmentStart.vCoord) *
(segmentEnd.uCoord - segmentStart.uCoord) /
(segmentEnd.vCoord - segmentStart.vCoord);
if (point.uCoord < intersectionU) {
inside = !inside;
}
}
}
return inside ? WireClassification::Inside : WireClassification::Outside;
}
/// \a metric sizes the band only: a polygon is exact, so its band is the length floor.
WireClassification classify(const Vec2& point, const ParametricMetric& metric = {}) const
{
return classify(point, trimLengthFloor(metric, point));
}
};
inline bool pointInTriangle(const Vec2& point, const Vec2& firstVertex, const Vec2& secondVertex,
const Vec2& thirdVertex)
{
const double firstCross = cross2D(secondVertex - firstVertex, point - firstVertex);
const double secondCross = cross2D(thirdVertex - secondVertex, point - secondVertex);
const double thirdCross = cross2D(firstVertex - thirdVertex, point - thirdVertex);
return firstCross >= -kTolerance && secondCross >= -kTolerance && thirdCross >= -kTolerance;
}
/// Ear-clipping triangulation of a simple (non-self-intersecting) parametric wire.
inline std::vector<std::array<int, 3>> triangulateSimpleWire(const SurfaceWire& wire)
{
std::vector<int> remainingIndices;
remainingIndices.reserve(wire.vertices.size());
if (wire.signedArea() >= 0.) {
for (size_t vertexIndex = 0; vertexIndex < wire.vertices.size(); ++vertexIndex) {
remainingIndices.push_back(static_cast<int>(vertexIndex));
}
} else {
for (size_t reverseIndex = wire.vertices.size(); reverseIndex > 0; --reverseIndex) {
remainingIndices.push_back(static_cast<int>(reverseIndex - 1));
}
}
std::vector<std::array<int, 3>> triangles;
size_t guardCounter = 0;
while (remainingIndices.size() > 3 && guardCounter++ < wire.vertices.size() * wire.vertices.size()) {
bool clippedEar = false;
for (size_t indexPosition = 0; indexPosition < remainingIndices.size(); ++indexPosition) {
const int previousIndex = remainingIndices[(indexPosition + remainingIndices.size() - 1) % remainingIndices.size()];
const int currentIndex = remainingIndices[indexPosition];
const int nextIndex = remainingIndices[(indexPosition + 1) % remainingIndices.size()];
const auto& previousVertex = wire.vertices[previousIndex];
const auto& currentVertex = wire.vertices[currentIndex];
const auto& nextVertex = wire.vertices[nextIndex];
if (cross2D(currentVertex - previousVertex, nextVertex - currentVertex) <= kTolerance) {
continue;
}
bool containsOtherVertex = false;
for (int candidateIndex : remainingIndices) {
if (candidateIndex == previousIndex || candidateIndex == currentIndex || candidateIndex == nextIndex) {
continue;
}
if (pointInTriangle(wire.vertices[candidateIndex], previousVertex, currentVertex, nextVertex)) {
containsOtherVertex = true;
break;
}
}
if (containsOtherVertex) {
continue;
}
triangles.push_back({previousIndex, currentIndex, nextIndex});
remainingIndices.erase(remainingIndices.begin() + indexPosition);
clippedEar = true;
break;
}
if (!clippedEar) {
break;
}
}
if (remainingIndices.size() == 3) {
triangles.push_back({remainingIndices[0], remainingIndices[1], remainingIndices[2]});
}
return triangles;
}
/// \name Angular constants for parametric arc curves
/// @{
inline constexpr double kPi = 3.14159265358979323846;
inline constexpr double kTwoPi = 2. * kPi;
inline constexpr double kHalfPi = 0.5 * kPi;
/// Chords per full-circle arc for display and rims, shared by all surfaces so shared rims match; divisible by 4.
inline constexpr int kArcSamples = 24;
/// @}
/// Angular tolerance equivalent to a kTolerance arc length at the given radius.
inline double angularTolerance(double radius)
{
return kTolerance / std::max(radius, kTolerance);
}
/// Widest angular span of one cover box: pi/4, eight boxes per full turn.
inline constexpr double kCoverChunkAngle = kPi / 4.;
/// The number of kCoverChunkAngle chunks covering an angular span: at least one, and never more
/// than a full turn takes, since a sweep may overshoot 2pi by a rounding hair.
inline int coverChunkCount(double span)
{
constexpr int fullTurnChunks = static_cast<int>(kTwoPi / kCoverChunkAngle); // eight
return std::max(1, std::min(fullTurnChunks, static_cast<int>(std::ceil(span / kCoverChunkAngle))));
}
/// Exact range of a cos(t) + b sin(t) over [t0, t1], at most a turn: the endpoint values, widened to the amplitude at a crest.
inline void sinusoidRange(double a, double b, double t0, double t1, double& minimum, double& maximum)
{
const double atStart = a * std::cos(t0) + b * std::sin(t0);
const double atEnd = a * std::cos(t1) + b * std::sin(t1);
minimum = std::min(atStart, atEnd);
maximum = std::max(atStart, atEnd);
const double amplitude = std::hypot(a, b);
const double crest = std::atan2(b, a);
// shifted into [t0, t0 + 2pi), where a span of at most a full turn makes "<= t1" exactly the
// test for falling inside the interval
const double crestInRange = crest - kTwoPi * std::floor((crest - t0) / kTwoPi);
if (crestInRange <= t1) {
maximum = amplitude;
}
const double trough = crest + kPi;
const double troughInRange = trough - kTwoPi * std::floor((trough - t0) / kTwoPi);
if (troughInRange <= t1) {
minimum = -amplitude;
}
}
/// One end of sinusoidRange, for the doubly swept covers of the sphere and the torus.
/// @{
inline double sinusoidMinimum(double a, double b, double t0, double t1)
{
double minimum = 0.;
double maximum = 0.;
sinusoidRange(a, b, t0, t1, minimum, maximum);
return minimum;
}
inline double sinusoidMaximum(double a, double b, double t0, double t1)
{
double minimum = 0.;
double maximum = 0.;
sinusoidRange(a, b, t0, t1, minimum, maximum);
return maximum;
}
/// @}
/// True if \a angle lies within the angular range [start, start + sweep] (sweep in (0, 2pi]),
/// allowing \a tolerance on both ends and treating a >= 2pi sweep as the full circle.
inline bool angleInSweepRange(double angle, double start, double sweep, double tolerance)
{
if (sweep >= kTwoPi - kTolerance) {
return true;
}
double delta = angle - start;
delta -= kTwoPi * std::floor(delta / kTwoPi); // wrap into [0, 2pi)
return delta <= sweep + tolerance || delta >= kTwoPi - tolerance;
}
/// The \a n-point Gauss-Legendre nodes and weights on [-1, 1], by Newton iteration on P_n.
inline void gaussLegendre(int n, std::vector<double>& nodes, std::vector<double>& weights)
{
nodes.assign(std::max(n, 1), 0.);
weights.assign(std::max(n, 1), 0.);
if (n < 1) {
return;
}
for (int i = 0; i < n; ++i) {
double root = std::cos(kPi * (i + 0.75) / (n + 0.5)); // asymptotic initial guess
double derivative = 1.;
for (int iteration = 0; iteration < 100; ++iteration) {
double previous = 1.;
double current = root;
for (int degreeIndex = 2; degreeIndex <= n; ++degreeIndex) {
const double next = ((2 * degreeIndex - 1) * root * current - (degreeIndex - 1) * previous) / degreeIndex;
previous = current;
current = next;
}
derivative = n * (root * current - previous) / (root * root - 1.);
const double delta = current / derivative;
root -= delta;
if (std::abs(delta) < 1.e-15) {
break;
}
}
nodes[i] = root;
weights[i] = 2. / ((1. - root * root) * derivative * derivative);
}
}
/// Fill \a roots with the real roots of w^3 + P w + Q = 0 and return their count: Cardano, or the trigonometric form for three.
/// The branch is chosen by the sign of P, not by a tolerance, so every input is covered.
inline int solveDepressedCubic(double coeffP, double coeffQ, std::array<double, 3>& roots)
{
const double discriminant = coeffQ * coeffQ / 4. + coeffP * coeffP * coeffP / 27.;
if (!(coeffP < 0.) || discriminant > 0.) {
const double sqrtDiscriminant = std::sqrt(std::max(0., discriminant));
roots[0] = std::cbrt(-0.5 * coeffQ + sqrtDiscriminant) + std::cbrt(-0.5 * coeffQ - sqrtDiscriminant);
return 1;
}
// three real roots: coeffP < 0 here, so the trigonometric form is well defined
const double magnitude = 2. * std::sqrt(-coeffP / 3.);
const double cosineArgument = std::max(-1., std::min(1., 3. * coeffQ / (coeffP * magnitude)));
const double baseAngle = std::acos(cosineArgument);
for (int branch = 0; branch < 3; ++branch) {
roots[branch] = magnitude * std::cos((baseAngle - kTwoPi * branch) / 3.);
}
return 3;
}
/// Which of solveQuarticReal's branches produced its roots, for the tests.
enum class QuarticBranch {
NotAQuartic, ///< the leading coefficient vanishes; no roots are produced
Biquadratic, ///< the depressed quartic's odd term is zero, so y^4 + p y^2 + r = 0 is solved directly
Resolvent ///< Ferrari's general branch, through the resolvent cubic
};
/// The real roots of a quartic: at most four, held inline.
struct QuarticRoots {
std::array<double, 4> value{};
int count = 0;
void push_back(double root)
{
assert(count < 4 && "QuarticRoots holds at most four roots");
value[count++] = root;
}
double* begin() { return value.data(); }
double* end() { return value.data() + count; }
const double* begin() const { return value.data(); }
const double* end() const { return value.data() + count; }
size_t size() const { return static_cast<size_t>(count); }
bool empty() const { return count == 0; }
double operator[](size_t index) const { return value[index]; }
};
/// Real roots of a4 x^4 + a3 x^3 + a2 x^2 + a1 x + a0 = 0 (a4 != 0) by Ferrari's method and Newton polishing; a tangential root is a near-equal pair.
/// The root variable is first rescaled by a power of two, exactly, so all branch tests are dimensionless; \a takenBranch reports the branch.
inline QuarticRoots solveQuarticReal(double a4, double a3, double a2, double a1, double a0,
QuarticBranch* takenBranch = nullptr)
{
const auto note = [takenBranch](QuarticBranch branch) {
if (takenBranch) {
*takenBranch = branch;
}
};
note(QuarticBranch::NotAQuartic);
QuarticRoots roots;
// A genuine quartic needs only a non-zero leading coefficient. There is no scale to compare it
// against -- the normalisation below handles any coefficient ratio -- so the test is exact.
if (!(std::abs(a4) > 0.)) {
return roots; // the torus caller guarantees a4 = |dir|^4 > 0
}
// monic x^4 + b x^3 + c x^2 + d x + e
double coeffB = a3 / a4, coeffC = a2 / a4, coeffD = a1 / a4, coeffE = a0 / a4;
if (!std::isfinite(coeffB) || !std::isfinite(coeffC) || !std::isfinite(coeffD) || !std::isfinite(coeffE)) {
return roots; // a4 is denormal-small next to the rest, or an input was not finite
}
// Cauchy root bound rounded up to a power of two, so x = scale * y is exact; x^4 = 0 keeps scale = 1
const double rootBound = std::max({std::abs(coeffB), std::sqrt(std::abs(coeffC)),
std::cbrt(std::abs(coeffD)), std::sqrt(std::sqrt(std::abs(coeffE)))});
int boundExponent = 0;
std::frexp(rootBound, &boundExponent);
const double scale = std::ldexp(1., boundExponent);
coeffB /= scale;
coeffC /= scale * scale;
coeffD /= scale * scale * scale;
coeffE /= scale * scale * scale * scale;
// depress with y = z - b/4: z^4 + p z^2 + q z + r
const double termP = coeffC - 3. * coeffB * coeffB / 8.;
const double termQ = coeffD - coeffB * coeffC / 2. + coeffB * coeffB * coeffB / 8.;
const double termR =
coeffE - coeffB * coeffD / 4. + coeffB * coeffB * coeffC / 16. - 3. * coeffB * coeffB * coeffB * coeffB / 256.;
const double shift = -coeffB / 4.;
auto addQuadraticRoots = [&](double quadB, double quadC) {
const double discriminant = quadB * quadB - 4. * quadC;
if (discriminant < 0.) {
return; // complex pair
}
const double sqrtDiscriminant = std::sqrt(discriminant);
roots.push_back(shift + 0.5 * (-quadB - sqrtDiscriminant));
roots.push_back(shift + 0.5 * (-quadB + sqrtDiscriminant));
};
auto addBiquadraticRoots = [&]() {
// biquadratic z^4 + p z^2 + r = 0
const double discriminant = termP * termP - 4. * termR;
if (discriminant < 0.) {
return;
}
const double sqrtDiscriminant = std::sqrt(discriminant);
for (const double zSquared : {0.5 * (-termP + sqrtDiscriminant), 0.5 * (-termP - sqrtDiscriminant)}) {
if (zSquared >= 0.) {
const double z = std::sqrt(zSquared);
roots.push_back(shift + z);
roots.push_back(shift - z);
}
}
};
// q is zero to the precision of its terms, which normalisation bounds by 1: kQuarticEpsilon over the whole quartic, not over q's terms
bool biquadratic = std::abs(termQ) <= kQuarticEpsilon;
if (!biquadratic) {
note(QuarticBranch::Resolvent);
// resolvent cubic m^3 + p m^2 + (p^2/4 - r) m - q^2/8 = 0; its largest real root is > 0
const double cubicA2 = termP;
const double cubicA1 = termP * termP / 4. - termR;
const double cubicA0 = -termQ * termQ / 8.;
const double cubicP = cubicA1 - cubicA2 * cubicA2 / 3.;
const double cubicQ = 2. * cubicA2 * cubicA2 * cubicA2 / 27. - cubicA2 * cubicA1 / 3. + cubicA0;
std::array<double, 3> cubicRoots;
const int cubicCount = solveDepressedCubic(cubicP, cubicQ, cubicRoots);
double resolvent = 0.;
for (int index = 0; index < cubicCount; ++index) {
resolvent = std::max(resolvent, cubicRoots[index] - cubicA2 / 3.);
}
// a resolvent below the resolution of its cubic is noise; then the biquadratic branch is the better-conditioned answer
const double resolventScale = std::max({std::abs(cubicA2), std::sqrt(std::abs(cubicA1)),
std::cbrt(std::abs(cubicA0))});
if (resolvent > kQuarticEpsilon * resolventScale) {
const double sqrtTwoResolvent = std::sqrt(2. * resolvent);
const double linearTerm = sqrtTwoResolvent * termQ / (4. * resolvent);
addQuadraticRoots(-sqrtTwoResolvent, termP / 2. + resolvent + linearTerm);
addQuadraticRoots(sqrtTwoResolvent, termP / 2. + resolvent - linearTerm);
} else {
biquadratic = true;
}
}
if (biquadratic) {
note(QuarticBranch::Biquadratic);
addBiquadraticRoots();
}
// Newton polish against the monic quartic; a step longer than the Cauchy bound 2, or non-finite, is rejected
auto quartic = [&](double x) { return (((x + coeffB) * x + coeffC) * x + coeffD) * x + coeffE; };
auto quarticDerivative = [&](double x) { return ((4. * x + 3. * coeffB) * x + 2. * coeffC) * x + coeffD; };
for (double& root : roots) {
for (int iteration = 0; iteration < 2; ++iteration) {
const double step = quartic(root) / quarticDerivative(root);
if (std::isfinite(step) && std::abs(step) <= 2.) {
root -= step;
}
}
}
for (double& root : roots) {
root *= scale; // exact: scale is a power of two
}
return roots;
}
/// Kind of a 2D trimmed boundary curve.
enum class CurveKind { Line, ///< straight line segment
Arc, ///< circular arc
BSpline ///< clamped (rational) B-spline curve
};
/// One trimmed boundary curve in a surface's (u, v) domain: a line segment, a circular arc or a clamped (rational) B-spline.
struct Curve2D {
CurveKind kind = CurveKind::Line;
Vec2 lineStart; ///< line: start point (unused for arcs)
Vec2 lineEnd; ///< line: end point (unused for arcs)
Vec2 center; ///< arc: circle centre (unused for lines)
double radius = 0.; ///< arc: circle radius
double startAngle = 0.; ///< arc: start angle [rad]
double endAngle = 0.; ///< arc: end angle [rad] (sweep = endAngle - startAngle)
/// \name B-spline data (kind == BSpline): poles, optional weights and a clamped knot vector; the curve parameter runs on [0, 1]. @{
int degree = 0;
std::vector<Vec2> poles;
std::vector<double> weights;
std::vector<double> knots;
/// The flattened on-curve polyline, both ends included; CurveWire::initialize fills it and reversing clears it.
mutable std::vector<Vec2> bsplineCache;
/// @}
/// \name Loop-canonical endpoints: the seam vertices the curve's neighbours agree on, substituted at the polyline's ends
/// @{