Algorithm Search⌘K

Algorithmadvanced

Medial surface of a solid

Also called 3D medial axis of a polyhedron, Sherbrooke-Patrikalakis-Brisson medial axis.

Computes the centres of maximal inscribed balls of a polyhedral solid, a complex of sheets, seams and junctions, by tracing seams from junction to junction as Sherbrooke, Patrikalakis and Brisson did.

Time
O(k^3 n^3) worst
Space
O(n^2) extra
Where
k = the largest number of faces that are nearest to one point; n = the number of faces of the polyhedron
Properties
deterministicexactiterative
Origin
Evan C. Sherbrooke, Nicholas M. Patrikalakis, Erik Brisson, 1996

The medial surface of a solid PP in R3\mathbb{R}^3 is the set of interior points that have two or more nearest points on the boundary, or, up to closure, the set of centres of the maximal balls inside PP. It is the three-dimensional medial axis: together with the radius of the ball at each point, the medial axis transform, it determines the solid, since PP is the union of its maximal balls. In the plane the medial axis of a polygon is a graph of curves. In space it is a two-dimensional complex. Its sheets are surfaces where two boundary elements are nearest. Its seams are curves where three or more sheets meet. Its junctions are points where seams meet. For a polyhedron the sheets are pieces of planes and quadric surfaces; curved sheets come only from reflex edges and reflex vertices. Sherbrooke, Patrikalakis and Brisson computed this complex for general polyhedra by tracing the seams from junction to junction and then filling in the sheets. This page states their method and implements its core step exactly for convex polyhedra, where every sheet is flat and the trace becomes a walk on the edges of a four-dimensional polytope.

In plain words

Blow up a balloon inside a solid until it touches the walls. If it touches two walls at once, its centre is on the medial surface. Move the balloon around, keeping it as big as it can be, and its centre draws a set of thin sheets inside the solid, like the walls of a honeycomb.

Where three walls are touched at once, the centre runs along a line, a seam where sheets meet. Where four are touched, the seams meet at a point, a junction.

The method starts at the corners of the solid, where several faces meet. From each corner it follows a seam inward until the balloon touches one more wall. That point is a junction, and new seams leave from it. When every seam has been followed, the sheets are the flat or curved pieces between the seams.

The problem

Input. A polyhedral solid PP: a bounded closed set with a boundary made of planar polygons. For the implemented case PP is convex, given as P={x:ni⋅x≤bi, i=1,…,n}P = \{x : n_i \cdot x \le b_i,\ i = 1, \ldots, n\} with unit normals nin_i, one for each facet. The normals have rational coordinates, such as (1,2,2)/3(1, 2, 2)/3, so every quantity below is rational.

Output. The medial surface as a cell complex: the junctions, each with its radius and its set of nearest boundary elements; the seams, as curves between junctions with the elements nearest along them; and the sheets, as regions bounded by seams and by the edges of PP.

Definitions. For x∈Px \in P, ρ(x)\rho(x) is the distance from xx to the boundary of PP. A ball B(x,r)⊆PB(x, r) \subseteq P is maximal if no other ball inside PP contains it. The medial surface M(P)M(P) is the closure of the set of interior points with at least two nearest boundary points. The medial axis transform is the map x↦ρ(x)x \mapsto \rho(x) on M(P)M(P).

For a convex PP, the distance to the plane of facet ii is di(x)=bi−ni⋅xd_i(x) = b_i - n_i \cdot x, and ρ(x)=min⁡idi(x)\rho(x) = \min_i d_i(x). The set T(x)T(x) of facets that attain the minimum is the tie set of xx. Then xx is in a sheet when ∣T(x)∣=2|T(x)| = 2, on a seam when ∣T(x)∣≥3|T(x)| \ge 3, and a junction when the seams through xx end there.

The algorithm

  1. TRACE-SEAMS(P)
  2. 1Q ← the vertices of P ▷ seams start on the boundary
  3. 2J ← an empty map from points to (radius, tie set)
  4. 3while Q is not empty do
  5. 4x ← POP(Q)
  6. 5if x is in J then continue
  7. 6(ρ, T) ← the distance from x to the boundary and the faces that attain it; J[x] ← (ρ, T)
  8. 7for each triple i, j, k in T and each sign of w = ±(n_i − n_j) × (n_i − n_k) do
  9. 8r ← max of n_l · w over l in T; S ← the faces l in T with n_l · w = r
  10. 9if i is not in S, or ρ = 0 and r ≥ 0, then skip this w ▷ not a seam, or leaves P
  11. 10t* ← the least t > 0 at which a face outside S is as near as S, or ρ / r if r > 0 and that is less
  12. 11y ← x + t* w; record the seam (x, y, S); push y on Q
  13. 12return J and the seams

Along x+twx + t w the faces of SS are at distance ρ−tr\rho - t r and stay nearest; the faces of TT outside SS fall behind at once, since their nl⋅wn_l \cdot w is smaller. A face ll outside TT catches up at t=(dl(x)−ρ)/(nl⋅w−r)t = (d_l(x) - \rho) / (n_l \cdot w - r) when nl⋅w>rn_l \cdot w > r, and line L10 takes the first such event. If r>0r > 0 the seam runs toward the boundary and reaches it at t=ρ/rt = \rho / r, at a vertex of PP. The sheets are not traced. The sheet of two faces ii and jj is the convex polygon spanned by the traced points whose tie set contains both, because its corners are junctions or vertices of PP.

The general case. For a nonconvex polyhedron, Sherbrooke, Patrikalakis and Brisson use the same plan with more kinds of boundary elements: faces, reflex edges and reflex vertices. A point of a seam is equidistant from three elements, so a seam is a curve on which a system of polynomial equations holds, and a junction solves a system with one more equation. The method finds the junctions at the vertices of the solid, traces each seam numerically from one junction to the next, and stops it where a fourth element becomes as near. It then forms each sheet from the cycle of seams and boundary edges around it. Two complications do not occur in the convex case. A nearest element must be checked against the whole boundary, not only against the planes. And seams are curved, so the trace steps along them and solves for the junction at the end.

