Algorithmadvanced
Liepa hole filling
Also called minimum weight hole triangulation.
Liepa's method that triangulates a hole by dynamic programming over its boundary, minimising area and dihedral angles, then refines and fairs the patch.
- Solves
- Mesh hole filling
- Time
- Θ(n^3) worst
- Space
- Θ(n^2) extra
- Where
- n = the number of vertices of the border loop
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter Liepa, 2003
Liepa hole filling closes a hole of an oriented triangle mesh in three steps. First, a dynamic program over the border loop of vertices chooses the triangulation of the loop, with no new vertices, of least weight. The weight is a pair: the largest dihedral angle between neighbouring triangles, the mesh triangles at the loop included, and then the total area. Second, refinement splits large triangles at their centroids and flips edges, so that the patch gets the edge length of the mesh around it. Third, fairing moves the new vertices to a smooth position with the loop fixed. The program is the polygon triangulation DP of Klincsek and of Barequet and Sharir applied to a loop in space, and takes time and space. It solves the mesh hole filling problem for one loop, and the patch it gives is a guess at the missing surface, judged by how it looks and by measurement, not by a theorem.
In plain words
A hole in a mesh has a ring of corners around it. Pick any way to cut the ring into triangles by joining its corners: that already closes the hole. There are very many ways, so we score each one. A cut is bad if two neighbouring triangles meet at a sharp fold, or if the triangles cover a lot of area.
Finding the best cut looks hard, but it is not. The side from the first corner to the last always belongs to one triangle, and that triangle splits the ring into two smaller rings. So solve all small rings first and build up.
The best cut has big, long triangles. So split each big one at its middle, flip edges that make thin triangles, and slide each new corner to the average of its neighbours. The patch is then smooth and as fine as the mesh around it.
The problem
The input is an oriented manifold mesh with exact vertex positions and one border loop , listed in the direction in which the patch must use the loop edges, that is, against the direction of the mesh faces on them. For each loop edge , let be the third vertex of the mesh triangle on it. The output is a set of triangles, with new vertices, whose border is the loop, so that the mesh with the patch has the loop edges as inner edges and a consistent orientation. The problem statement, its hardness, and other methods are on the mesh hole filling page.
The algorithm
For a triangle with , its weight is , where is its area and is the largest dihedral angle between and its neighbours that are already known: the triangle chosen on the edge inside the part , or the mesh triangle with apex when ; the same for the edge ; and the mesh triangle on when . The dihedral angle of two triangles is the angle between their normals by the right-hand rule, 0 when they are flat. Weights add by and are compared in lexicographic order.
LIEPA-FILL(M, v[0 .. n − 1])- 1
for i ← 0 to n − 2 do W[i][i + 1] ← (0, 0) - 2
for j ← 2 to n − 1 do ▷ by the length of the interval - 3
for i ← 0 to n − 1 − j do - 4
k ← i + j; W[i][k] ← ∞ - 5
for m ← i + 1 to k − 1 do - 6
c ← W[i][m] ⊕ W[m][k] ⊕ Ω(i, m, k) - 7
if c < W[i][k] then W[i][k] ← c; O[i][k] ← m - 8
T ← the triangles (v_i, v_O[i][k], v_k), from (0, n − 1) down by the stored apexes - 9
repeat: split each triangle of T at its centroid x if α|x − v| > σ(v) and α|x − v| > σ(x) for its 3 vertices v - 10
flip each edge of T, not on the loop, whose two opposite angles sum to more than π until no triangle was split- 11
move each new vertex to the solution of the Laplace equation on T, with the loop fixed return T
Here is the mean length of the mesh edges at for a loop vertex, and is the mean of at the three corners for a new centroid . The factor sets the density of the patch, and the code uses .
The predicate and its failure. The angle term compares angles between normals, and each normal is a cross product of edge vectors. For a nearly flat pair, the angle is near 0 and the normals are nearly parallel, so in floating point the cosine rounds to 1 and different near-flat choices tie. The choices of the program then depend on rounding. This does not break the result, since every triangulation closes the hole, but it makes the output depend on the order of the tests. A sliver triangle with a zero normal has no angle; the code gives it the worst angle , so that the program avoids it when it can. With integer or rational coordinates and an exact weight such as the sum of the squared double areas, the program is exact.
Example
The area alone. For the skew loop , , , , the hole filling page shows that the diagonal gives area , and the diagonal gives .
The angle first. Now let this loop be a hole in a folded sheet, with the mesh triangles , , , and , , , . The table follows lines L1 to L7.
| interval | apex | angles with the known neighbours | weight |
|---|---|---|---|
| 1 | with : ; with : | ||
| 2 | with : ; with : | ||
| with : ; with : ; with : | |||
| with : ; with : ; with : ; and from |
The angle with is , because the normal of is and the normal of is . Line L7 keeps , since , and the patch is , . It has more area than the other choice, but it follows the two planes of the sheet, which meet at a crease of . On this small loop, the refinement of line L9 adds no vertex, because each centroid is closer to the corners than .
Correctness
Three facts are proved, and one is only measured.
- The program is exact for a monotone weight. If the weight of a triangle does not depend on its neighbours and the operation is monotone, as sum and max are, the program returns a triangulation of least weight. Every triangulation of the part has one triangle on the chord , and its apex splits the rest into two smaller parts, so the induction of the polygon triangulation DP applies to the loop in space. The tests check this against all triangulations for loops up to 8 vertices, with the exact sum of squared double areas, with random integer tables, and with max.
- Liepa's weight is not monotone, so the program is a heuristic for it. The lexicographic pair fails monotonicity: , but adding gives . A 5-vertex loop with such weights makes the program miss the optimum. The angle term also depends on the triangles chosen inside the parts. So the patch has the stated weight, but it need not be the best one. On random loops in the tests it was worse than the exhaustive optimum in 72 of 300 cases.
- The patch closes the hole with a consistent orientation. Each triangle uses its edges as . Each chord is used once in each direction, by the triangle below it and by its parent, and each loop edge once, against the mesh. Splits and flips keep these directed edges, and a flip that would make a third face on an edge is skipped.
- The fairing has one solution. With the loop fixed, the Laplace system on the new vertices is positive definite when each new vertex reaches the loop, so it has a unique solution, which is flat when the loop is flat.
The full proofs are below.
Proof: The loop dynamic program is optimal for monotone weights, its patch closes the hole with a consistent orientation, and the membrane fairing has a unique solutionfull
Setup. The loop is , , listed in the direction in which the patch must use its edges. For , let be the abstract polygon , closed by the chord . A triangulation of is a set of triangles with over these vertices that cut it into triangles without crossing chords, in the sense of a convex polygon with the same vertex order. The polygon is the whole loop. A weight is a value for each triangle in a set with a total order , and an operation that is associative and commutative with a neutral element . The weight of a triangulation is , and . The operation is monotone if implies .
Lemma 1 (decomposition). For , every triangulation of contains exactly one triangle with the chord as an edge, say , and is the union of a triangulation of and one of . Every choice of and of the two smaller triangulations gives a triangulation of in this way, and different choices give different triangulations.
Proof. The chord is an edge of the polygon , so it lies in exactly one triangle of , whose third vertex is strictly between and . The chords and split into this triangle, and , and no chord of crosses them, so the other triangles of fall into the two parts and triangulate them. Conversely, a triangle and triangulations of the two parts have no crossing chords, since chords inside and inside only use vertices of one part. The triple , left part, right part is recovered from , so the map is one to one.
The number of triangulations of an -vertex loop therefore satisfies and , the recurrence of the Catalan numbers, so . The tests check this count for by enumeration.
Claim 1 (optimality). Suppose does not depend on the apexes chosen inside the parts, and is monotone. Then after lines L1 to L7, is the least weight of a triangulation of , and line L8 returns a triangulation that has this weight.
Proof. By induction on . For the only triangulation is empty, and line L1 sets . For , the loop of line L2 has already set the costs of all shorter intervals. Line L6 computes, for each , the value , which by induction is the weight of the triangulation made of and the stored optimal parts, and line L7 keeps the least . Now let be any triangulation of , with the triangle and the parts of Lemma 1. Then , and by induction and . Monotonicity, used twice with commutativity, gives . So the least is at most the weight of every triangulation, and it is the weight of one. Line L8 follows the stored apexes from and outputs exactly that triangulation.
Sum and maximum are monotone, so the program is exact for the total area and for the largest weight of one triangle.
Claim 2 (the lexicographic pair is not monotone). With pairs that add by and are ordered lexicographically, the program can return a triangulation that is not optimal.
Proof. We have , but . Take with , , , , , and for every other triangle. For the program keeps the part of weight over of weight . Every triangulation that does not use contains a triangle of weight , so the program returns weight , while has weight .
Liepa's weight is such a pair, and its angle term also depends on the apexes of the triangles chosen inside the parts, so Claim 1 does not apply to it. The program then returns a triangulation whose stored weight is its true weight, since each pair of neighbouring patch triangles is a parent and a child in the recursion and is counted once, but the triangulation need not be the best one. The tests compare it with exhaustive search on loops of up to 7 vertices and check only that it is never better than the optimum.
Claim 3 (the patch closes the hole consistently). Suppose the mesh is an oriented manifold mesh and the loop is a border loop listed as returned by border_loops, with distinct vertices. Then the triangles of line L8, added to the mesh, give an oriented manifold mesh in which each loop edge has two faces.
Proof. Each triangle with uses its edges as , and . A chord with , other than , is the chord of exactly one triangle , where it is used as . In the recursion of line L8, the interval comes from a parent triangle that has and as its first and second, or second and third, vertices, so the parent uses the same edge as , and no other triangle contains it. So inside the patch each chord has two faces with opposite directions. A loop edge lies in exactly one patch triangle, used as , and the loop edge is used as by the top triangle. The mesh uses each loop edge in the opposite direction, because border_loops lists the loop against the border edges. So each loop edge gets a second face with the opposite direction. The chords join loop vertices that are not neighbours in the loop, and if such a chord were already an edge of the mesh, it would get a third face. This case is excluded by the hypothesis of a manifold result and must be checked in use.
Claim 4 (refinement keeps the closing). A centroid split replaces a triangle by , and for a new vertex . It keeps the three directed edges of the triangle, and adds the edges , , , each with two faces in opposite directions. A flip in line L10 replaces two triangles and by and , which keep the four outer directed edges and replace , by , . The flip is skipped when or when is already an edge of the patch, so no edge gets a third face, and loop edges are never flipped. So the conclusions of Claim 3 hold after every step. Each round of line L9 either splits a triangle or ends the loop, and the number of rounds is bounded by the parameter, so the refinement stops. Each loop of flips stops after a bounded number of flips.
Claim 5 (the membrane is unique, flat for a flat loop). Let be the new vertices of the patch, and let every vertex of be joined to a loop vertex by a path of patch edges. Then the system for , with the loop vertices fixed, has a unique solution, Gauss-Seidel sweeps converge to it, and if the loop lies in a plane, so does the solution.
Proof. Write the system as , where is the graph Laplacian restricted to . is symmetric and weakly diagonally dominant, with strict dominance in each row of a vertex next to the loop. Because every free vertex reaches the loop, is irreducibly diagonally dominant, so it is non-singular and positive definite. Gauss-Seidel converges for every symmetric positive definite matrix. For a plane that contains the loop, the function is affine, so also solves the system for the values on the loop, and the constant is a solution. By uniqueness for all .
Complexity
Lines L2 to L7 test each triple once, triples, each in time on the real RAM with one dihedral angle per known neighbour. So the program takes time, and the tables and take space. Line L8 takes time. The refinement and the fairing depend on the size of the final patch, which depends on and , not on alone. Each round of lines L9 and L10 takes about time plus the flips. The fairing is a sparse linear system with unknowns. The code uses Gauss-Seidel sweeps, and a sparse direct or conjugate gradient solver is faster for large patches.
Properties
- No new vertices in the first step. The program uses only loop vertices, so it cannot make a patch with a better shape than a triangulation of the loop allows. The refinement adds the inner vertices.
- Not always embedded. Nothing stops the patch from crossing itself or the mesh. Deciding whether a loop in space has a triangulation with its own vertices that does not cross itself is NP-complete, so a cubic program cannot promise it.
- Deterministic. Ties go to the smallest apex .
- Exact core. With a monotone exact weight on rational coordinates, the triangulation step is exact. With Liepa's weight, angles are floating point values.
Variants and improvements
- Other weights. The total area alone, the sum of the squared areas, the largest angle alone, or the sum of the dihedral angles. Sum and max weights per triangle keep the program exact. Barequet and Sharir weigh the triangles for long and thin gaps in CAD meshes.
- Smoother fairing. Liepa fairs with umbrella operators of the mesh. A Laplace equation gives a membrane that meets the mesh with a crease. A bi-Laplace equation also matches the normals at the loop and gives a thin plate. The cotangent Laplacian and implicit fairing give weights that depend less on the triangle shapes.
- Remeshing in place of the splits. Run isotropic remeshing on the patch with a target edge length taken from the mesh.
- Islands and multiple loops. The program fills one loop. Holes with islands need a bridge between the loops first, or a method of another type.
- Search for embedded patches. Some later methods add the test for crossing triangles into the search, at a higher cost.
When to use it
Use it for holes of small and medium size in a scanned or edited mesh, where the patch should follow the surface around the hole and where the rest of the mesh should not change. It is the standard surface-based method, and it keeps every triangle of the input. For very large or very complex holes, for holes with islands, and for a model with many defects at once, a volumetric mesh repair or a reconstruction gives a closed result more reliably, at the cost of a new surface everywhere.
Pitfalls
- Holes that are not holes. Each border loop of the mesh is a candidate, including the rim of a cup and the outline of an open sheet. Select the loops to fill, for example by their length.
- Loops that touch themselves. If a vertex appears twice in a loop, as when two holes meet at one vertex, a patch triangle can join the two copies, which gives a degenerate triangle or a non-manifold vertex. Split such loops first.
- Chords that already exist. A diagonal of the loop can already be an edge of the mesh, for example across a narrow neck. A patch triangle on it gives that edge three faces. Test the chords against the edges of the mesh and give such triangles an infinite weight.
- Crossing patches. For a loop with a strong twist, the best triangulation can cross itself. Test the result with a mesh self-intersection check.
- Cubic time. A loop of 2000 vertices takes about steps. Cut very long loops into pieces first.
- Wrong orientation. The loop must be listed against the mesh faces. A loop in the wrong direction gives a patch that faces inward.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/liepa-hole-filling/. The authors are listed in prov/4HZ1HE.jsonl.
"""Fill a hole of a triangle mesh in the way of Liepa (SGP 2003).
1. A dynamic program over the border loop finds the triangulation of the loop
of least weight. The weight of a triangle is a pair: the largest dihedral
angle with its neighbours, then its area. Pairs add by (max, +) and are
compared in lexicographic order.
2. Refinement splits large patch triangles at their centroids and flips patch
edges that are not locally Delaunay, so that the patch gets the density of
the mesh around it.
3. Fairing moves the new vertices to the solution of the uniform Laplace
equation, with the loop fixed (a membrane patch).
The dynamic program is generic: `triangulate_loop` takes any weight and any
monotone way to add weights, so it can be tested against exhaustive search.
"""
from math import acos, sqrt
from typing import Callable, NamedTuple, Optional, Sequence, TypeVar
Vec = tuple[float, ...]
W = TypeVar("W")
# ---- vector helpers ----
def sub(a: Sequence[float], b: Sequence[float]) -> Vec:
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def cross(a: Sequence[float], b: Sequence[float]) -> 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 dot(a: Sequence[float], b: Sequence[float]) -> float:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def normal(p: Sequence[Sequence[float]], a: int, b: int, c: int) -> Vec:
"""The normal of the oriented triangle (a, b, c), twice its area long."""
return cross(sub(p[b], p[a]), sub(p[c], p[a]))
def area(p: Sequence[Sequence[float]], a: int, b: int, c: int) -> float:
n = normal(p, a, b, c)
return sqrt(dot(n, n)) / 2
def dihedral(p: Sequence[Sequence[float]], t: tuple[int, int, int], u: tuple[int, int, int]) -> float:
"""The angle between the normals of two oriented triangles; 0 when they are flat."""
n1, n2 = normal(p, *t), normal(p, *u)
l1, l2 = dot(n1, n1), dot(n2, n2)
if l1 == 0 or l2 == 0:
return acos(-1.0) # a degenerate triangle counts as the worst fold
c = dot(n1, n2) / sqrt(l1 * l2)
return acos(max(-1.0, min(1.0, c)))
# ---- the dynamic program ----
class LoopTriangulation(NamedTuple):
weight: object # the weight of the whole triangulation
triangles: list[tuple[int, int, int]] # positions in the loop, (i, m, k) with i < m < k
def triangulate_loop(
n: int,
omega: Callable[[int, int, int, Optional[int], Optional[int]], W],
plus: Callable[[W, W], W],
zero: W,
) -> LoopTriangulation:
"""Least weight triangulation of the loop 0, 1, ..., n - 1 by dynamic programming.
omega(i, m, k, a, b) is the weight of the triangle (i, m, k). The values a and b
are the apex of the triangle already chosen on the edge (i, m) and on the edge
(m, k), or None when that edge is a loop edge. The weight of a triangulation is
the plus of its triangle weights; the result is optimal when plus is monotone.
"""
if n < 3:
raise ValueError("a loop needs at least 3 vertices")
cost: list[list[Optional[W]]] = [[None] * n for _ in range(n)]
apex = [[-1] * n for _ in range(n)]
for i in range(n - 1): # @line L1
cost[i][i + 1] = zero
for j in range(2, n): # @line L2
for i in range(n - j): # @line L3
k = i + j # @line L4
for m in range(i + 1, k): # @line L5
a = apex[i][m] if m > i + 1 else None
b = apex[m][k] if k > m + 1 else None
cand = plus(plus(cost[i][m], cost[m][k]), omega(i, m, k, a, b)) # @line L6
if cost[i][k] is None or cand < cost[i][k]: # @line L7
cost[i][k], apex[i][k] = cand, m
tris: list[tuple[int, int, int]] = []
stack = [(0, n - 1)]
while stack: # @line L8
i, k = stack.pop()
if k - i >= 2:
m = apex[i][k]
tris.append((i, m, k))
stack.append((i, m))
stack.append((m, k))
return LoopTriangulation(cost[0][n - 1], sorted(tris))
# ---- holes of a mesh ----
def border_loops(faces: Sequence[Sequence[int]]) -> list[list[int]]:
"""The border loops of an oriented manifold mesh, each in the order a patch must walk it.
A face that uses the border edge a -> b leaves the patch to use b -> a, so each loop
is listed along the reversed border edges. Each border vertex must have one
border edge in and one out.
"""
directed = set()
for f in faces:
for i in range(len(f)):
directed.add((f[i], f[(i + 1) % len(f)]))
nxt: dict[int, int] = {}
for a, b in directed:
if (b, a) not in directed:
if b in nxt:
raise ValueError("a vertex with two border loops")
nxt[b] = a # the patch walks b -> a
loops, seen = [], set()
for s in sorted(nxt):
if s in seen:
continue
loop, v = [], s
while v not in seen:
seen.add(v)
loop.append(v)
v = nxt[v]
loops.append(loop)
return loops
def outside_apex(faces: Sequence[Sequence[int]], loop: Sequence[int]) -> list[Optional[int]]:
"""For each loop edge (loop[i], loop[i + 1]), the third vertex of the mesh triangle on it."""
third: dict[tuple[int, int], int] = {}
for f in faces:
if len(f) == 3:
for i in range(3):
third[(f[i], f[(i + 1) % 3])] = f[(i + 2) % 3]
n = len(loop)
return [third.get((loop[(i + 1) % n], loop[i])) for i in range(n)]
def liepa_triangulation(points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]],
loop: Sequence[int]) -> list[tuple[int, int, int]]:
"""Triangles over the mesh vertices that close the loop, with Liepa's weight."""
n = len(loop)
out = outside_apex(faces, loop)
def omega(i: int, m: int, k: int, a: Optional[int], b: Optional[int]) -> tuple[float, float]:
t = (loop[i], loop[m], loop[k])
worst = 0.0
# the neighbour across (i, m), then across (m, k), and across (k, i) at the top
if a is not None:
worst = max(worst, dihedral(points, t, (loop[i], loop[a], loop[m])))
elif out[i] is not None:
worst = max(worst, dihedral(points, t, (loop[m], loop[i], out[i])))
if b is not None:
worst = max(worst, dihedral(points, t, (loop[m], loop[b], loop[k])))
elif out[m] is not None:
worst = max(worst, dihedral(points, t, (loop[k], loop[m], out[m])))
if i == 0 and k == n - 1 and out[n - 1] is not None:
worst = max(worst, dihedral(points, t, (loop[i], loop[k], out[n - 1])))
return (worst, area(points, *t))
def plus(x: tuple[float, float], y: tuple[float, float]) -> tuple[float, float]:
return (max(x[0], y[0]), x[1] + y[1])
r = triangulate_loop(n, omega, plus, (0.0, 0.0))
return [(loop[i], loop[m], loop[k]) for i, m, k in r.triangles]
# ---- refinement and fairing ----
def edge_scale(points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]]) -> dict[int, float]:
"""The mean length of the mesh edges at each vertex (Liepa's sigma)."""
total: dict[int, float] = {}
count: dict[int, int] = {}
seen = set()
for f in faces:
for i in range(len(f)):
u, v = f[i], f[(i + 1) % len(f)]
e = (min(u, v), max(u, v))
if e in seen:
continue
seen.add(e)
d = sub(points[u], points[v])
ln = sqrt(dot(d, d))
for x in e:
total[x] = total.get(x, 0.0) + ln
count[x] = count.get(x, 0) + 1
return {x: total[x] / count[x] for x in total}
def _angle_at(p: Sequence[Sequence[float]], o: int, a: int, b: int) -> float:
u, v = sub(p[a], p[o]), sub(p[b], p[o])
lu, lv = dot(u, u), dot(v, v)
if lu == 0 or lv == 0:
return 0.0
return acos(max(-1.0, min(1.0, dot(u, v) / sqrt(lu * lv))))
def relax(points: Sequence[Sequence[float]], patch: list[tuple[int, int, int]], fixed: set[tuple[int, int]]) -> int:
"""Flip patch edges whose two opposite angles sum to more than pi. Returns the number of flips."""
flips = 0
changed = True
while changed and flips < 100 * len(patch) + 100:
changed = False
where: dict[tuple[int, int], int] = {}
for idx, t in enumerate(patch):
for i in range(3):
where[(t[i], t[(i + 1) % 3])] = idx
undirected = {(min(a, b), max(a, b)) for a, b in where}
for (a, b), f in list(where.items()):
g = where.get((b, a))
if g is None or a > b or (a, b) in fixed or (b, a) in fixed:
continue
c = next(x for x in patch[f] if x not in (a, b))
d = next(x for x in patch[g] if x not in (a, b))
if c == d or (min(c, d), max(c, d)) in undirected:
continue
if _angle_at(points, c, a, b) + _angle_at(points, d, a, b) > acos(-1.0) + 1e-12:
patch[f], patch[g] = (c, a, d), (d, b, c) # a -> b is replaced by d -> c
flips += 1
changed = True
break
return flips
class Fill(NamedTuple):
points: list[Vec] # the old points, then the new ones
patch: list[tuple[int, int, int]] # the new triangles
coarse: list[tuple[int, int, int]] # the triangles of the dynamic program
def fill_hole(points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]], loop: Sequence[int],
alpha: float = sqrt(2.0), fair: bool = True, max_rounds: int = 50) -> Fill:
"""Triangulate, refine and fair the patch that closes one border loop."""
pts: list[Vec] = [tuple(float(x) for x in p) for p in points]
coarse = liepa_triangulation(pts, faces, loop)
patch = list(coarse)
sigma = edge_scale(pts, faces)
n = len(loop)
fixed = {(loop[i], loop[(i + 1) % n]) for i in range(n)}
for v in loop:
sigma.setdefault(v, 0.0)
for _ in range(max_rounds): # @line L9
split = False
new_patch = []
for a, b, c in patch:
ctr = tuple((pts[a][j] + pts[b][j] + pts[c][j]) / 3 for j in range(3))
sc = (sigma[a] + sigma[b] + sigma[c]) / 3
ok = True
for v in (a, b, c):
d = sub(ctr, pts[v])
ln = alpha * sqrt(dot(d, d))
if ln <= sc or ln <= sigma[v]:
ok = False
if ok:
k = len(pts)
pts.append(ctr)
sigma[k] = sc
new_patch += [(a, b, k), (b, c, k), (c, a, k)]
split = True
else:
new_patch.append((a, b, c))
patch = new_patch
relax(pts, patch, fixed) # @line L10
if not split:
break
if fair:
fair_patch(pts, patch, set(range(len(points)))) # @line L11
return Fill(pts, patch, coarse)
def fair_patch(pts: list[Vec], patch: Sequence[tuple[int, int, int]], fixed: set[int],
tol: float = 1e-13, max_sweeps: int = 100000) -> None:
"""Move each free vertex of the patch to the mean of its neighbours (Gauss-Seidel)."""
nb: dict[int, set[int]] = {}
for t in patch:
for i in range(3):
for j in range(3):
if i != j:
nb.setdefault(t[i], set()).add(t[j])
free = sorted(v for v in nb if v not in fixed)
for _ in range(max_sweeps):
delta = 0.0
for v in free:
ns = nb[v]
new = tuple(sum(pts[u][j] for u in ns) / len(ns) for j in range(3))
d = sub(new, pts[v])
delta = max(delta, abs(d[0]), abs(d[1]), abs(d[2]))
pts[v] = new
if delta < tol:
break
def fill_all_holes(points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]],
keep: Callable[[list[int]], bool] = lambda loop: True) -> tuple[list[Vec], list[tuple[int, ...]]]:
"""Fill every border loop for which keep(loop) is true, one after another."""
pts: list[Vec] = [tuple(float(x) for x in p) for p in points]
out: list[tuple[int, ...]] = [tuple(f) for f in faces]
for loop in border_loops(faces):
if keep(loop):
r = fill_hole(pts, out, loop)
pts = r.points
out += r.patch
return pts, out
test_liepa_hole_filling.py 246 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/liepa-hole-filling/. The authors are listed in prov/4HZ1HE.jsonl.
import random
from math import acos, comb
from liepa_hole_filling import (border_loops, dihedral, area, fill_hole, liepa_triangulation, normal,
outside_apex, triangulate_loop, dot)
# ---- brute force: every triangulation of the loop 0, ..., n - 1 ----
def all_triangulations(i, k, memo=None):
if memo is None:
memo = {}
if k - i < 2:
return [[]]
if (i, k) not in memo:
out = []
for m in range(i + 1, k):
for left in all_triangulations(i, m, memo):
for right in all_triangulations(m, k, memo):
out.append(left + right + [(i, m, k)])
memo[(i, k)] = out
return memo[(i, k)]
def catalan(n):
return comb(2 * n, n) // (n + 1)
def random_loop(rng, n, r=6):
return [(rng.randint(-r, r), rng.randint(-r, r), rng.randint(-r, r)) for _ in range(n)]
def sq_double_area(p, t):
nv = normal(p, *t)
return dot(nv, nv)
# ---- the dynamic program against exhaustive search ----
def test_number_of_triangulations_is_catalan():
for n in range(3, 10):
assert len(all_triangulations(0, n - 1)) == catalan(n - 2)
def test_sum_weight_is_optimal():
rng = random.Random(2003)
for _ in range(250):
n = rng.randint(3, 8)
p = random_loop(rng, n)
r = triangulate_loop(n, lambda i, m, k, a, b: sq_double_area(p, (i, m, k)), lambda x, y: x + y, 0)
best = min(sum(sq_double_area(p, t) for t in T) for T in all_triangulations(0, n - 1))
assert r.weight == best
assert sum(sq_double_area(p, t) for t in r.triangles) == best
assert len(r.triangles) == n - 2
def test_table_weights_sum_and_max_are_optimal():
rng = random.Random(1995)
for _ in range(250):
n = rng.randint(3, 8)
w = {(i, m, k): rng.randint(0, 50) for i in range(n) for m in range(i + 1, n) for k in range(m + 1, n)}
om = lambda i, m, k, a, b: w[(i, m, k)]
for plus, agg in ((lambda x, y: x + y, sum), (max, max)):
r = triangulate_loop(n, om, plus, 0)
best = min(agg(w[t] for t in T) for T in all_triangulations(0, n - 1))
assert r.weight == best == agg(w[t] for t in r.triangles)
def test_lexicographic_pair_is_not_decomposable():
"""(max, +) in lexicographic order is not monotone, so the program can miss the optimum."""
rng = random.Random(7)
strict = 0
for _ in range(400):
n = rng.randint(4, 8)
w = {(i, m, k): (rng.randint(0, 3), rng.randint(0, 9))
for i in range(n) for m in range(i + 1, n) for k in range(m + 1, n)}
plus = lambda x, y: (max(x[0], y[0]), x[1] + y[1])
def total(T):
return (max(w[t][0] for t in T), sum(w[t][1] for t in T))
r = triangulate_loop(n, lambda i, m, k, a, b: w[(i, m, k)], plus, (0, 0))
best = min(total(T) for T in all_triangulations(0, n - 1))
assert r.weight == total(r.triangles)
assert r.weight >= best
strict += r.weight > best
assert strict > 0
def test_lexicographic_counterexample_of_the_proof():
w = {t: (9, 0) for t in [(i, m, k) for i in range(5) for m in range(i + 1, 5) for k in range(m + 1, 5)]}
w[(0, 1, 4)] = (5, 0)
w[(1, 2, 4)], w[(2, 3, 4)] = (1, 10), (0, 0)
w[(1, 2, 3)], w[(1, 3, 4)] = (2, 0), (0, 0)
plus = lambda x, y: (max(x[0], y[0]), x[1] + y[1])
r = triangulate_loop(5, lambda i, m, k, a, b: w[(i, m, k)], plus, (0, 0))
assert r.weight == (5, 10) and r.triangles == [(0, 1, 4), (1, 2, 4), (2, 3, 4)]
assert (5, 0) == plus(plus(w[(0, 1, 4)], w[(1, 2, 3)]), w[(1, 3, 4)])
def liepa_true_weight(p, loop, out, T):
"""The weight of a full triangulation: the largest dihedral angle over all adjacent pairs, then the area."""
tri = [(loop[i], loop[m], loop[k]) for i, m, k in T]
where = {}
for t in tri:
for j in range(3):
where[(t[j], t[(j + 1) % 3])] = t
n = len(loop)
for i in range(n):
if out[i] is not None:
where[(loop[(i + 1) % n], loop[i])] = (loop[(i + 1) % n], loop[i], out[i])
worst = 0.0
for t in tri:
for j in range(3):
u = where.get((t[(j + 1) % 3], t[j]))
if u is not None:
worst = max(worst, dihedral(p, t, u))
return (worst, sum(area(p, *t) for t in tri))
def test_liepa_weight_against_exhaustive():
rng = random.Random(42)
for _ in range(120):
n = rng.randint(3, 7)
loop_pts = random_loop(rng, n)
# a ring of mesh triangles around the loop, with apexes pushed outward
pts = list(loop_pts)
faces = []
for i in range(n):
a, b = loop_pts[i], loop_pts[(i + 1) % n]
pts.append(tuple(2 * (a[j] + b[j]) + rng.randint(-2, 2) for j in range(3)))
faces.append((i + 1 if i + 1 < n else 0, i, n + i))
loop = list(range(n))
out = outside_apex(faces, loop)
assert out == [n + i for i in range(n)]
got = liepa_triangulation(pts, faces, loop)
pos = {v: i for i, v in enumerate(loop)}
T = sorted(tuple(sorted(pos[v] for v in t)) for t in got)
mine = liepa_true_weight(pts, loop, out, T)
best = min(liepa_true_weight(pts, loop, out, S) for S in all_triangulations(0, n - 1))
assert mine >= (best[0] - 1e-12, best[1] - 1e-9)
assert len(got) == n - 2
# ---- the page example ----
def test_page_example_skew_quad():
p = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 1)]
r = triangulate_loop(4, lambda i, m, k, a, b: (0.0, area(p, i, m, k)),
lambda x, y: (max(x[0], y[0]), x[1] + y[1]), (0.0, 0.0))
assert r.triangles == [(0, 1, 2), (0, 2, 3)]
assert abs(r.weight[1] - (0.5 + 3 ** 0.5 / 2)) < 1e-12
def test_page_example_dihedral_choice():
# the skew quad as a hole in a folded sheet: the angle term overrules the area term
pts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 1),
(0.5, -1, -6), (2, 0.5, -1), (0.5, 2, 0.5), (-1, 0.5, 0.5)]
faces = [(1, 0, 4), (2, 1, 5), (3, 2, 6), (0, 3, 7)]
loop = [0, 1, 2, 3]
assert outside_apex(faces, loop) == [4, 5, 6, 7]
got = liepa_triangulation(pts, faces, loop)
assert got == [(0, 1, 3), (1, 2, 3)]
out = outside_apex(faces, loop)
w13 = liepa_true_weight(pts, loop, out, [(0, 1, 3), (1, 2, 3)])
w02 = liepa_true_weight(pts, loop, out, [(0, 1, 2), (0, 2, 3)])
assert abs(w13[0] - acos(0.5)) < 1e-12 and abs(w13[1] - 2 ** 0.5) < 1e-12
assert abs(w02[0] - acos(1 / 37 ** 0.5)) < 1e-12 and w02[1] < w13[1]
# ---- filling holes in meshes ----
def grid(n):
pts = [(x, y, 0) for y in range(n + 1) for x in range(n + 1)]
faces = []
for y in range(n):
for x in range(n):
a = y * (n + 1) + x
faces += [(a, a + 1, a + n + 2), (a, a + n + 2, a + n + 1)]
return pts, faces
def directed_ok(faces):
seen = set()
for f in faces:
for i in range(3):
e = (f[i], f[(i + 1) % 3])
if e in seen:
return False
seen.add(e)
return True
def test_border_loops_of_a_disk():
pts, faces = grid(2)
loops = border_loops(faces)
assert len(loops) == 1 and len(loops[0]) == 8
# the patch walks the border against the faces: 0 -> 3 is the reverse of the face edge 3 -> 0
assert loops[0][:2] == [0, 3]
def test_fill_planar_hole_in_grid():
pts, faces = grid(6)
hole = {(x, y) for x in range(2, 4) for y in range(1, 5)}
kept = [f for idx, f in enumerate(faces) if ((idx // 2) % 6, (idx // 2) // 6) not in hole]
loops = border_loops(kept)
assert len(loops) == 2
inner = min(loops, key=len)
assert len(inner) == 12
r = fill_hole(pts, kept, inner)
allf = kept + r.patch
assert directed_ok(allf)
assert len(border_loops(allf)) == 1
assert len(r.coarse) == len(inner) - 2
assert len(r.points) > len(pts) # the refinement added vertices
for q in r.points[len(pts):]:
assert abs(q[2]) < 1e-9 # the membrane of a flat loop is flat
total = sum(area(r.points, *t) for t in r.patch)
assert abs(total - 8.0) < 1e-9 # the patch covers the 2 x 4 hole exactly once
def test_fill_open_box_gives_closed_cube():
pts = [(x, y, z) for z in (0, 1) for y in (0, 1) for x in (0, 1)]
quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
faces = []
for a, b, c, d in quads[1:]: # the bottom face is missing
faces += [(a, b, c), (a, c, d)]
loops = border_loops(faces)
assert len(loops) == 1 and sorted(loops[0]) == [0, 1, 2, 3]
r = fill_hole(pts, faces, loops[0])
allf = faces + r.patch
assert directed_ok(allf) and border_loops(allf) == []
vol6 = 0.0
for a, b, c in allf:
P, Q, R = r.points[a], r.points[b], r.points[c]
vol6 += dot(P, (Q[1] * R[2] - Q[2] * R[1], Q[2] * R[0] - Q[0] * R[2], Q[0] * R[1] - Q[1] * R[0]))
assert abs(vol6 - 6.0) < 1e-9
# the coarse patch is flat: the dihedral angle with the side walls is 90 degrees for both diagonals,
# and between its two triangles it is 0
assert len(r.coarse) == 2
History
Klincsek in 1980 and Gilbert in 1979 found the cubic dynamic program for the triangulation of least weight of a polygon. In 1995 Barequet and Sharir used it in space, to close the gaps between the faces of CAD models. In 2003 Liepa combined it with a weight that puts the dihedral angle first, and with refinement and fairing, so that the patch blends into the mesh around it. His method became the usual surface-based hole filler of mesh processing.
References
- Peter Liepa, Filling holes in meshes, Eurographics Symposium on Geometry Processing, 2003, 200 to 206, the weight of a triangulation (largest dihedral angle, then area), its dynamic program, and the refinement and fairing of the patch
- Gill Barequet and Micha Sharir, Filling gaps in the boundary of a polyhedron, Computer Aided Geometric Design 12(2), 1995, 207 to 229, the triangulation of a gap loop of least weight by dynamic programming in cubic time
- Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 8, Model Repair (the hole filling of Liepa as a surface-based repair method)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 4HZ1HE Edit this page History Report an error Markdown