Algorithm Search⌘K

Algorithmresearch

Delaunay refinement surface meshing

Also called Boissonnat-Oudot surface mesher.

Boissonnat and Oudot's mesher that inserts points of a smooth surface until the restricted Delaunay triangulation is a good, homeomorphic approximation.

Time
O(n^3) worst
Space
O(n^2) extra
Where
n = the number of output vertices
Properties
deterministicnot exactiterative
Origin
Jean Daniel Boissonnat, Steve Oudot, 2005

Delaunay refinement surface meshing builds a triangle mesh of a smooth closed surface SS by choosing points on SS one at a time. It keeps the 3D Delaunay triangulation of the points chosen so far and reads off the restricted Delaunay triangulation: the triangles whose dual Voronoi edge meets SS. Each place where such an edge meets SS is the center of an empty ball that touches the three corners of the triangle. If the ball is larger than a user size σ\sigma at its center, its center is added. Boissonnat and Oudot (2005) proved that the loop stops, and that with σ\sigma below about 0.0910.091 times the local feature size, the output is homeomorphic to SS and close to it. The surface is used only through an oracle that intersects segments with it.

In plain words

Scatter a few points on the surface. Build their 3D Delaunay triangulation, then ask, for each triangle, whether the line of points equally far from its three corners crosses the surface between the right limits. Where it does, a ball centered on the surface touches the three corners and contains no other point. A big ball means a big hole in the sample, so put a new point at its center and repeat. When every such ball is smaller than the size you asked for, the triangles you found form the mesh. The proof says that a small enough size gives the right shape. Tests show that much larger sizes still give the right shape, and that too large a size does not.

The problem

The input is a smooth (C2C^2) closed surface S⊂R3S \subset \mathbb{R}^3 and a size function σ:S→R\sigma : S \to \mathbb{R} that is positive and 1-Lipschitz. The surface is known through an oracle that, given a segment or a ray, returns the points where it meets SS. The output is a finite sample E⊂SE \subset S and its restricted Delaunay triangulation Del∣S(E)\mathrm{Del}|_S(E).

The medial axis of SS is the closure of the set of points with two or more nearest points on SS, and dM(x)d_M(x) is the distance from x∈Sx \in S to it, also called the local feature size. Let V(E)V(E) be the union of the Voronoi edges of EE. For a triangle ff of the Delaunay triangulation whose dual Voronoi edge meets SS at cc, the ball B(c,r)B(c, r) through the corners of ff is a surface Delaunay ball. It contains no point of EE in its interior. Following Definition 2.2 of the paper, EE is a loose ε\varepsilon-sample when

  1. every x∈S∩V(E)x \in S \cap V(E) has a point of EE within ε dM(x)\varepsilon\, d_M(x), that is, every surface Delaunay ball has radius at most ε dM\varepsilon\, d_M at its center, and
  2. Del∣S(E)\mathrm{Del}|_S(E) has a vertex on every connected component of SS.

An ε\varepsilon-sample in the sense of Amenta and Bern, with every point of SS within ε dM\varepsilon\, d_M of EE, is a loose ε\varepsilon-sample when ε<0.1\varepsilon < 0.1 (Lemma 2.3).

This page makes three kinds of claim.

  • Proved bounds, cited. Let ε0≈0.091\varepsilon_0 \approx 0.091 be the smallest positive ε\varepsilon with 2ε1−8ε+arcsin⁡ε1−ε≥π4\frac{2\varepsilon}{1 - 8\varepsilon} + \arcsin\frac{\varepsilon}{1 - \varepsilon} \ge \frac{\pi}{4} (Section 2.3 of the paper). For a loose ε\varepsilon-sample with ε≤ε0\varepsilon \le \varepsilon_0: Del∣S(E)\mathrm{Del}|_S(E) is a 2-manifold without boundary (Theorem 4.3); the nearest point map π\pi restricted to it is a homeomorphism onto SS, and the two are ambient isotopic (Theorem 4.4); the Hausdorff distance between them is at most 4.5 ε2sup⁡SdM4.5\,\varepsilon^2 \sup_S d_M (Theorem 4.5); and ∣E∣≥2(1−g)+25π μ(S)/ε2|E| \ge 2(1 - g) + \frac{2}{5\pi}\, \mu(S) / \varepsilon^2, where gg is the genus and μ(S)=∬SdM−2\mu(S) = \iint_S d_M^{-2} (Theorem 5.1). For the algorithm: it terminates for every positive 1-Lipschitz σ\sigma (Lemma 8.1); if σ≤ε dM\sigma \le \varepsilon\, d_M the output is a loose ε\varepsilon-sample (Lemma 8.2); and if σ≤dM\sigma \le d_M the points inserted by the loop number at most 643π⋅4∬Sσ−2=2563π∬Sσ−2≈27.2∬Sσ−2\frac{64}{3\pi} \cdot 4 \iint_S \sigma^{-2} = \frac{256}{3\pi} \iint_S \sigma^{-2} \approx 27.2 \iint_S \sigma^{-2}, since the proof of Lemma 8.3 shows they are (12,σ)(\frac12, \sigma)-sparse and Theorem 5.4 bounds a (κ,φ)(\kappa, \varphi)-sparse sample by 643π1κ2∬Sφ−2\frac{64}{3\pi} \frac{1}{\kappa^2} \iint_S \varphi^{-2}. So the topological guarantee needs σ<0.091 dM\sigma < 0.091\, d_M.
  • Proved here. The oracle used by the implementation answers exactly whether a Voronoi edge meets SS; the dual Voronoi edge of a triangle is the segment between the circumcenters of its two tetrahedra, or a ray for a hull triangle; recomputing only the triangles of changed tetrahedra keeps Del∣S(E)\mathrm{Del}|_S(E) correct; the loop stops even though new points are rounded to an integer grid; persistent facets survive. See proofs/correctness.md.
  • Measured, no guarantee. On a sphere of radius RR (dM=Rd_M = R) and a torus with tube radius rr and Rtorus=3rR_{\text{torus}} = 3r (dM=rd_M = r), the output was a closed surface with the right Euler characteristic, every edge in two triangles, for every σ\sigma tried: from 0.09R0.09R to 3R3R on the sphere, and from 0.5r0.5r to 1.5r1.5r on the torus, 1616 times the proved threshold. On the torus it failed at σ=2r\sigma = 2r for each of the five seeds tried. The sizes were well inside the proved bounds: at σ=0.09R\sigma = 0.09 R on the sphere the run gave 10501050 points, against the lower bound 2+25π⋅4π/0.0081≈2002 + \frac{2}{5\pi} \cdot 4\pi / 0.0081 \approx 200 and the upper bound 12+2563π⋅4π/0.0081≈42,00012 + \frac{256}{3\pi} \cdot 4\pi / 0.0081 \approx 42{,}000. The proved constants are much worse than the measured ones.

The algorithm

The mesher keeps the 3D Delaunay triangulation DD of EE, with a ghost tetrahedron on each face of the convex hull, so that every triangle has two neighbors. For a triangle ff with neighbors t1,t2t_1, t_2, the dual Voronoi edge is the segment between their circumcenters, or, if t2t_2 is a ghost, the ray from the circumcenter of t1t_1 along the outward normal of ff. The oracle returns the points of SS on it.

  1. DELAUNAY-SURFACE-MESHING(S, σ)
  2. 1E ← for one or more seed points x on each component of S, three points of S near x that form a persistent facet
  3. 2D ← the Delaunay triangulation of E, with ghost tetrahedra on the hull faces
  4. 3for each triangle f of D: C(f) ← the points where the Voronoi edge dual to f meets S, found by the oracle
  5. 4while some triangle f has c in C(f) whose ball has radius r = |c - a| > σ(c), for a corner a of f:
  6. 5take the pair (f, c) with the largest r / σ(c)
  7. 6insert c into E and update D by Bowyer-Watson insertion
  8. 7recompute C(g) for each triangle g of a removed or new tetrahedron, and forget the triangles that are gone
  9. 8return E and Del|S(E), the triangles f with C(f) not empty

The paper takes the bad balls from a list in any order; picking the worst first is this implementation's choice. Line L1 follows Section 7 of the paper. Around each seed xx, take a ball BxB_x of radius below min⁡{16dist(x,other seeds), dM(x), 16σ(x)}\min\{\frac16 \mathrm{dist}(x, \text{other seeds}),\ d_M(x),\ \frac16 \sigma(x)\} and pick three points of S∩BxS \cap B_x such that the line through their circumcenter, normal to their plane, meets SS inside BxB_x. The resulting facet has a surface Delaunay ball of radius at most 13σ\frac13 \sigma; Lemma 7.1 shows such a persistent facet stays in Del∣S(E)\mathrm{Del}|_S(E) to the end, which gives Condition 2.