Example

Let P=[0,4]×[0,2]×[0,2]P = [0, 4] \times [0, 2] \times [0, 2], with faces 0 to 5 on the planes x=4x = 4, x=0x = 0, y=2y = 2, y=0y = 0, z=2z = 2 and z=0z = 0. The trace starts at the 8 corners.

step point xx ρ\rho tie set TT seams found
corner (0,0,0)(0,0,0) 0 {1,3,5}\{1, 3, 5\} w=(1,1,1)w = (1,1,1), r=−1r = -1: faces 2 and 4 catch up at t=1t = 1, so the seam ends at (1,1,1)(1,1,1)
junction (1,1,1)(1,1,1) 1 {1,2,3,4,5}\{1, 2, 3, 4, 5\} 4 seams back to the corners at x=0x = 0, and w=(2,0,0)w = (2,0,0) with S={2,3,4,5}S = \{2,3,4,5\}, r=0r = 0: face 0 catches up at t=1t = 1, at (3,1,1)(3,1,1)
junction (3,1,1)(3,1,1) 1 {0,2,3,4,5}\{0, 2, 3, 4, 5\} the seam back to (1,1,1)(1,1,1) and 4 seams to the corners at x=4x = 4

The result has 2 junctions and 9 seams: 8 from the corners, each with 3 nearest faces and a radius that grows from 0 to 1, and the middle seam from (1,1,1)(1,1,1) to (3,1,1)(3,1,1), with 4 nearest faces and a constant radius 1. The 12 sheets belong to the 12 pairs of adjacent faces. The 8 sheets between an end face and a side face are triangles, such as (0,2,0),(0,2,2),(1,1,1)(0,2,0), (0,2,2), (1,1,1) for faces 1 and 2. The 4 sheets between two side faces are trapezoids, such as (0,2,2),(4,2,2),(3,1,1),(1,1,1)(0,2,2), (4,2,2), (3,1,1), (1,1,1) for faces 2 and 4. The opposite faces y=0y = 0 and y=2y = 2 are both nearest only along the middle seam, so they have no sheet of their own. For the cube [0,2]3[0,2]^3 the two junctions merge into the centre, whose tie set has all 6 faces, and only the 8 corner seams remain.

Correctness

For a convex PP and an interior xx, the ball B(x,ρ(x))B(x, \rho(x)) lies in every half-space, so it lies in PP. Its foot on each nearest plane is a boundary point, and every nearest boundary point is such a foot. So the nearest boundary points match the faces of T(x)T(x) one to one, and xx is on the medial surface exactly when ∣T(x)∣≥2|T(x)| \ge 2.

The trace is a walk on a polytope. Lift PP to

P^={(x,r)∈R4:r≥0, ni⋅x+r≤bi for every facet i},\hat{P} = \{(x, r) \in \mathbb{R}^4 : r \ge 0,\ n_i \cdot x + r \le b_i \text{ for every facet } i\},

the region under the graph of ρ\rho. The upper boundary of P^\hat{P} is the graph of ρ\rho. Its 2-faces project to the sheets, its edges off the floor r=0r = 0 project to the seams, and its vertices project to the junctions and to the vertices of PP. Lines L7 to L9 find every edge of P^\hat{P} at a vertex, except the edges in the floor. Line L10 finds the far end of each edge. Every junction is reached because of a simplex method argument. A vertex of P^\hat{P} with r>0r > 0 does not minimize rr, so it has an edge on which rr decreases. Following such edges reaches a vertex of PP in the floor, and the trace explores this path in reverse. The full proof is in the proof file.

These facts are checked by the tests, with Fraction. Random convex polyhedra are built from the 6 axis planes and 2 to 6 planes whose normals come from Pythagorean quadruples. On each one the tests check four things. A point on a traced seam has exactly the seam's faces as nearest; this is checked at over 500 rational points. The junctions equal those of a brute force, which solves bl−nl⋅x=ρb_l - n_l \cdot x = \rho for every 4 faces. For every triple of faces, the traced seams that contain it tile exactly the interval of the bisector line on which the three are nearest. And on the bisector plane of two faces, a rational point is in the polygon of the traced sheet corners exactly when both faces are nearest.

Proof: TRACE-SEAMS finds every junction and seam of the medial surface of a convex polyhedronfull

We use the pseudocode of the page. P={x:ni⋅x≤bi, i∈F}P = \{x : n_i \cdot x \le b_i,\ i \in F\} is a bounded convex polyhedron with nonempty interior, where FF indexes the facets of PP, one plane per facet, and each nin_i is a unit vector. Distinct facets have distinct outer normals. For x∈Px \in P, di(x)=bi−ni⋅x≥0d_i(x) = b_i - n_i \cdot x \ge 0, ρ(x)=min⁡i∈Fdi(x)\rho(x) = \min_{i \in F} d_i(x) and T(x)={i:di(x)=ρ(x)}T(x) = \{i : d_i(x) = \rho(x)\}.

Lemma 1 (nearest points are feet on nearest facets). For xx in the interior of PP, the distance from xx to the boundary is ρ(x)\rho(x), and the nearest boundary points are the points x+ρ(x)nix + \rho(x) n_i for i∈T(x)i \in T(x), which are distinct. So xx has two or more nearest boundary points exactly when ∣T(x)∣≥2|T(x)| \ge 2.