The implementation meshes a sphere and a torus, both zero sets of a polynomial FF with integer coefficients. All points have integer coordinates. A circumcenter is N/WN / W with integer NN and WW, so a Voronoi edge is the set of (A+sB)/W(A + sB)/W for ss in [0,1][0, 1] or [0,∞)[0, \infty), and WdF((A+sB)/W)W^d F((A + sB)/W) is a polynomial in ss with integer coefficients. A Sturm sequence counts its roots in the interval exactly; bisection then locates each root to within 18\frac18 of a unit, and the center is rounded to the grid. Orientation and insphere signs are exact integer computations. Radii and σ\sigma are compared in floating point; this only decides which balls count as bad.

Example

A sphere of radius R=220R = 2^{20} with σ=R/2\sigma = R/2 and seed 1. Four seeds at the corners of a randomly rotated regular tetrahedron give 1212 starting points. Their restricted Delaunay triangulation has 2020 triangles: the 44 persistent facets, whose balls have r/σ=0.082r / \sigma = 0.082, and 1616 triangles with bad balls, the worst at r/σ=2.256r / \sigma = 2.256. Each row shows the state before the next insertion.

insertions points triangles of Del|S(E) bad balls worst r / σ
0 12 20 16 2.256
4 16 28 24 1.793
10 22 40 27 1.233
22 34 64 11 1.051
28 40 76 1 1.000
29 41 78 0 none

At every step the restricted triangulation is a triangulated sphere with 2V−42V - 4 triangles. The output has 4141 points, 7878 triangles and 117117 edges, each in exactly two triangles, so its Euler characteristic is 22, and the 44 persistent facets are still there. Every vertex is within one grid unit of SS (on a radius of about a million), and the triangles found from the Delaunay triangulation are exactly those found by testing every triple of points against the definition. Here σ=0.5 dM\sigma = 0.5\, d_M, more than five times the proved threshold, so the topology is correct without a guarantee.

The torus with R=3⋅218R = 3 \cdot 2^{18} and r=218r = 2^{18} behaves the same at σ=1.5 r\sigma = 1.5\, r: 4040 points, 8080 triangles, Euler characteristic 00. At σ=2r\sigma = 2r the loop stops after 2020 points with 3030 triangles, some edges in one, three or four triangles, and Euler characteristic 66. The surface Delaunay balls are all small enough, yet the output is not a surface: the threshold matters, though the proved one is far too cautious.

Correctness

Termination (Lemma 8.1): a point inserted as the center of a bad ball B(c,r)B(c, r) is at distance r>σ(c)≥σ0=min⁡Sσ>0r > \sigma(c) \ge \sigma_0 = \min_S \sigma > 0 from every earlier point, because the ball is empty. So the inserted points are σ0\sigma_0 apart, and a compact surface has room for only finitely many of them. In the implementation the rounded point is at distance at least r−32r - \frac{\sqrt3}{2}, so the same argument works whenever σ0>32\sigma_0 > \frac{\sqrt3}{2} grid units.

Output quality (Lemma 8.2): when the loop stops, no surface Delaunay ball is bad, so every one has r≤σ(c)r \le \sigma(c). If σ≤ε dM\sigma \le \varepsilon\, d_M this is Condition 1 of a loose ε\varepsilon-sample. Condition 2 comes from the persistent facets: if a later point xx fell inside a persistent ball B(ci,ri)B(c_i, r_i) with ri≤13σ(ci)r_i \le \frac13 \sigma(c_i), then σ(x)>23σ(ci)\sigma(x) > \frac23 \sigma(c_i) by the Lipschitz condition, while a corner vv of the facet satisfies ∣v−x∣≤2ri≤23σ(ci)<σ(x)|v - x| \le 2 r_i \le \frac23 \sigma(c_i) < \sigma(x), so vv would lie inside the bad ball centered at xx, which is empty. With ε≤0.091\varepsilon \le 0.091, Theorems 4.3 to 4.5 then give a manifold, homeomorphic and isotopic to SS, within 4.5 ε2sup⁡dM4.5\,\varepsilon^2 \sup d_M.

Bookkeeping: inserting a point changes only the tetrahedra of its cavity, and the dual Voronoi edge of a triangle depends only on its two tetrahedra. So only triangles of removed or new tetrahedra need a new oracle call. The proof file gives the details, including why the segment between the two circumcenters is the whole Voronoi edge.

The theorems assume E⊂SE \subset S. The implementation's points are within 32+18\frac{\sqrt3}{2} + \frac18 grid units of SS, so the theorems are not formally applied to it; the tests check the topology directly.

Proof: The oracle is exact, the dual Voronoi edge is the segment or ray between circumcenters, the incremental update is correct, and the loop stops with persistent facets intactfull

Claim. Assume general position: no five points of EE on a sphere or four on a plane, no Voronoi vertex on SS. Let δ=32\delta = \frac{\sqrt3}{2}, the largest distance that rounding to the integer grid moves a point.

  1. For a line x(s)=(A+sB)/Wx(s) = (A + sB)/W with integer A,B,W>0A, B, W > 0, the polynomial computed for the sphere is W2F(x(s))W^2 F(x(s)) and for the torus W4F(x(s))W^4 F(x(s)), and the Sturm count gives exactly the number of distinct points of SS on the part of the line with ss in the given interval.
  2. Let f=abcf = abc be a triangle of the Delaunay triangulation DD. If both its tetrahedra t1=f∪{d1}t_1 = f \cup \{d_1\} and t2=f∪{d2}t_2 = f \cup \{d_2\} are real, with circumcenters c1,c2c_1, c_2, its dual Voronoi edge (the points whose nearest points in EE include a,b,ca, b, c) is the segment c1c2c_1 c_2. If t2t_2 is a ghost, it is the ray from c1c_1 along the normal of ff that points away from d1d_1.
  3. After an insertion, recomputing the triangles of the removed and the new tetrahedra gives the same restricted triangles and surface balls as computing all of them again.
  4. If σ≥σ0>δ\sigma \ge \sigma_0 > \delta on a neighborhood of SS, the loop stops.
  5. If a facet of the initial sample has a surface Delaunay ball B(ci,ri)B(c_i, r_i) with ri+δ≤13σ(ci)r_i + \delta \le \frac13 \sigma(c_i), it is a restricted triangle at the end.

What is cited. Sturm's theorem: for a square-free polynomial pp with Sturm sequence p0=p,p1=p′,pk+1=−rem(pk−1,pk)p_0 = p, p_1 = p', p_{k+1} = -\mathrm{rem}(p_{k-1}, p_k), the number of distinct real roots in (a,b](a, b] is V(a)−V(b)V(a) - V(b), where VV counts sign changes, zeros dropped. The bounds on the output (homeomorphism for ε≤0.091\varepsilon \le 0.091, Hausdorff distance, size) are Theorems 4.3 to 4.5, 5.1 and 5.4 and Lemmas 8.2 to 8.4 of Boissonnat and Oudot (2005) and are not repeated.

Step 1: the polynomial and the count (part 1). For the sphere F(x)=∣x∣2−R2F(x) = |x|^2 - R^2, so W2F(x(s))=∑k(Ak+sBk)2−R2W2W^2 F(x(s)) = \sum_k (A_k + s B_k)^2 - R^2 W^2, which is what is computed. For the torus F(x)=(∣x∣2+R2−r2)2−4R2(x12+x22)F(x) = (|x|^2 + R^2 - r^2)^2 - 4R^2 (x_1^2 + x_2^2); multiplying by W4W^4 gives q2−4R2W2(X12+X22)q^2 - 4R^2 W^2 (X_1^2 + X_2^2) with X=A+sBX = A + sB and q=∣X∣2+(R2−r2)W2q = |X|^2 + (R^2 - r^2) W^2, which is what is computed. Since W>0W > 0, the roots in ss are the parameters where the line meets SS. All coefficients are integers, so the Sturm sequence is computed exactly in rationals. If the last element of the sequence is not constant, it is gcd⁡(p,p′)\gcd(p, p') up to a factor, and p/gcd⁡(p,p′)p / \gcd(p, p') has the same distinct roots, all simple; the implementation counts with that. A root exactly at the lower end is tested directly by evaluating pp there, and Sturm's theorem counts the rest in (a,b](a, b]. For a ray, the interval is cut at Cauchy's bound 1+max⁡i∣pi/pd∣1 + \max_i |p_i / p_d|, beyond which there are no roots. The count is exact. Each root is then bracketed by exact bisection to an interval of length at most 18⌈∣B∣/W⌉\frac{1}{8 \lceil |B| / W \rceil} in ss, so the computed point is within 18\frac18 of the exact point of SS along the edge, and it lies in the interval.

Step 2: the dual Voronoi edge (part 2). The points equidistant from a,b,ca, b, c form a line ℓ\ell normal to ff through its circumcenter. Parametrize it as x(s)x(s), affine in ss. For a point yy of EE, set

gy(s)=∣y−x(s)∣2−∣a−x(s)∣2=2(a−y)⋅x(s)+∣y∣2−∣a∣2,g_y(s) = |y - x(s)|^2 - |a - x(s)|^2 = 2 (a - y) \cdot x(s) + |y|^2 - |a|^2,