Proof. Let r=ρ(x)>0r = \rho(x) > 0. For z∈B(x,r)z \in B(x, r) and every ii, ni⋅z≤ni⋅x+r≤bin_i \cdot z \le n_i \cdot x + r \le b_i, so the open ball lies in the interior of PP and every boundary point is at distance at least rr. For i∈T(x)i \in T(x) the point y=x+rniy = x + r n_i satisfies di(y)=0d_i(y) = 0 and dl(y)=dl(x)−r nl⋅ni≥r−r=0d_l(y) = d_l(x) - r\, n_l \cdot n_i \ge r - r = 0 for every ll, so y∈Py \in P is on the plane of facet ii, a boundary point at distance rr. Conversely, let zz be a boundary point with ∣z−x∣=r|z - x| = r. Then dl(z)=0d_l(z) = 0 for some ll, and r=∣z−x∣≥nl⋅(z−x)=dl(x)−dl(z)=dl(x)≥rr = |z - x| \ge n_l \cdot (z - x) = d_l(x) - d_l(z) = d_l(x) \ge r. So dl(x)=rd_l(x) = r, l∈T(x)l \in T(x), and equality in the Cauchy-Schwarz step gives z−x=rnlz - x = r n_l. Distinct facets have distinct normals, so their feet are distinct. □\square

The lifted polytope. Let P^={(x,r):r≥0 and ni⋅x+r≤bi for i∈F}\hat{P} = \{(x, r) : r \ge 0 \text{ and } n_i \cdot x + r \le b_i \text{ for } i \in F\}. It is bounded, since x∈Px \in P and 0≤r≤ρ(x)0 \le r \le \rho(x), and it is the set of (x,r)(x, r) with x∈Px \in P and 0≤r≤ρ(x)0 \le r \le \rho(x). Call r≥0r \ge 0 the floor constraint and ni⋅x+r≤bin_i \cdot x + r \le b_i the constraint of facet ii; its row is ai=(ni,1)a_i = (n_i, 1). A face of P^\hat{P} is the set where a given set of constraints is tight, and its dimension is 44 minus the rank of the tight rows (for a face that is not empty).

Lemma 2 (rank of tie rows). For three distinct facets i,j,ki, j, k, the rows ai,aj,aka_i, a_j, a_k are linearly independent, and w=(ni−nj)×(ni−nk)≠0w = (n_i - n_j) \times (n_i - n_k) \ne 0.

Proof. Three distinct unit vectors are not on one line, since a line meets the unit sphere in at most two points. So ni−njn_i - n_j and ni−nkn_i - n_k are independent and w≠0w \ne 0. If αai+βaj+γak=0\alpha a_i + \beta a_j + \gamma a_k = 0, the last coordinate gives α+β+γ=0\alpha + \beta + \gamma = 0, so β(nj−ni)+γ(nk−ni)=0\beta (n_j - n_i) + \gamma (n_k - n_i) = 0 and β=γ=0=α\beta = \gamma = 0 = \alpha. □\square

Lemma 3 (edges and vertices). (a) A vertex of P^\hat{P} with r=0r = 0 is (v,0)(v, 0) for a vertex vv of PP, and conversely. (b) An edge of P^\hat{P} that is not in the floor has, at each relative interior point (x,r)(x, r), r=ρ(x)r = \rho(x) and exactly the facet constraints of a set SS with ∣S∣≥3|S| \ge 3 tight, and S=T(x)S = T(x).

Proof. (a) The floor face is P×{0}P \times \{0\}, whose faces are faces of P^\hat{P}, and its vertices are (v,0)(v, 0) for the vertices vv of PP. (b) On the relative interior of an edge the tight set is constant and has rank 3. The floor is not tight there, so the tight set consists of facet constraints of some set SS, and ∣S∣≥3|S| \ge 3 for rank 3. Tightness gives r=ds(x)r = d_s(x) for s∈Ss \in S, and r≤dl(x)r \le d_l(x) for all ll gives r=ρ(x)r = \rho(x) and S=T(x)S = T(x). □\square

Lemma 4 (local tie sets). Let x∈Px \in P with ρ=ρ(x)\rho = \rho(x) and T=T(x)T = T(x), and let v≠0v \ne 0. For all small t>0t > 0, dl(x+tv)=ρ−t nl⋅vd_l(x + tv) = \rho - t\, n_l \cdot v for l∈Tl \in T, and the facets of TT with the largest nl⋅vn_l \cdot v are exactly the facets nearest to x+tvx + tv, provided x+tv∈Px + tv \in P.

Proof. For l∉Tl \notin T, dl(x)>ρd_l(x) > \rho, so by continuity dl(x+tv)d_l(x + tv) stays larger than every ds(x+tv)d_s(x + tv), s∈Ts \in T, for small tt. Among the facets of TT the smallest distance belongs to the largest nl⋅vn_l \cdot v. □\square

Lemma 5 (one step). Let z=(x,ρ(x))z = (x, \rho(x)) be a vertex of P^\hat{P} and T=T(x)T = T(x). The pairs (w,S)(w, S) that pass line L9 correspond one to one, up to the order in which they are found, to the edges of P^\hat{P} at zz that are not in the floor. For each, line L11 returns the other end of the edge, which is a vertex of P^\hat{P}, and SS is the tie set on the open edge.

Proof. Let ee be an edge at zz not in the floor, and let (x+tv,ρ(x)−tc)(x + tv, \rho(x) - t c), 0≤t≤10 \le t \le 1, be a parametrization of it, with v≠0v \ne 0. (If v=0v = 0 the edge would be vertical, but on an open vertical segment below the graph of ρ\rho no facet constraint is tight, and on one above it the point is not in P^\hat{P}.) By Lemma 3, the open edge has a constant tie set SS with ∣S∣≥3|S| \ge 3, and by Lemma 4, SS is the set of l∈Tl \in T with the largest nl⋅vn_l \cdot v, and cc is that largest value. Take i<j<ki < j < k in SS. Then ni⋅v=nj⋅v=nk⋅vn_i \cdot v = n_j \cdot v = n_k \cdot v, so vv is orthogonal to ni−njn_i - n_j and ni−nkn_i - n_k and is a nonzero multiple of ww by Lemma 2. One of the two signs of line L7 makes ww a positive multiple of vv. For it, line L8 computes SS and r=ni⋅wr = n_i \cdot w, and i∈Si \in S. If ρ(x)=0\rho(x) = 0, the edge leaves the floor, so its rr coordinate grows, and r<0r < 0. So the pair passes line L9.

Conversely, let (w,S)(w, S) pass line L9, with i,j,k∈Si, j, k \in S. For small t>0t > 0 the point (x+tw,ρ(x)−tr)(x + tw, \rho(x) - tr) has ρ(x)−tr>0\rho(x) - tr > 0, because either ρ(x)>0\rho(x) > 0 or r<0r < 0. By Lemma 4 it lies in P^\hat{P} on the graph of ρ\rho, with exactly the facet constraints of SS tight, which have rank at least 3 by Lemma 2. So it is on an edge (a face of dimension at most 1 that contains a segment) not in the floor, and this edge contains zz and the direction (w,−r)(w, -r). Two passing pairs with the same edge have parallel ww of the same sign, and line L11 records both under one key, so each edge is recorded once.

Along the edge, the facet s∈Ss \in S has ds=ρ(x)−trd_s = \rho(x) - tr. A facet l∉Sl \notin S has dl(x+tw)=dl(x)−t nl⋅wd_l(x + tw) = d_l(x) - t\, n_l \cdot w, and dl(x)−ρ(x)≥0d_l(x) - \rho(x) \ge 0, with equality only for l∈T∖Sl \in T \setminus S, where nl⋅w<rn_l \cdot w < r. So ll stays farther than SS for all t>0t > 0 if nl⋅w≤rn_l \cdot w \le r, and it becomes as near at t=(dl(x)−ρ(x))/(nl⋅w−r)>0t = (d_l(x) - \rho(x)) / (n_l \cdot w - r) > 0 otherwise. The floor is reached at t=ρ(x)/rt = \rho(x) / r when r>0r > 0. The edge ends at the first of these events, which is t∗t^* of line L10. The set is bounded, so some event happens. At the end point yy a new constraint is tight: the floor, whose row (0,0,0,1)(0, 0, 0, 1) has product −r≠0-r \ne 0 with the direction (w,−r)(w, -r), or a facet ll, whose row has product nl⋅w−r≠0n_l \cdot w - r \ne 0. All rows of SS have product 0 with the direction. So the new row is not in the span of the rows of SS, the tight rows at yy have rank 4, and yy is a vertex. □\square

Lemma 6 (descent). Every vertex zz of P^\hat{P} with r>0r > 0 is joined to a vertex in the floor by a path of edges of P^\hat{P} that are not in the floor.

Proof. The linear function f(x,r)=rf(x, r) = r has its minimum 0 over P^\hat{P}, so zz does not minimize it. At a vertex of a polytope that does not minimize a linear function, some edge at the vertex decreases the function, since the edge directions at a vertex generate the cone of feasible directions there. That edge starts at r>0r > 0, so it is not in the floor. Its other end is a vertex with a smaller rr. The polytope has finitely many vertices, so repeating this ends at a vertex with r=0r = 0. □\square

Theorem. TRACE-SEAMS terminates. The keys of JJ are exactly the vertices of PP and the projections of the vertices of P^\hat{P} with r>0r > 0, each with its ρ\rho and TT. The recorded seams are exactly the projections of the edges of P^\hat{P} not in the floor, each with its tie set.

Proof. Every point pushed on QQ is a vertex of P^\hat{P} projected: those of line L1 by Lemma 3(a), and those of line L11 by Lemma 5. Line L5 processes each point at most once, there are finitely many vertices, and each processed point pushes finitely many points, so the loop terminates. Every recorded seam is an edge by Lemma 5.

For completeness, consider the graph GG whose nodes are the vertices of P^\hat{P} and whose arcs are the edges of P^\hat{P} not in the floor. When a node is processed, Lemma 5 records all its arcs and pushes all its neighbours. So the processed nodes are closed under neighbours, and they include every floor vertex by line L1. By Lemma 6 every node is connected in GG to a floor vertex, so every node is processed. Every arc has a processed end, so every arc is recorded. □\square

Corollary (the medial surface). An interior point xx of PP lies on the medial surface exactly when ∣T(x)∣≥2|T(x)| \ge 2, by Lemma 1, and then (x,ρ(x))(x, \rho(x)) lies on a face of P^\hat{P} of dimension at most 2 that is not in the floor. Such a face is a 2-face where the constraints of two facets ii and jj are tight (a sheet), or an edge (a seam), or a vertex (a junction). The sheet of ii and jj is the projection of the 2-face {r=di=dj}∩P^\{r = d_i = d_j\} \cap \hat{P}. This is a convex polygon whose vertices are vertices of P^\hat{P} with i,j∈Ti, j \in T, so it is the convex hull of the keys of JJ whose tie sets contain ii and jj. This is what sheet_points returns. If that 2-face has dimension below 2, the pair has no sheet.

Corollary (size). P^\hat{P} is a 4-polytope with at most ∣F∣+1|F| + 1 facets. By the upper bound theorem, a dd-polytope with NN facets has O(N⌊d/2⌋)O(N^{\lfloor d/2 \rfloor}) faces, so P^\hat{P} has O(n2)O(n^2) vertices, edges and 2-faces, and the medial surface of a convex polyhedron with nn facets has O(n2)O(n^2) junctions, seams and sheets.