which is affine in ss. The point x(s)x(s) has a,b,ca, b, c among its nearest points exactly when gy(s)≥0g_y(s) \ge 0 for all yy, so the Voronoi edge is the intersection of half-lines, an interval II. A tetrahedron tjt_j of DD has an empty circumsphere, centered at cj=x(sj)c_j = x(s_j), so gy(sj)≥0g_y(s_j) \ge 0 for all yy and sj∈Is_j \in I. By convexity [s1,s2]⊆I[s_1, s_2] \subseteq I (with s1<s2s_1 < s_2 after renaming). Now gd2(s2)=0g_{d_2}(s_2) = 0 because d2d_2 is on the circumsphere of t2t_2, and gd2(s1)>0g_{d_2}(s_1) > 0 because by general position d2d_2 is not on the circumsphere of t1t_1, and it is not inside it. An affine function that is positive at s1s_1 and zero at s2s_2 is negative beyond s2s_2, so II ends at s2s_2; in the same way gd1g_{d_1} ends it at s1s_1. So I=[s1,s2]I = [s_1, s_2], the segment c1c2c_1 c_2.

If t2t_2 is a ghost, ff is a face of the convex hull, and every point of EE is on the side of its plane that contains d1d_1, or on the plane. Let nn be the normal of ff pointing away from d1d_1, and x(s)=c1+snx(s) = c_1 + s n. The slope of gyg_y is 2(a−y)⋅n≥02(a - y) \cdot n \ge 0 for every yy, since y−ay - a points to the inner side or along the plane. So each gyg_y is nondecreasing, and gy(0)≥0g_y(0) \ge 0 makes it nonnegative on [0,∞)[0, \infty). The slope for d1d_1 is positive and gd1(0)=0g_{d_1}(0) = 0, so II ends at s=0s = 0 on the other side. Hence II is the ray from c1c_1 along nn. In both cases every computed center lies on II, so its ball through a,b,ca, b, c contains no point of EE in its interior.

The ghost test of the insertion uses the same fact: a new point conflicts with a ghost tetrahedron exactly when it is strictly outside the hull face, which is the limit of the insphere test as the fourth vertex goes to infinity on the outer side. With this rule, Bowyer-Watson insertion with ghosts produces the Delaunay triangulation of E∪{p}E \cup \{p\} together with ghosts on the new hull faces, as for points inside the hull.

Step 3: the incremental update (part 3). Inserting pp removes the tetrahedra (and ghosts) in conflict with pp and creates new ones joined to pp; every other tetrahedron is unchanged. By Step 2 the Voronoi edge of a triangle, and so its surface balls, depends only on the triangle and its two tetrahedra. A triangle that is not a face of a removed or new tetrahedron has the same two tetrahedra before and after, so its result does not change. Every other triangle that still exists is a face of a new tetrahedron and is recomputed; one that no longer exists is removed. The surface balls are computed by the same function either way, so the stored set equals a fresh computation.

Step 4: termination (part 4). When a center xx of a bad ball B(x,r)B(x, r) is inserted, r>σ(x′)≥σ0r > \sigma(x') \ge \sigma_0 where x′x' is the rounded point that is evaluated, and by Step 2 no point of EE lies within distance rr of xx. The inserted point x′x' is within δ\delta of xx, so it is at distance at least r−δ>σ0−δ>0r - \delta > \sigma_0 - \delta > 0 from every earlier point. So the inserted points are pairwise at least σ0−δ\sigma_0 - \delta apart, and they lie within δ+18\delta + \frac18 of SS by Step 1. The open balls of radius 12(σ0−δ)\frac12 (\sigma_0 - \delta) around them are disjoint and lie in a bounded region, so there are finitely many, and the loop, which inserts one point per round, stops.

Step 5: persistent facets (part 5). Suppose a point x′x', rounded from the center xx of a bad ball B(x,r)B(x, r), is the first inserted point inside the open ball B(ci,ri)B(c_i, r_i); the ball was bad because r>σ(x′)r > \sigma(x'). Since ∣x′−ci∣<ri|x' - c_i| < r_i and σ\sigma is 1-Lipschitz, σ(x′)>σ(ci)−ri≥23σ(ci)+δ\sigma(x') > \sigma(c_i) - r_i \ge \frac23 \sigma(c_i) + \delta. For a corner vv of the facet,