Complexity

  • The size of the output. P^\hat{P} is a polytope in R4\mathbb{R}^4 with at most n+1n + 1 facets. By the upper bound theorem of McMullen it has O(n2)O(n^2) vertices and O(n2)O(n^2) edges, so the medial surface of a convex polyhedron with nn faces has O(n2)O(n^2) junctions, seams and sheets. This is proved, not measured.
  • The trace. Each traced point costs O(n)O(n) for its tie set at line L6. It tries O(k3)O(k^3) triples at line L7, and each triple costs O(n)O(n) for the event search at line L10. Over O(n2)O(n^2) points that is O(k3n3)O(k^3 n^3) time. If no five faces are nearest to one point, k≤4k \le 4 and the bound is O(n3)O(n^3). The space is O(n2)O(n^2) for the map JJ and the seams.
  • The input step. The code finds the vertices and the facets of PP from its half-spaces by brute force, in O(n4)O(n^4) time. A B-rep gives them directly.
  • The general case. For a nonconvex polyhedron the medial surface is part of the Voronoi diagram of the faces, edges and vertices, and its size can grow faster than quadratically in nn. The cost of the method of Sherbrooke, Patrikalakis and Brisson depends on the number of seams and on the numerical trace of each, through its step size and tolerance; this page states no worst-case bound for it.

Properties

  • Exact in the convex case. Each junction solves a linear system, and each seam end is a ratio of rational numbers, so the code computes every point with Fraction. In the general case the junctions are algebraic numbers. Floating-point tracing can then miss a short seam or join two seams that should stay apart, and Culver, Keyser and Manocha compute them exactly for this reason.
  • Degenerate ties. A point with five or more nearest faces, such as the centre of a cube, needs no special case. Line L8 groups all faces that stay nearest in a direction, and a seam with four or more nearest faces, such as the middle seam of the example, is traced once.
  • Not stable. As in the plane, a small change to the solid can add a large sheet. A tiny bump on a face of a cube adds sheets that reach from the bump to the middle of the cube. Applications usually prune sheets whose radius changes fast relative to their size.
  • Homotopy. The medial surface of a bounded open set has the same homotopy type as the set, so it keeps the handles and cavities of the solid.
  • The convex case is the 3D straight skeleton. For a convex polyhedron the medial surface is the trace of the faces as they move inward at unit speed, the three-dimensional analogue of the straight skeleton of a convex polygon.

Variants and improvements

  • Exact computation. Culver, Keyser and Manocha compute the seams and junctions of a general polyhedron with exact algebraic arithmetic, which removes the failures of floating-point tracing at the cost of much slower arithmetic.
  • From the Voronoi diagram of samples. Sample the boundary densely and compute the Voronoi diagram of the samples. Its poles, the Voronoi vertices far from the sample, approximate the medial surface, and the power crust of Amenta, Choi and Kolluri uses them to rebuild the surface and the medial axis together. This works on any input but gives only an approximation, with spurious sheets that must be pruned.
  • From a voxel grid. A distance transform on voxels and a thinning step give a discrete medial surface. It is simple and robust, but its accuracy is limited by the voxel size.
  • Shrinking balls. For each boundary sample, shrink a ball tangent at the sample until it touches the boundary at one more point. Its centre is a medial point, and mid-surface extraction uses this to reduce thin solids.
  • Curved solids. For solids bounded by NURBS surfaces, seams are traced by solving systems of equations on the surfaces, with the same plan of junctions, seams and sheets.

When to use it

Use the medial surface when the question is about local thickness or shape. Examples are hot spots in castings, where the largest inscribed balls show the last metal to solidify; thin walls in molded and printed parts; the reduction of thin solids to shells by mid-surface extraction; and the split of a solid into simple pieces for meshing. Use the exact convex trace when the solid or its pieces are convex polyhedra, and tracing with exact arithmetic for general polyhedra when the topology of the result matters. When only an approximate skeleton is needed, as in shape matching or animation, sampled or voxel methods are simpler and more robust. For thickness at single points, a shape diameter function is cheaper still.

Pitfalls

  • Distance to planes, not to faces. In a nonconvex solid, the nearest point of a face plane may lie off the face, and a far face can be nearer than its plane suggests. The rule ρ=min⁡idi\rho = \min_i d_i holds only for convex solids.
  • Redundant planes. A plane that touches PP only at a vertex or an edge is at distance 0 there and would join the tie sets. Use only the planes of the facets, as the code does.
  • Only one sign of the seam direction. The cross product gives the line of a seam, not its side. Test both signs and reject the one that leaves the solid or loses one of the three faces, as line L9 does.
  • Missing seams in floating point. A junction with five or more nearest elements splits into several close junctions under rounding, and short seams appear or vanish. Use exact arithmetic or merge junctions closer than a tolerance, and accept that the topology may then be wrong.
  • Expecting a curve skeleton. The medial surface of a solid is two-dimensional. A long square bar has four strips that run from its long edges to its axis, not a single curve, so curve skeletons need a further reduction.

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.

medial_surface_of_a_solid.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/medial-surface-of-a-solid/. The authors are listed in prov/B7FYY7.jsonl.

"""The seams and junctions of the medial surface of a convex polyhedron.

The polyhedron is P = {x : n_i . x <= b_i} with unit normals n_i whose
coordinates are rational, such as (1, 2, 2)/3, so that the distance
b_i - n_i . x from an inside point to the plane of face i is rational and
every computation is exact with Fraction.

For an inside point x of a convex polyhedron, the nearest boundary points
are the feet on the nearest face planes, so x is on the medial surface
exactly when two or more faces are nearest. The medial surface is made of
flat sheets (two faces nearest), seams (three or more faces nearest along a
line) and junctions (the ends of seams inside P). The code traces the seams
from the vertices of P, as Sherbrooke, Patrikalakis and Brisson trace seams
from the boundary in the general case. Degenerate ties, such as the centre
of a cube where six faces are nearest, are handled.

Cost: finding the vertices and faces of P by brute force takes O(F^4) for F
planes. Each junction with a tie set T tries O(|T|^3) directions, and each
seam takes O(F) time to find its end, so the trace takes O(J (|T|^3 + F))
for J junctions and vertices.
"""

from __future__ import annotations

from fractions import Fraction
from itertools import combinations
from typing import Sequence

Vec = tuple[Fraction, Fraction, Fraction]
Plane = tuple[Vec, Fraction]


def dot(a: Vec, b: Vec) -> Fraction:
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def sub(a: Vec, b: Vec) -> Vec:
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def cross(a: Vec, b: Vec) -> Vec:
    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 det3(a: Vec, b: Vec, c: Vec) -> Fraction:
    return dot(a, cross(b, c))


def solve3(rows: Sequence[Vec], rhs: Sequence[Fraction]) -> Vec | None:
    """Cramer's rule for a 3 by 3 system; None if it is singular."""
    d = det3(rows[0], rows[1], rows[2])
    if d == 0:
        return None
    cols = [tuple(r[k] for r in rows) for k in range(3)]
    out = []
    for k in range(3):
        c = list(cols)
        c[k] = tuple(rhs)
        out.append(det3(c[0], c[1], c[2]) / d)  # transpose has the same det
    return (out[0], out[1], out[2])


class ConvexPolyhedron:
    """P = {x : n_i . x <= b_i}. Precondition: every n_i has length 1, all
    data are Fractions, and P is bounded with nonempty interior."""

    def __init__(self, planes: Sequence[tuple[Sequence[Fraction], Fraction]]):
        self.planes: list[Plane] = [((Fraction(n[0]), Fraction(n[1]), Fraction(n[2])), Fraction(b))
                                    for n, b in planes]
        for n, _ in self.planes:
            if dot(n, n) != 1:
                raise ValueError("normals must be unit vectors")
        self.vertices = self._vertices()
        self.faces = self._faces()

    def dist(self, i: int, x: Vec) -> Fraction:
        n, b = self.planes[i]
        return b - dot(n, x)

    def inside(self, x: Vec) -> bool:
        return all(self.dist(i, x) >= 0 for i in range(len(self.planes)))

    def _vertices(self) -> list[Vec]:
        out: set[Vec] = set()
        for i, j, k in combinations(range(len(self.planes)), 3):
            x = solve3([self.planes[i][0], self.planes[j][0], self.planes[k][0]],
                       [self.planes[i][1], self.planes[j][1], self.planes[k][1]])
            if x is not None and self.inside(x):
                out.add(x)
        return sorted(out)

    def _faces(self) -> list[int]:
        """The planes that carry a facet: at least three vertices on the plane
        that are not on one line."""
        out = []
        for i in range(len(self.planes)):
            on = [v for v in self.vertices if self.dist(i, v) == 0]
            if any(cross(sub(b, a), sub(c, a)) != (0, 0, 0) for a, b, c in combinations(on, 3)):
                out.append(i)
        return out

    def nearest(self, x: Vec) -> tuple[Fraction, frozenset[int]]:
        """The distance from x to the boundary and the faces that attain it."""
        ds = {i: self.dist(i, x) for i in self.faces}
        r = min(ds.values())
        return r, frozenset(i for i, d in ds.items() if d == r)


Seam = tuple[Vec, Vec, frozenset[int]]


def medial_seams(P: ConvexPolyhedron) -> tuple[dict[Vec, tuple[Fraction, frozenset[int]]], list[Seam]]:
    """Trace the seam graph of the medial surface of P.

    Returns the junctions and vertices of P, each with its radius and its set
    of nearest faces, and the seams as (start, end, faces nearest along it)."""
    queue: list[Vec] = list(P.vertices)  # @line L1
    junctions: dict[Vec, tuple[Fraction, frozenset[int]]] = {}  # @line L2
    seams: dict[tuple[frozenset[Vec], frozenset[int]], Seam] = {}
    while queue:  # @line L3
        x = queue.pop()  # @line L4
        if x in junctions:  # @line L5
            continue
        rho, T = P.nearest(x)  # @line L6
        junctions[x] = (rho, T)
        ns = {i: P.planes[i][0] for i in P.faces}
        for i, j, k in combinations(sorted(T), 3):  # @line L7
            w = cross(sub(ns[i], ns[j]), sub(ns[i], ns[k]))
            if w == (0, 0, 0):
                continue
            for v in (w, (-w[0], -w[1], -w[2])):
                r = max(dot(ns[l], v) for l in T)  # @line L8
                S = frozenset(l for l in T if dot(ns[l], v) == r)
                if dot(ns[i], v) != r or not (rho > 0 or r < 0):  # @line L9
                    continue
                # along x + t v the faces of S are at distance rho - t r
                best = rho / r if r > 0 else None  # @line L10
                for l in P.faces:
                    if l in S:
                        continue
                    a = dot(ns[l], v)
                    if a > r:
                        t = (P.dist(l, x) - rho) / (a - r)
                        if best is None or t < best:
                            best = t
                assert best is not None and best > 0, "P must be bounded"
                y = (x[0] + best * v[0], x[1] + best * v[1], x[2] + best * v[2])  # @line L11
                key = (frozenset((x, y)), S)
                if key not in seams:
                    seams[key] = (x, y, S)
                queue.append(y)
    return junctions, list(seams.values())  # @line L12


def sheet_points(junctions: dict[Vec, tuple[Fraction, frozenset[int]]], i: int, j: int) -> list[Vec]:
    """The corners of the sheet of faces i and j: the traced points whose
    nearest faces include both. The sheet is their convex hull."""
    return sorted(x for x, (_, T) in junctions.items() if i in T and j in T)