∣v−x∣≤∣v−ci∣+∣ci−x′∣+∣x′−x∣<2ri+δ≤23σ(ci)−δ<σ(x′)<r.|v - x| \le |v - c_i| + |c_i - x'| + |x' - x| < 2 r_i + \delta \le \tfrac23 \sigma(c_i) - \delta < \sigma(x') < r.

So vv lies in the interior of B(x,r)B(x, r), which is empty by Step 2, a contradiction. Hence no point is ever inserted inside B(ci,ri)B(c_i, r_i). That ball stays empty, its center stays on SS and is equidistant from the three corners, so it stays a surface Delaunay ball of the facet, and the facet stays in Del∣S(E)\mathrm{Del}|_S(E).

What is not proved. That the output is homeomorphic to SS is Boissonnat and Oudot's theorem for loose ε\varepsilon-samples of points on SS with ε≤0.091\varepsilon \le 0.091. The implementation's points are within δ+18\delta + \frac18 of SS, not on it, and the tests use σ\sigma far above 0.091 dM0.091\, d_M, so for them the topology is checked directly: every edge in two triangles, every vertex link one cycle, the Euler characteristic, and orientability. The choice of the worst ball first is not needed by the proofs. ■\blacksquare

Complexity

For nn output vertices, the 3D Delaunay triangulation has O(n2)O(n^2) tetrahedra in the worst case, so each insertion costs O(n2)O(n^2) and the loop costs O(n3)O(n^3) in the worst case, with O(n2)O(n^2) space. The oracle call per triangle costs a constant number of operations on numbers whose size grows with the coordinates. Samples of smooth surfaces behave much better than the worst case: in the runs above there were only a few tetrahedra per point. The scan for the worst ball adds O(n)O(n) per insertion, which a priority queue would reduce. The sphere with σ=0.09R\sigma = 0.09R and 10501050 points took about 1010 seconds in Python.

The number of output points is Θ(μ(S)/ε2)\Theta(\mu(S) / \varepsilon^2) when σ=ε dM\sigma = \varepsilon\, d_M with ε≤0.091\varepsilon \le 0.091 (Lemma 8.4 and Theorem 5.1), so it is optimal up to a constant factor. On the sphere, with μ(S)=4π\mu(S) = 4\pi, the runs gave 4141, 106106, 382382 and 10501050 points for ε=0.5,0.3,0.15,0.09\varepsilon = 0.5, 0.3, 0.15, 0.09, which is 0.820.82, 0.760.76, 0.680.68 and 0.680.68 times μ(S)/ε2\mu(S) / \varepsilon^2.

Properties

  • The output vertices are points of SS (in exact arithmetic), so no projection step is needed.
  • σ\sigma can vary over SS. It must be 1-Lipschitz, and must stay below 0.091 dM0.091\, d_M where the guarantee is wanted.
  • The algorithm needs only the oracle, not a parametrization, normals or curvature.
  • The restricted triangulation contains every persistent facet from the start.
  • Triangle shapes are not controlled by the basic loop. Section 9.1 of the paper adds a second pass that also calls a ball bad when its triangle has an angle below θ\theta, and proves termination for θ<30°\theta < 30°.

Variants and improvements

  • Chew's 1993 mesher is the ancestor: it refines surface Delaunay balls by size and shape, without the sampling theory that gives the topological guarantee. The planar version is Chew's second algorithm.
  • Cheng, Dey, Ramos and Ray guarantee the topology without knowing dMd_M, by refining until the restricted Voronoi cells have the topological ball property, which Edelsbrunner and Shah's theorem turns into a homeomorphism.
  • Boissonnat and Oudot extended the method to Lipschitz surfaces in 2006, and protecting balls extend Delaunay refinement to surfaces with sharp edges and corners.
  • Chapter 14 of Cheng, Dey and Shewchuk adds volume meshing: refine the tetrahedra inside SS as well, as in tetrahedral Delaunay refinement.
  • The CGAL library's former Surface_mesher package, by Laurent Rineau and Mariette Yvinec, states that it is mainly based on this work; it is deprecated since CGAL 6.0 in favor of the 3D Mesh Generation package.

When to use it

Use it when the surface is given implicitly, as a level set, a CAD surface with an intersection routine, or anything else that can answer segment queries, and when a topological guarantee matters. For a fast mesh of a level set on a grid, marching cubes and other isosurface extraction methods are simpler but offer no shape or topology guarantee. For a parametric patch, parametric surface meshing works in the parameter plane. For reconstruction from a fixed point cloud with no oracle, see surface reconstruction.

Pitfalls

  • With σ\sigma too large the loop can stop with a non-manifold output, as the torus at σ=2r\sigma = 2r shows: every ball is small enough, yet triangles share edges three or four at a time. No check after the fact is built in.
  • Without the persistent facets of Section 7, a sample with no restricted triangle on some component has no bad ball there, and the loop never reaches it.
  • dMd_M is rarely known for a real surface. A guessed σ\sigma gives no guarantee; the variant of Cheng, Dey, Ramos and Ray avoids the guess.
  • The intersection of a Voronoi edge with SS is a root of a polynomial or of a general function. Missing a root, or seeing a tangency as a crossing, changes Del∣S(E)\mathrm{Del}|_S(E). Exact root counting avoids this for algebraic surfaces.
  • The tetrahedra of DD are scaffolding, not a volume mesh: many are flat. A volume mesh needs its own refinement, and a radius-edge bound would not remove its slivers.
  • A Voronoi vertex exactly on SS, a Voronoi edge tangent to SS, or five cospherical points are degenerate cases that the paper assumes away. The implementation raises an error when such a case would make a tetrahedron flat.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

delaunay_surface_meshing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delaunay-surface-meshing/. The authors are listed in prov/8F2351.jsonl.

"""Boissonnat and Oudot's Delaunay refinement surface mesher (2005).

The surface S is the zero set of a polynomial F with integer coefficients: a
sphere or a torus. It is known to the mesher only through an oracle that, given
a segment or a ray, returns the points where it meets S. The mesher keeps the
3D Delaunay triangulation of the sample E, finds the restricted Delaunay
triangles (those whose dual Voronoi edge meets S), and inserts the center c of
any surface Delaunay ball B(c, r) with r > sigma(c), until there is none.

Coordinates are integers. A new vertex is the exact intersection of a Voronoi
edge with S, located to within a small fraction of a unit and rounded once to
the integer grid, so it lies within one unit of S. All predicates on the
current points are exact: orientation and insphere signs use int arithmetic,
and the question whether a Voronoi edge meets S is answered by an exact Sturm
sequence on a polynomial with integer coefficients. Radii and sigma are
compared in floating point, which only decides which balls count as bad.
"""

import math
import random
from fractions import Fraction
from typing import Callable, Dict, List, Optional, Sequence, Set, Tuple, Union

from mg2geom import cross, dist2, dot, insphere, orient3d, sub

Tet = Tuple[int, int, int, int]
Face = Tuple[int, int, int]
GHOST = -1  # the vertex at infinity; a tetrahedron with it is a hull face


# polynomials in one variable s: lists of coefficients, index = power
def padd(p: Sequence, q: Sequence) -> list:
    n = max(len(p), len(q))
    return [(p[i] if i < len(p) else 0) + (q[i] if i < len(q) else 0) for i in range(n)]


def pmul(p: Sequence, q: Sequence) -> list:
    out = [0] * (len(p) + len(q) - 1)
    for i, a in enumerate(p):
        for j, b in enumerate(q):
            out[i + j] += a * b
    return out


def peval(p: Sequence, x):
    v = 0
    for c in reversed(p):
        v = v * x + c
    return v


def _trim(p: Sequence) -> list:
    p = list(p)
    while len(p) > 1 and p[-1] == 0:
        p.pop()
    return p


def _sign(x) -> int:
    return (x > 0) - (x < 0)


def _rem(a: Sequence, b: Sequence) -> list:
    a = [Fraction(x) for x in a]
    while len(a) >= len(b) and not (len(a) == 1 and a[0] == 0):
        c = a[-1] / b[-1]
        sh = len(a) - len(b)
        for i in range(len(b)):
            a[sh + i] -= c * b[i]
        a.pop()
        a = _trim(a) if a else [Fraction(0)]
    return a


def sturm(p: Sequence) -> List[list]:
    """The Sturm sequence p, p', -rem(p, p'), ... of a nonzero polynomial."""
    p = _trim(p)
    seq = [p]
    if len(p) == 1:
        return seq
    seq.append([i * p[i] for i in range(1, len(p))])
    while len(seq[-1]) > 1:
        r = _rem(seq[-2], seq[-1])
        if len(r) == 1 and r[0] == 0:
            break
        seq.append([-x for x in r])
    return seq


def _variations(seq: List[list], x) -> int:
    """Sign changes of the sequence at x; x = None means +infinity, '-' means -infinity."""
    signs = []
    for q in seq:
        if x is None:
            s = _sign(q[-1])
        elif x == "-":
            s = _sign(q[-1]) * (-1) ** (len(q) - 1)
        else:
            s = _sign(peval(q, x))
        if s:
            signs.append(s)
    return sum(1 for i in range(1, len(signs)) if signs[i] != signs[i - 1])


def count_roots(seq: List[list], lo, hi) -> int:
    """Number of distinct real roots of seq[0] in (lo, hi] (Sturm's theorem)."""
    return _variations(seq, lo) - _variations(seq, hi)


def _quo(a: Sequence, b: Sequence) -> list:
    """The quotient of a by b, for b dividing a exactly."""
    a = [Fraction(x) for x in a]
    q = [Fraction(0)] * (len(a) - len(b) + 1)
    for sh in range(len(a) - len(b), -1, -1):
        c = a[sh + len(b) - 1] / b[-1]
        q[sh] = c
        for i in range(len(b)):
            a[sh + i] -= c * b[i]
    return _trim(q)


def root_bound(p: Sequence) -> Fraction:
    """Cauchy's bound: every real root has absolute value below it."""
    p = _trim(p)
    return 1 + max(Fraction(abs(c), abs(p[-1])) for c in p[:-1])


def roots_in(p: Sequence, lo, hi, tol: Fraction) -> List[Fraction]:
    """The distinct real roots of p in [lo, hi], each to within tol.

    lo is a Fraction or '-' for minus infinity; hi a Fraction or None for plus
    infinity. The number of roots is exact; only their positions are approximate.
    A repeated root is first removed by dividing p by gcd(p, p'), so that every
    remaining root is simple and Sturm's theorem counts the roots in (a, b]
    even when a or b is a root.
    """
    p = _trim(p)
    if len(p) == 1:
        if p[0] == 0:
            raise ValueError("the line lies in the surface")
        return []
    seq = sturm(p)
    if len(seq[-1]) > 1:  # p has a repeated root: keep its square-free part, same distinct roots
        p = _quo(p, seq[-1])
        seq = sturm(p)
    out = []
    if lo == "-":
        lo = -root_bound(p)
    elif peval(p, lo) == 0:
        out.append(Fraction(lo))
    if hi is None:
        hi = root_bound(p)
    stack = [(Fraction(lo), Fraction(hi))]
    while stack:
        a, b = stack.pop()
        n = count_roots(seq, a, b)
        if n == 0:
            continue
        sa, sb = _sign(peval(p, a)), _sign(peval(p, b))
        if n == 1 and sb == 0:
            out.append(b)
        elif n == 1 and sa * sb < 0:
            while b - a > tol:  # one simple root, where p changes sign
                m = (a + b) / 2
                sm = _sign(peval(p, m))
                if sm == 0:
                    a = b = m
                elif sm == sa:
                    a = m
                else:
                    b = m
            out.append((a + b) / 2)
        elif b - a <= tol:
            out.append(b if sb == 0 else (a + b) / 2)
        else:
            m = (a + b) / 2
            stack.append((m, b))
            stack.append((a, m))
    return sorted(out)


def _sq(a, b) -> list:
    """(a + b s)^2."""
    return [a * a, 2 * a * b, b * b]


class Sphere:
    """The sphere |x| = R. Its medial axis is the center, so lfs = R everywhere."""

    euler = 2

    def __init__(self, R: int):
        if int(R) != R or R <= 0:
            raise ValueError("R must be a positive integer")
        self.R = int(R)

    def poly(self, A: Sequence[int], B: Sequence[int], W: int) -> list:
        """W^2 F((A + s B) / W) as a polynomial in s with integer coefficients."""
        p = [-self.R * self.R * W * W]
        for k in range(3):
            p = padd(p, _sq(A[k], B[k]))
        return p

    def distance(self, p: Sequence) -> float:
        return abs(math.sqrt(sum(float(x) ** 2 for x in p)) - self.R)

    def lfs(self, p: Sequence) -> float:
        return float(self.R)

    def project(self, p: Sequence[float]) -> tuple:
        n = math.sqrt(sum(x * x for x in p))
        return tuple(x * self.R / n for x in p)

    def normal(self, p: Sequence[float]) -> tuple:
        n = math.sqrt(sum(x * x for x in p))
        return tuple(x / n for x in p)

    def seeds(self, rng: random.Random) -> List[tuple]:
        """Four points of a randomly rotated regular tetrahedron on the sphere."""
        q = _random_rotation(rng)
        base = [(1, 1, 1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1)]
        return [self.project(_apply(q, v)) for v in base]


class Torus:
    """The torus at distance r from the circle of radius R in the plane z = 0.

    With R >= 2 r its medial axis is that circle together with the z axis, so
    lfs = r everywhere.
    """

    euler = 0

    def __init__(self, R: int, r: int):
        if int(R) != R or int(r) != r or r <= 0 or R < 2 * r:
            raise ValueError("need integers R >= 2 r > 0")
        self.R, self.r = int(R), int(r)

    def poly(self, A: Sequence[int], B: Sequence[int], W: int) -> list:
        """W^4 F((A + s B) / W) with F = (|x|^2 + R^2 - r^2)^2 - 4 R^2 (x^2 + y^2)."""
        R2, r2, W2 = self.R * self.R, self.r * self.r, W * W
        xy = padd(_sq(A[0], B[0]), _sq(A[1], B[1]))
        q = padd(padd(xy, _sq(A[2], B[2])), [(R2 - r2) * W2])
        return padd(pmul(q, q), [-4 * R2 * W2 * c for c in xy])

    def _core(self, p: Sequence[float]) -> tuple:
        rho = math.hypot(p[0], p[1])
        return (self.R * p[0] / rho, self.R * p[1] / rho, 0.0)

    def distance(self, p: Sequence) -> float:
        q = [float(x) for x in p]
        return abs(math.hypot(math.hypot(q[0], q[1]) - self.R, q[2]) - self.r)

    def lfs(self, p: Sequence) -> float:
        return float(self.r)

    def normal(self, p: Sequence[float]) -> tuple:
        c = self._core(p)
        d = sub(p, c)
        n = math.sqrt(dot(d, d))
        return tuple(x / n for x in d)

    def project(self, p: Sequence[float]) -> tuple:
        c = self._core(p)
        return tuple(c[k] + self.r * v for k, v in enumerate(self.normal(p)))

    def seeds(self, rng: random.Random) -> List[tuple]:
        """Four points spread around the torus, at random angles."""
        out = []
        a0 = rng.uniform(0, 2 * math.pi)
        for i in range(4):
            a = a0 + i * math.pi / 2
            b = rng.uniform(0, 2 * math.pi)
            rho = self.R + self.r * math.cos(b)
            out.append((rho * math.cos(a), rho * math.sin(a), self.r * math.sin(b)))
        return out


def _random_rotation(rng: random.Random) -> list:
    q = [rng.gauss(0, 1) for _ in range(4)]
    n = math.sqrt(sum(x * x for x in q))
    w, x, y, z = (v / n for v in q)
    return [
        [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
        [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
        [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
    ]


def _apply(m: list, v: Sequence) -> tuple:
    return tuple(sum(m[i][j] * v[j] for j in range(3)) for i in range(3))


def _round(p: Sequence) -> tuple:
    return tuple(int(round(x)) for x in p)


def faces_of(t: Tet) -> List[Face]:
    return [t[:i] + t[i + 1 :] for i in range(4)]


def circumcenter_hom(a, b, c, d) -> Tuple[tuple, int]:
    """The circumcenter of a tetrahedron as N / W with integer N and W > 0."""
    u, v, w = sub(b, a), sub(c, a), sub(d, a)
    det = dot(u, cross(v, w))
    if det == 0:
        raise ValueError("flat tetrahedron")
    uu, vv, ww = dot(u, u), dot(v, v), dot(w, w)
    cvw, cwu, cuv = cross(v, w), cross(w, u), cross(u, v)
    N = tuple(2 * det * a[k] + uu * cvw[k] + vv * cwu[k] + ww * cuv[k] for k in range(3))
    W = 2 * det
    return (N, W) if W > 0 else (tuple(-x for x in N), -W)


class Mesher:
    """The 3D Delaunay triangulation of the sample, kept with hull (ghost) tetrahedra,
    and its restricted Delaunay triangles."""

    def __init__(self, surface, sigma: Union[float, Callable], seed: int = 0, max_vertices: int = 2000):
        self.S = surface
        self.sigma = sigma if callable(sigma) else (lambda p, s=float(sigma): s)
        self.max_vertices = max_vertices
        self.rng = random.Random(seed)
        self.pts: List[tuple] = []
        self.tets: Set[Tet] = set()
        self.face_tets: Dict[Face, Set[Tet]] = {}
        self.cc: Dict[Tet, Tuple[tuple, int]] = {}
        self.inside: Optional[tuple] = None
        self.balls: Dict[Face, List[tuple]] = {}  # restricted face -> [(center, r, sigma(center))]
        self.persistent: List[Face] = []
        self.log: List[tuple] = []  # (center, r, sigma) of each inserted point

    # the oracle: where a Voronoi edge meets S
    def voronoi_edge(self, f: Face) -> Tuple[tuple, tuple, int, Optional[int]]:
        """The Voronoi edge dual to face f as (A, B, W, end): the points (A + s B) / W
        for s in [0, end], with end = None for a ray."""
        t1, t2 = self.face_tets[f]
        if t1[0] == GHOST:
            t1, t2 = t2, t1
        N1, W1 = self.cc[t1]
        if t2[0] != GHOST:
            N2, W2 = self.cc[t2]
            A = tuple(x * W2 for x in N1)
            return A, tuple(N2[k] * W1 - A[k] for k in range(3)), W1 * W2, 1
        a, b, c = (self.pts[v] for v in f)
        d = self.pts[next(v for v in t1 if v not in f)]
        n = cross(sub(b, a), sub(c, a))
        if dot(n, sub(d, a)) > 0:
            n = tuple(-x for x in n)
        return N1, tuple(W1 * x for x in n), W1, None

    def surface_balls(self, f: Face) -> List[tuple]:
        A, B, W, end = self.voronoi_edge(f)
        G = self.S.poly(A, B, W)  # @line L3
        length = math.sqrt(sum(float(x) ** 2 for x in B)) / W
        tol = Fraction(1, 8) / max(1, math.ceil(length))
        out = []
        a = self.pts[f[0]]
        for s in roots_in(G, Fraction(0), end, tol):
            x = tuple((A[k] + s * B[k]) / W for k in range(3))
            c = _round(x)
            r = math.sqrt(float(dist2(x, a)))
            out.append((c, r, self.sigma(c)))
        return out

    # Bowyer-Watson insertion with ghost tetrahedra
    def conflicts(self, t: Tet, p: tuple) -> bool:
        if t[0] == GHOST:
            f = [self.pts[v] for v in t[1:]]
            o = orient3d(*f, p)
            if o == 0:
                raise ValueError("degenerate input: a point on the plane of a hull face")
            return _sign(o) != _sign(orient3d(*f, self.inside))
        return insphere(*[self.pts[v] for v in t], p) > 0

    def _add_tet(self, t: Tet) -> None:
        t = tuple(sorted(t))
        if t[0] != GHOST:
            self.cc[t] = circumcenter_hom(*[self.pts[v] for v in t])
        self.tets.add(t)
        for f in faces_of(t):
            self.face_tets.setdefault(f, set()).add(t)

    def _remove_tet(self, t: Tet) -> None:
        self.tets.discard(t)
        self.cc.pop(t, None)
        for f in faces_of(t):
            s = self.face_tets[f]
            s.discard(t)
            if not s:
                del self.face_tets[f]

    def insert(self, p: tuple, hint: Sequence[Tet] = ()) -> int:
        if len(self.pts) >= self.max_vertices:
            raise RuntimeError("too many vertices")
        if p in self.pts:
            raise ValueError("repeated point")
        start = next((t for t in hint if t in self.tets and self.conflicts(t, p)), None)
        if start is None:
            start = next(t for t in sorted(self.tets) if self.conflicts(t, p))
        cavity = {start}
        stack = [start]
        while stack:
            t = stack.pop()
            for f in faces_of(t):
                for u in self.face_tets[f]:
                    if u not in cavity and self.conflicts(u, p):
                        cavity.add(u)
                        stack.append(u)
        boundary = []
        for t in cavity:
            for f in faces_of(t):
                if not any(u in cavity for u in self.face_tets[f] if u != t):
                    boundary.append(f)
        self.pts.append(p)
        v = len(self.pts) - 1
        for t in cavity:
            self._remove_tet(t)
        new = []
        for f in boundary:
            real = [self.pts[w] for w in f if w != GHOST]
            if len(real) == 3 and orient3d(*real, p) == 0:
                raise ValueError("degenerate input: cospherical or coplanar points")
            self._add_tet(f + (v,))
            new.append(tuple(sorted(f + (v,))))
        return v

    def _start(self, pts: Sequence[tuple]) -> None:
        """The first tetrahedron and its four hull faces, then the other points."""
        a, b, c = pts[0], pts[1], pts[2]
        i = next(i for i in range(3, len(pts)) if orient3d(a, b, c, pts[i]) != 0)
        first = [a, b, c, pts[i]]
        self.pts = list(first)
        self.inside = tuple(Fraction(sum(q[k] for q in first), 4) for k in range(3))
        self._add_tet((0, 1, 2, 3))
        for f in faces_of((0, 1, 2, 3)):
            self._add_tet((GHOST,) + f)
        for q in pts[3:i] + pts[i + 1 :]:
            self.insert(q)

    # restricted Delaunay triangles
    def update_faces(self, faces) -> None:
        for f in faces:
            if GHOST in f:
                continue
            if f not in self.face_tets:
                self.balls.pop(f, None)
                continue
            b = self.surface_balls(f)
            if b:
                self.balls[f] = b
            else:
                self.balls.pop(f, None)

    def restricted(self) -> Set[Face]:
        return set(self.balls)

    def worst_ball(self) -> Optional[tuple]:
        best = None
        for f in sorted(self.balls):
            for c, r, sg in self.balls[f]:
                if r > sg and (best is None or r / sg > best[0]):
                    best = (r / sg, f, c, r, sg)
        return best

    def initial_sample(self) -> List[tuple]:
        """Section 7 of the paper: three points of S near each seed, forming a persistent facet."""
        seeds = self.S.seeds(self.rng)
        out = []
        for x in seeds:
            d = min(math.dist(x, y) for y in seeds if y is not x)
            rad = 0.99 * min(d / 6, self.S.lfs(x), self.sigma(_round(x)) / 6)
            for _ in range(50):
                tri = self._triangle_near(x, rad)
                if tri is not None:
                    out.extend(tri)
                    break
            else:
                raise RuntimeError("no persistent facet found near a seed")
        return out

    def _triangle_near(self, x: tuple, rad: float) -> Optional[List[tuple]]:
        n = self.S.normal(x)
        e = (1.0, 0.0, 0.0) if abs(n[0]) < 0.9 else (0.0, 1.0, 0.0)
        t1 = cross(n, e)
        l1 = math.sqrt(dot(t1, t1))
        t1 = tuple(v / l1 for v in t1)
        t2 = cross(n, t1)
        a0 = self.rng.uniform(0, 2 * math.pi)
        tri = []
        for i in range(3):
            a = a0 + i * 2 * math.pi / 3 + self.rng.uniform(-0.3, 0.3)
            q = tuple(x[k] + 0.5 * rad * (math.cos(a) * t1[k] + math.sin(a) * t2[k]) for k in range(3))
            tri.append(_round(self.S.project(q)))
        if len(set(tri)) < 3:
            return None
        # the line through the circumcenter, normal to the triangle, must meet S inside B(x, rad)
        a, b, c = tri
        u, v = sub(b, a), sub(c, a)
        nn = cross(u, v)
        W = 2 * dot(nn, nn)
        if W == 0:
            return None
        N = tuple(W * a[k] + dot(u, u) * cross(v, nn)[k] + dot(v, v) * cross(nn, u)[k] for k in range(3))
        G = self.S.poly(N, tuple(W * k for k in nn), W)
        for s in roots_in(G, "-", None, Fraction(1, 1 << 40)):
            y = tuple(float((N[k] + s * W * nn[k]) / W) for k in range(3))
            if math.dist(y, x) < rad:
                return tri
        return None

    def run(self) -> None:
        init = self.initial_sample()  # @line L1
        self._start(init)  # @line L2
        self.persistent = [tuple(sorted(self.pts.index(q) for q in init[i : i + 3])) for i in range(0, len(init), 3)]
        self.update_faces(list(self.face_tets))
        while True:
            w = self.worst_ball()  # @line L4
            if w is None:
                break
            _, f, c, r, sg = w  # @line L5
            old = set(self.tets)
            self.insert(c, sorted(self.face_tets[f]))  # @line L6
            self.log.append((c, r, sg))
            gone = old - self.tets
            born = self.tets - old
            touched = {g for t in gone | born for g in faces_of(t)}
            self.update_faces(sorted(touched))  # @line L7


def delaunay_surface_mesh(surface, sigma: Union[float, Callable], seed: int = 0, max_vertices: int = 2000) -> Mesher:
    """Mesh the surface until every surface Delaunay ball B(c, r) has r <= sigma(c).

    sigma is a number or a function of a point, in the integer units of the
    surface, and must be positive and 1-Lipschitz. Returns the Mesher: pts holds
    the sample and restricted() the triangles of the restricted Delaunay
    triangulation, as triples of indices into pts.
    """
    m = Mesher(surface, sigma, seed, max_vertices)
    m.run()
    return m  # @line L8
mg2geom.py 159 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mg2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small exact geometric tools used by the mg2 pages.

Points are tuples of int or fractions.Fraction. Every predicate returns an
exact value when the coordinates are int or Fraction, so its sign is the true
sign. A float converts to a Fraction without rounding (exact()), so the sign
is then exact for the float point as it is stored. The angle functions return
floats and are used only to report or to compare with a stated bound.
"""

import math
from fractions import Fraction
from typing import Sequence, Tuple

Point = Tuple


def exact(p: Point) -> Tuple[Fraction, ...]:
    """The point p with each coordinate converted to Fraction, without rounding."""
    return tuple(Fraction(c) for c in p)


def sub(a: Point, b: Point) -> tuple:
    return tuple(x - y for x, y in zip(a, b))


def dot(a: Point, b: Point):
    return sum(x * y for x, y in zip(a, b))


def cross(a: Point, b: Point) -> tuple:
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def dist2(a: Point, b: Point):
    return sum((x - y) * (x - y) for x, y in zip(a, b))


def det3(r0: Sequence, r1: Sequence, r2: Sequence):
    return dot(r0, cross(r1, r2))


def det4(m: Sequence[Sequence]):
    """Determinant of a 4 by 4 matrix by cofactor expansion along the first row."""
    total = 0
    for j in range(4):
        minor = [[m[i][k] for k in range(4) if k != j] for i in range(1, 4)]
        term = m[0][j] * det3(minor[0], minor[1], minor[2])
        total += term if j % 2 == 0 else -term
    return total


def orient2d(a: Point, b: Point, c: Point):
    """Twice the signed area of the triangle a, b, c; positive if counterclockwise."""
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def orient3d(a: Point, b: Point, c: Point, d: Point):
    """Six times the signed volume of the tetrahedron a, b, c, d.

    It is det[b - a, c - a, d - a]: positive when d lies on the side of the
    plane abc from which a, b, c appear clockwise.
    """
    return det3(sub(b, a), sub(c, a), sub(d, a))


def insphere(a: Point, b: Point, c: Point, d: Point, e: Point):
    """Positive if e lies inside the sphere through a, b, c, d, zero on it.

    The value is det of the rows (p - e, |p - e|^2) for p = a, b, c, d,
    divided by nothing, times the sign of orient3d(a, b, c, d), so the result
    does not depend on the order of a, b, c, d. The tetrahedron must not be flat.
    """
    rows = []
    for p in (a, b, c, d):
        v = sub(p, e)
        rows.append([v[0], v[1], v[2], dot(v, v)])
    o = orient3d(a, b, c, d)
    if o == 0:
        raise ValueError("flat tetrahedron")
    val = -det4(rows)
    return val if o > 0 else -val


def circumcenter3(a: Point, b: Point, c: Point, d: Point) -> tuple:
    """Exact circumcenter of a tetrahedron, by Cramer's rule on 2 (p - a) . x = |p - a|^2."""
    u, v, w = sub(b, a), sub(c, a), sub(d, a)
    det = det3(u, v, w)
    if det == 0:
        raise ValueError("flat tetrahedron")
    bu, bv, bw = Fraction(dot(u, u)), Fraction(dot(v, v)), Fraction(dot(w, w))
    # x = (bu (v x w) + bv (w x u) + bw (u x v)) / (2 det)
    cvw, cwu, cuv = cross(v, w), cross(w, u), cross(u, v)
    x = tuple((bu * cvw[k] + bv * cwu[k] + bw * cuv[k]) / (2 * det) for k in range(3))
    return tuple(a[k] + x[k] for k in range(3))


def tri_circumcenter3(a: Point, b: Point, c: Point) -> tuple:
    """Exact circumcenter of a triangle in space (the center of its smallest circumscribed sphere)."""
    u, v = sub(b, a), sub(c, a)
    n = cross(u, v)
    nn = Fraction(dot(n, n))
    if nn == 0:
        raise ValueError("flat triangle")
    t1 = cross(n, u)
    t2 = cross(v, n)
    uu, vv = dot(u, u), dot(v, v)
    # x = (|u|^2 (v x n) + |v|^2 (n x u)) / (2 |n|^2)
    return tuple(a[k] + (uu * t2[k] + vv * t1[k]) / (2 * nn) for k in range(3))


def radius_edge2(a: Point, b: Point, c: Point, d: Point) -> Fraction:
    """Exact square of the radius-edge ratio R / l_min of a tetrahedron."""
    cc = circumcenter3(a, b, c, d)
    r2 = dist2(cc, a)
    pts = (a, b, c, d)
    lmin2 = min(dist2(pts[i], pts[j]) for i in range(4) for j in range(i + 1, 4))
    return Fraction(r2) / Fraction(lmin2)


def _angle(u: Sequence[float], v: Sequence[float]) -> float:
    nu = math.sqrt(sum(x * x for x in u))
    nv = math.sqrt(sum(x * x for x in v))
    c = sum(x * y for x, y in zip(u, v)) / (nu * nv)
    return math.degrees(math.acos(max(-1.0, min(1.0, c))))


def triangle_angles_deg(a: Point, b: Point, c: Point) -> list:
    """The three plane angles of a triangle in degrees, in 2D or 3D (floats)."""
    p = [tuple(float(x) for x in q) for q in (a, b, c)]
    out = []
    for i in range(3):
        o, s, t = p[i], p[(i + 1) % 3], p[(i + 2) % 3]
        out.append(_angle(sub(s, o), sub(t, o)))
    return out


def dihedral_angles_deg(a: Point, b: Point, c: Point, d: Point) -> list:
    """The six dihedral angles of a tetrahedron in degrees (floats).

    The angle at edge pq is the angle between the two faces pqr and pqs,
    measured inside the tetrahedron.
    """
    p = [tuple(float(x) for x in q) for q in (a, b, c, d)]
    out = []
    for i in range(4):
        for j in range(i + 1, 4):
            k, m = [t for t in range(4) if t not in (i, j)]
            e = sub(p[j], p[i])
            ee = dot(e, e)
            # components of p_k - p_i and p_m - p_i orthogonal to the edge
            u = sub(p[k], p[i])
            v = sub(p[m], p[i])
            u = tuple(u[t] - dot(u, e) / ee * e[t] for t in range(3))
            v = tuple(v[t] - dot(v, e) / ee * e[t] for t in range(3))
            out.append(_angle(u, v))
    return out
test_delaunay_surface_meshing.py 338 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delaunay-surface-meshing/. The authors are listed in prov/8F2351.jsonl.

import math
import random
from collections import Counter, defaultdict
from fractions import Fraction as F
from functools import lru_cache
from itertools import combinations

import pytest

from delaunay_surface_meshing import (
    GHOST,
    Mesher,
    Sphere,
    Torus,
    count_roots,
    delaunay_surface_mesh,
    faces_of,
    peval,
    pmul,
    roots_in,
    sturm,
)
from mg2geom import cross, dist2, dot, insphere, orient3d, sub

R = 1 << 20
SPHERE = Sphere(R)
TORUS = Torus(3 << 18, 1 << 18)  # lfs = r = 2^18 everywhere
LFS = {"sphere": R, "torus": 1 << 18}
SURF = {"sphere": SPHERE, "torus": TORUS}
CASES = [("sphere", F(1, 2), 1), ("torus", F(3, 2), 1), ("sphere", F(3, 10), 2)]
ROUND = math.sqrt(3) / 2  # rounding to the grid moves a point at most this far
# a computed center is within 1/8 of the exact point of S on the Voronoi edge, then rounded


@lru_cache(maxsize=None)
def run(kind, eps, seed):
    return delaunay_surface_mesh(SURF[kind], float(eps * LFS[kind]), seed=seed)


def edge_count(T):
    E = Counter()
    for f in T:
        for e in combinations(f, 2):
            E[e] += 1
    return E


def brute_restricted(S, pts):
    """Restricted Delaunay triangles straight from the definition: abc is one if some
    point of S has a, b, c among its nearest sample points (an empty ball centered on S)."""
    out = set()
    n = len(pts)
    for i, j, k in combinations(range(n), 3):
        a, b, c = pts[i], pts[j], pts[k]
        u, v = sub(b, a), sub(c, a)
        nn = cross(u, v)
        W = 2 * dot(nn, nn)
        if W == 0:
            continue
        # the points equidistant from a, b, c: (N + s W nn) / W
        N = tuple(W * a[t] + dot(u, u) * cross(v, nn)[t] + dot(v, v) * cross(nn, u)[t] for t in range(3))
        cf = [x / W for x in N]
        others = sorted((p for q, p in enumerate(pts) if q not in (i, j, k)), key=lambda p: math.dist(p, cf))
        lo, hi, empty = None, None, False  # bounds on s as (numerator, positive denominator)
        aa = dot(a, a)
        for p in others:
            # |x - p|^2 >= |x - a|^2  <=>  alpha + s beta >= 0
            d = sub(a, p)
            alpha = 2 * dot(d, N) + W * (dot(p, p) - aa)
            beta = 2 * W * dot(d, nn)
            if beta == 0:
                empty = alpha < 0
            elif beta > 0:  # s >= -alpha / beta
                if lo is None or -alpha * lo[1] > lo[0] * beta:
                    lo = (-alpha, beta)
            else:  # s <= alpha / -beta
                if hi is None or alpha * hi[1] < hi[0] * -beta:
                    hi = (alpha, -beta)
            if empty or (lo is not None and hi is not None and lo[0] * hi[1] > hi[0] * lo[1]):
                empty = True
                break
        if empty:
            continue
        G = S.poly(N, tuple(W * x for x in nn), W)
        lo = "-" if lo is None else F(*lo)
        hi = None if hi is None else F(*hi)
        if roots_in(G, lo, hi, F(1, 1 << 30)):
            out.add((i, j, k))
    return out


# the exact tools


def test_sturm_counts_and_locates_roots():
    rng = random.Random(5)
    for _ in range(40):
        roots = sorted({F(rng.randint(-40, 40), rng.randint(1, 6)) for _ in range(rng.randint(1, 4))})
        p = [1]
        for x in roots:
            p = pmul(p, [-x.numerator, x.denominator])
        if rng.random() < 0.3:
            p = pmul(p, [1, 0, 1])  # s^2 + 1 adds no real root
        if rng.random() < 0.3:
            p = pmul(p, [-roots[0].numerator, roots[0].denominator])  # a double root counts once
        seq = sturm(p)
        lo, hi = F(rng.randint(-50, 0)), F(rng.randint(0, 50))
        a, b = lo + F(1, 1000), hi + F(1, 1000)  # not roots, so the count is exact even for p
        assert count_roots(seq, a, b) == sum(1 for x in roots if a < x <= b)
        got = roots_in(p, lo, hi, F(1, 1000))
        want = [x for x in roots if lo <= x <= hi]
        assert len(got) == len(want)
        assert all(abs(g - w) <= F(1, 1000) for g, w in zip(got, want))
        assert len(roots_in(p, "-", None, F(1, 1000))) == len(roots)


def test_surface_polynomial_is_the_implicit_function_on_the_line():
    rng = random.Random(6)
    for S, deg in ((SPHERE, 2), (TORUS, 4)):
        for _ in range(20):
            A = tuple(rng.randint(-(1 << 30), 1 << 30) for _ in range(3))
            B = tuple(rng.randint(-(1 << 30), 1 << 30) for _ in range(3))
            W = rng.randint(1, 1 << 10)
            s = F(rng.randint(-100, 100), rng.randint(1, 100))
            x = [(A[k] + s * B[k]) / W for k in range(3)]
            if S is SPHERE:
                val = sum(c * c for c in x) - R * R
            else:
                q = sum(c * c for c in x) + S.R ** 2 - S.r ** 2
                val = q * q - 4 * S.R ** 2 * (x[0] ** 2 + x[1] ** 2)
            assert peval(S.poly(A, B, W), s) == val * W ** deg


# the output


@pytest.mark.parametrize("case", CASES)
def test_every_vertex_lies_on_the_surface(case):
    m = run(*case)
    S = SURF[case[0]]
    assert max(S.distance(p) for p in m.pts) <= ROUND + 1 / 8


@pytest.mark.parametrize("case", CASES[:2] + [("torus", F(2), 1)])
def test_restricted_triangles_match_brute_force(case):
    m = run(*case)
    want = brute_restricted(SURF[case[0]], m.pts)
    assert m.restricted() == want


@pytest.mark.parametrize("case", CASES[:2] + [("torus", F(2), 1)])
def test_the_triangulation_is_delaunay(case):
    m = run(*case)
    n = len(m.pts)
    real = [t for t in m.tets if t[0] != GHOST]
    for t in real:
        P = [m.pts[v] for v in t]
        assert orient3d(*P) != 0
        assert all(insphere(*P, m.pts[q]) < 0 for q in range(n) if q not in t)
    for f, ts in m.face_tets.items():
        assert len(ts) == 2
    hull = [t[1:] for t in m.tets if t[0] == GHOST]
    for f in hull:  # every point is on the inner side of every hull face
        P = [m.pts[v] for v in f]
        sides = {(orient3d(*P, m.pts[q]) > 0) for q in range(n) if q not in f}
        assert len(sides) == 1
    used = {v for t in m.tets for v in t if v != GHOST}
    assert used == set(range(n))


@pytest.mark.parametrize("case", CASES)
def test_incremental_update_equals_a_fresh_computation(case):
    m = run(*case)
    fresh = {}
    for f in m.face_tets:
        if GHOST not in f:
            b = m.surface_balls(f)
            if b:
                fresh[f] = b
    assert fresh == m.balls


@pytest.mark.parametrize("case", CASES)
def test_no_bad_ball_is_left(case):
    """At the end every surface Delaunay ball B(c, r) has r <= sigma(c), which with
    sigma = eps lfs is Condition 1 of a loose eps-sample (Lemma 8.2)."""
    m = run(*case)
    kind, eps, _ = case
    assert m.balls
    for f, balls in m.balls.items():
        for c, r, sg in balls:
            assert r <= sg == float(eps * LFS[kind])
            assert SURF[kind].distance(c) <= ROUND + 1 / 8


@pytest.mark.parametrize("case", CASES)
def test_output_is_a_closed_two_manifold_of_the_right_genus(case):
    m = run(*case)
    T = m.restricted()
    E = edge_count(T)
    assert set(E.values()) == {2}
    V = {v for f in T for v in f}
    assert V == set(range(len(m.pts)))
    link = defaultdict(list)
    for f in T:
        for v in f:
            link[v].append(tuple(x for x in f if x != v))
    for v, edges in link.items():  # the link of every vertex is one cycle
        adj = defaultdict(list)
        for a, b in edges:
            adj[a].append(b)
            adj[b].append(a)
        assert all(len(x) == 2 for x in adj.values())
        seen, stack = {edges[0][0]}, [edges[0][0]]
        while stack:
            for y in adj[stack.pop()]:
                if y not in seen:
                    seen.add(y)
                    stack.append(y)
        assert len(seen) == len(adj)
    assert len(V) - len(E) + len(T) == SURF[case[0]].euler
    # connected and orientable: orient one triangle and propagate across edges
    orient = {}
    first = min(T)
    orient[first] = first
    stack = [first]
    by_edge = defaultdict(list)
    for f in T:
        for e in combinations(f, 2):
            by_edge[e].append(f)
    while stack:
        f = stack.pop()
        o = orient[f]
        for i in range(3):
            a, b = o[i], o[(i + 1) % 3]
            for g in by_edge[tuple(sorted((a, b)))]:
                if g == f:
                    continue
                c = next(x for x in g if x not in (a, b))
                want = (b, a, c)
                if g in orient:
                    assert set(zip(orient[g], orient[g][1:] + orient[g][:1])) >= {(b, a)}
                else:
                    orient[g] = want
                    stack.append(g)
    assert len(orient) == len(T)


@pytest.mark.parametrize("case", CASES)
def test_persistent_facets_stay(case):
    """Section 7: each initial triple has a surface Delaunay ball of radius at most sigma / 3,
    and Lemma 7.1: it is still a restricted triangle at the end."""
    kind, eps, seed = case
    m0 = Mesher(SURF[kind], float(eps * LFS[kind]), seed)
    init = m0.initial_sample()
    m0._start(init)
    m0.update_faces(list(m0.face_tets))
    pers = [tuple(sorted(m0.pts.index(q) for q in init[i : i + 3])) for i in range(0, len(init), 3)]
    for f in pers:
        assert any(r + ROUND <= sg / 3 for c, r, sg in m0.balls[f])
    m = run(*case)
    assert m.persistent == pers
    assert all(f in m.restricted() for f in m.persistent)


@pytest.mark.parametrize("case", CASES)
def test_inserted_points_are_far_apart(case):
    """Lemma 8.1: a point is inserted at distance r > sigma(c) from the sample (less rounding)."""
    m = run(*case)
    k = len(m.pts) - len(m.log)
    for i, (c, r, sg) in enumerate(m.log):
        assert m.pts[k + i] == c and r > sg
        d = min(math.sqrt(dist2(c, m.pts[j])) for j in range(k + i))
        assert d >= r - ROUND


def test_example_sphere():
    m = run("sphere", F(1, 2), 1)
    assert len(m.pts) == 41 and len(m.log) == 29 and len(m.restricted()) == 78
    ratios = [round(r / sg, 3) for c, r, sg in m.log]
    assert ratios[0] == 2.256 and ratios[4] == 1.793 and ratios[10] == 1.233 and ratios[-1] == 1.0
    assert all(x >= y - 0.01 for x, y in zip(ratios, ratios[1:]))  # the worst ratio falls, nearly monotone
    m0 = Mesher(SPHERE, R / 2, 1)
    m0._start(m0.initial_sample())
    m0.update_faces(list(m0.face_tets))
    r0 = sorted(round(r / sg, 3) for f in m0.balls for c, r, sg in m0.balls[f])
    assert len(m0.pts) == 12 and len(m0.balls) == 20
    assert r0[:4] == [0.082] * 4 and r0[4] > 1 and r0[-1] == 2.256
    # replay the loop: (points, restricted triangles, bad balls) before each insertion
    trace = []
    while True:
        bad = sum(1 for f in m0.balls for c, r, sg in m0.balls[f] if r > sg)
        trace.append((len(m0.pts), len(m0.balls), bad))
        w = m0.worst_ball()
        if w is None:
            break
        old = set(m0.tets)
        m0.insert(w[2], sorted(m0.face_tets[w[1]]))
        m0.update_faces(sorted({g for t in old ^ m0.tets for g in faces_of(t)}))
    assert [trace[k] for k in (0, 4, 10, 22, 28, 29)] == [
        (12, 20, 16),
        (16, 28, 24),
        (22, 40, 27),
        (34, 64, 11),
        (40, 76, 1),
        (41, 78, 0),
    ]
    assert all(t == 2 * p - 4 for p, t, _ in trace)  # a triangulated sphere at every step
    assert m0.pts == m.pts


def test_measured_versus_proved():
    """The guarantee needs sigma < 0.091 lfs. Measured: the torus comes out right at
    sigma = 1.5 lfs, 16 times the proved threshold, but not at 2 lfs, and the sizes
    stay below mu(S) / eps^2."""
    good = run("torus", F(3, 2), 1)
    assert len(good.pts) == 40 and set(edge_count(good.restricted()).values()) == {2}
    bad = run("torus", F(2), 1)
    assert len(bad.pts) == 20
    E = edge_count(bad.restricted())
    assert set(E.values()) != {2}
    V = {v for f in bad.restricted() for v in f}
    assert len(V) - len(E) + len(bad.restricted()) == 6
    mu = 4 * math.pi  # mu(S) = area / lfs^2 for the unit sphere
    for eps, seed in ((F(1, 2), 1), (F(3, 10), 2)):
        assert len(run("sphere", eps, seed).pts) < mu / float(eps) ** 2


def test_bad_input():
    with pytest.raises(ValueError):
        Sphere(0)
    with pytest.raises(ValueError):
        Torus(5, 3)
    with pytest.raises(RuntimeError):
        delaunay_surface_mesh(SPHERE, R / 5, seed=1, max_vertices=30)

History

Chew (1993) proposed meshing a curved surface by refining surface Delaunay balls. Edelsbrunner and Shah (1994, 1997) defined the restricted Delaunay triangulation and proved that the closed ball property makes it homeomorphic to the surface, and Amenta and Bern (1999) showed that for an ε\varepsilon-sample with ε<0.1\varepsilon < 0.1 every Voronoi face meets the surface in a topological ball or not at all. Boissonnat and Oudot (2005) introduced loose ε\varepsilon-samples, which a mesher can check on its own output, and proved that Chew-style refinement produces them with optimal size. Cheng, Dey, Ramos and Ray (2004, 2007) removed the need to know the local feature size, and the book of Cheng, Dey and Shewchuk (2013) gives the whole theory.

References

  1. Jean-Daniel Boissonnat and Steve Oudot, Provably good sampling and meshing of surfaces, Graphical Models 67(5), 2005, 405 to 451, Section 2 (surface Delaunay balls, Definition 2.2 of a loose epsilon-sample, Lemma 2.3), Section 2.3 (the constant epsilon_0, about 0.091), Theorems 4.3, 4.4 and 4.5 (manifold, homeomorphism and isotopy, Hausdorff distance at most 4.5 epsilon^2 times the largest d_M), Theorem 5.1 and Theorem 5.4 (lower and upper bounds on the size), Section 6 (the algorithm), Section 7 (persistent facets, Lemmas 7.1 and 7.2), Section 8 (Lemmas 8.1 to 8.4), Section 9.1 (removing skinny facets for angles below 30 degrees)
  2. L. Paul Chew, Guaranteed-quality mesh generation for curved surfaces, Proceedings of the 9th Annual Symposium on Computational Geometry, 1993, 274 to 280, the surface mesher that inserts centers of large surface Delaunay balls (general locator)
  3. Siu-Wing Cheng, Tamal K. Dey and Jonathan Richard Shewchuk, Delaunay Mesh Generation, CRC Press, 2013, Chapter 13 (restricted Delaunay triangulations of surface samples, pages 287 to 316), Chapter 14 (meshing smooth surfaces and volumes, pages 317 to 348)
  4. Siu-Wing Cheng, Tamal K. Dey, Edgar A. Ramos and Tathagata Ray, Sampling and meshing a surface with guaranteed topology and geometry, SIAM Journal on Computing 37(4), 2007, 1199 to 1227, refinement driven by the topological ball property instead of the local feature size (general locator)
  5. Jean-Daniel Boissonnat and Steve Oudot, Provably good sampling and meshing of Lipschitz surfaces, Proceedings of the 22nd Annual Symposium on Computational Geometry, 2006, 337 to 346, the extension to surfaces that are only Lipschitz (general locator)
  6. Herbert Edelsbrunner and Nimish R. Shah, Triangulating topological spaces, International Journal of Computational Geometry and Applications 7(4), 1997, 365 to 378, the restricted Delaunay triangulation and the closed ball property (general locator)
  7. Nina Amenta and Marshall Bern, Surface reconstruction by Voronoi filtering, Discrete and Computational Geometry 22(4), 1999, 481 to 504, the local feature size and epsilon-samples; Theorem 2 on Voronoi faces that meet the surface for epsilon below 0.1

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example