def in_convex_hull_planar(pts: Sequence[Vec], x: Vec) -> bool:
    """Is x in the convex hull of the coplanar points pts? Exact, by
    projection to the coordinate plane where the points are not degenerate."""
    if not pts:
        return False
    if len(pts) == 1:
        return x == pts[0]
    a = pts[0]
    # the plane (or line) of the points
    b = next((p for p in pts if p != a), None)
    if b is None:
        return x == a
    c = next((p for p in pts if cross(sub(b, a), sub(p, a)) != (0, 0, 0)), None)
    if c is None:  # collinear: a segment
        d = sub(b, a)
        if cross(d, sub(x, a)) != (0, 0, 0):
            return False
        ts = [dot(sub(p, a), d) for p in pts]
        tx = dot(sub(x, a), d)
        return min(ts) <= tx <= max(ts)
    n = cross(sub(b, a), sub(c, a))
    if dot(n, sub(x, a)) != 0:
        return False
    k = max(range(3), key=lambda q: abs(n[q]))
    ax = [q for q in range(3) if q != k]
    pr = sorted({(p[ax[0]], p[ax[1]]) for p in pts})
    q = (x[ax[0]], x[ax[1]])

    def turn(o, p1, p2):
        return (p1[0] - o[0]) * (p2[1] - o[1]) - (p1[1] - o[1]) * (p2[0] - o[0])

    lower: list = []
    for p in pr:
        while len(lower) >= 2 and turn(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    upper: list = []
    for p in reversed(pr):
        while len(upper) >= 2 and turn(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    hull = lower[:-1] + upper[:-1]
    return all(turn(hull[m], hull[(m + 1) % len(hull)], q) >= 0 for m in range(len(hull)))
test_medial_surface_of_a_solid.py 206 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/medial-surface-of-a-solid/. The authors are listed in prov/B7FYY7.jsonl.

import itertools
import random
import unittest
from fractions import Fraction as Fr

from medial_surface_of_a_solid import (ConvexPolyhedron, cross, dot, in_convex_hull_planar, medial_seams,
                                       sheet_points, sub)

AXES = [((1, 0, 0), 1), ((-1, 0, 0), 1), ((0, 1, 0), 1), ((0, -1, 0), 1), ((0, 0, 1), 1), ((0, 0, -1), 1)]


def rational_unit_normals():
    """Unit vectors with rational coordinates from Pythagorean quadruples."""
    out = set()
    for (a, b, c), d in [((1, 2, 2), 3), ((2, 3, 6), 7), ((1, 4, 8), 9), ((4, 4, 7), 9), ((2, 6, 9), 11),
                         ((6, 6, 7), 11)]:
        for p in itertools.permutations((a, b, c)):
            for s in itertools.product((1, -1), repeat=3):
                out.add(tuple(Fr(s[k] * p[k], d) for k in range(3)))
    return sorted(out)


NORMALS = rational_unit_normals()


def box(a, b, c):
    return ConvexPolyhedron([((1, 0, 0), a), ((-1, 0, 0), 0), ((0, 1, 0), b), ((0, -1, 0), 0),
                             ((0, 0, 1), c), ((0, 0, -1), 0)])


def random_polyhedron(rng):
    planes = [(n, Fr(rng.randrange(6, 13), 3)) for n, _ in AXES]
    for n in rng.sample(NORMALS, rng.randrange(2, 7)):
        planes.append((n, Fr(rng.randrange(3, 10), 3)))
    return ConvexPolyhedron(planes)


def solve(rows, rhs):
    """Gaussian elimination over Fractions; None if singular."""
    m = [list(r) + [v] for r, v in zip(rows, rhs)]
    k = len(m)
    for c in range(k):
        p = next((r for r in range(c, k) if m[r][c] != 0), None)
        if p is None:
            return None
        m[c], m[p] = m[p], m[c]
        for r in range(k):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                m[r] = [x - f * y for x, y in zip(m[r], m[c])]
    return [m[r][k] / m[r][r] for r in range(k)]


def brute_junctions(P):
    """Every interior point where four faces with independent equations tie
    for nearest: solve b_l - n_l . x = rho for each 4-subset."""
    out = set()
    for quad in itertools.combinations(P.faces, 4):
        s = solve([list(P.planes[l][0]) + [Fr(1)] for l in quad], [P.planes[l][1] for l in quad])
        if s is None:
            continue
        x, rho = (s[0], s[1], s[2]), s[3]
        if rho > 0 and P.inside(x) and set(quad) <= P.nearest(x)[1]:
            out.add(x)
    return out


def brute_seam_interval(P, i, j, k):
    """The parameter interval on the line equidistant from faces i, j, k on
    which all three are nearest, by checking each other face in turn."""
    ni, nj, nk = (P.planes[l][0] for l in (i, j, k))
    w = cross(sub(ni, nj), sub(ni, nk))
    x0 = solve([list(sub(ni, nj)), list(sub(ni, nk)), list(w)],
               [P.planes[i][1] - P.planes[j][1], P.planes[i][1] - P.planes[k][1], Fr(0)])
    x0 = tuple(x0)
    lo, hi = None, None
    # constraints of the form a + t c >= 0
    cons = [(P.dist(i, x0), -dot(ni, w))]
    for l in P.faces:
        cons.append((P.dist(l, x0) - P.dist(i, x0), -dot(P.planes[l][0], w) + dot(ni, w)))
    for a, c in cons:
        if c == 0:
            if a < 0:
                return None
        elif c > 0:
            t = -a / c
            lo = t if lo is None else max(lo, t)
        else:
            t = -a / c
            hi = t if hi is None else min(hi, t)
    if lo is None or hi is None or lo >= hi:
        return None
    return x0, w, lo, hi


def param(x0, w, y):
    return dot(sub(y, x0), w) / dot(w, w)


class TestHandCases(unittest.TestCase):
    def test_cube(self):
        P = box(2, 2, 2)
        J, S = medial_seams(P)
        inner = {x: v for x, v in J.items() if v[0] > 0}
        self.assertEqual(list(inner), [(1, 1, 1)])
        self.assertEqual(inner[(1, 1, 1)], (1, frozenset(range(6))))
        self.assertEqual(len(S), 8)
        self.assertTrue(all(len(s[2]) == 3 for s in S))

    def test_long_box(self):
        P = box(4, 2, 2)
        J, S = medial_seams(P)
        inner = sorted(x for x, v in J.items() if v[0] > 0)
        self.assertEqual(inner, [(1, 1, 1), (3, 1, 1)])
        self.assertEqual(len(S), 9)
        mid = [s for s in S if len(s[2]) == 4]
        self.assertEqual(len(mid), 1)
        self.assertEqual(mid[0][2], frozenset({2, 3, 4, 5}))

    def test_sheet_of_cube(self):
        P = box(2, 2, 2)
        J, _ = medial_seams(P)
        # the sheet of faces x = 2 and y = 2 is the triangle (2,2,0), (2,2,2), (1,1,1)
        self.assertEqual(sheet_points(J, 0, 2), sorted([(2, 2, 0), (2, 2, 2), (1, 1, 1)]))


class TestRandom(unittest.TestCase):
    def test_seams_are_equidistant(self):
        """Every rational point inside a traced seam has exactly the seam's
        faces as nearest, and they number three or more."""
        rng = random.Random(1)
        checked = 0
        for _ in range(30):
            P = random_polyhedron(rng)
            J, S = medial_seams(P)
            for a, b, faces in S:
                self.assertGreaterEqual(len(faces), 3)
                for _ in range(4):
                    t = Fr(rng.randrange(1, 100), 100)
                    x = tuple(a[q] + t * (b[q] - a[q]) for q in range(3))
                    self.assertTrue(P.inside(x))
                    self.assertEqual(P.nearest(x)[1], faces)
                    checked += 1
            for x, (rho, T) in J.items():
                self.assertEqual(P.nearest(x), (rho, T))
        self.assertGreater(checked, 500)

    def test_junctions_against_brute_force(self):
        rng = random.Random(2)
        for _ in range(18):
            P = random_polyhedron(rng)
            J, _ = medial_seams(P)
            self.assertEqual({x for x, v in J.items() if v[0] > 0}, brute_junctions(P))
            self.assertEqual({x for x, v in J.items() if v[0] == 0}, set(P.vertices))

    def test_seams_against_brute_force(self):
        """For every triple of faces, the traced seams that contain it tile
        exactly the interval of the bisector line where the three are nearest."""
        rng = random.Random(3)
        for _ in range(18):
            P = random_polyhedron(rng)
            _, S = medial_seams(P)
            for tri in itertools.combinations(P.faces, 3):
                got = [s for s in S if set(tri) <= s[2]]
                want = brute_seam_interval(P, *tri)
                if want is None:
                    self.assertEqual(got, [])
                    continue
                x0, w, lo, hi = want
                ivs = sorted(tuple(sorted((param(x0, w, a), param(x0, w, b)))) for a, b, _ in got)
                self.assertTrue(ivs)
                self.assertEqual(ivs[0][0], lo)
                self.assertEqual(ivs[-1][1], hi)
                for p, q in zip(ivs, ivs[1:]):
                    self.assertEqual(p[1], q[0])

    def test_sheets_against_nearest_faces(self):
        """A rational point of the bisector plane of faces i and j is in the
        hull of the traced sheet corners exactly when i and j are nearest."""
        rng = random.Random(4)
        checked = 0
        for _ in range(20):
            P = random_polyhedron(rng)
            J, _ = medial_seams(P)
            for i, j in itertools.combinations(P.faces, 2):
                pts = sheet_points(J, i, j)
                if len(pts) < 3:
                    continue
                m = sub(P.planes[i][0], P.planes[j][0])
                e = next(cross(m, a) for a in ((1, 0, 0), (0, 1, 0), (0, 0, 1)) if cross(m, a) != (0, 0, 0))
                f = cross(m, e)
                c = tuple(sum(p[q] for p in pts) / len(pts) for q in range(3))
                for _ in range(6):
                    s, t = Fr(rng.randrange(-40, 41), 20), Fr(rng.randrange(-40, 41), 20)
                    x = tuple(c[q] + s * e[q] + t * f[q] for q in range(3))
                    want = P.inside(x) and {i, j} <= P.nearest(x)[1]
                    self.assertEqual(in_convex_hull_planar(pts, x), want)
                    checked += 1
        self.assertGreater(checked, 500)


if __name__ == "__main__":
    unittest.main()

History

Blum introduced the medial axis in 1967 for shapes in the plane, and the definition carries over to any dimension. For polyhedra, Milenkovic computed the Voronoi diagram of a polyhedron by tracing in 1993. Sherbrooke, Patrikalakis and Brisson gave a conference version of their algorithm at the ACM Symposium on Solid Modeling and Applications in 1995 and the full algorithm in 1996. It handles polyhedra of any genus with nonconvex vertices and edges and finds the medial axis transform with its radius function. Culver, Keyser and Manocha made the computation exact in 1999 and 2004. From the late 1990s, approximations from boundary samples, such as the power crust of Amenta, Choi and Kolluri in 2001, became the usual choice for meshes and scanned shapes. Exact tracing remained the method for CAD solids with few faces.

References

  1. Evan C. Sherbrooke, Nicholas M. Patrikalakis and Erik Brisson, An algorithm for the medial axis transform of 3D polyhedral solids, IEEE Transactions on Visualization and Computer Graphics 2(1), 44 to 61, 1996, the classification of medial points into sheets, seams and junctions, the tracing of seams between junctions, and the examples on convex and nonconvex polyhedra with holes
  2. Tim Culver, John Keyser and Dinesh Manocha, Exact computation of the medial axis of a polyhedron, Computer Aided Geometric Design 21(1), 65 to 98, 2004, the exact computation of seams and junctions with algebraic numbers and its comparison with floating-point tracing
  3. Nina Amenta, Sunghee Choi and Ravi Krishna Kolluri, The power crust, Proceedings of the Sixth ACM Symposium on Solid Modeling and Applications, 2001, the approximation of the medial axis by the Voronoi poles of a dense boundary sample

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