Algorithmadvanced
Angle-based flattening
Also called ABF, ABF++.
Sheffer and de Sturler's parameterization that solves for the planar angles of all triangles closest to the 3D angles under validity constraints, then lays out the mesh.
- Solves
- Mesh parameterization
- Time
- O(n) layoutO(n^3) per_iterationO(n^(3/2)) per_iteration_nested_dissection
- Space
- O(n^2) extraO(n log n) nested_dissection
- Where
- k = the number of iterations; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alla Sheffer, Eric de Sturler, Bruno Lévy, Maxim Mogilnitsky, Alexander Bogomyakov, 2001
Angle-based flattening, ABF, flattens a triangle mesh with the topology of a disk by solving for angles instead of positions. The unknowns are the planar angles of all triangle corners. The method finds the angles that are closest to the angles of the 3D mesh, in a relative least squares sense, among all angle sets that are the angles of some flat mesh. Three kinds of constraints say when that is so: the angles of a triangle add up to , the angles around an inner vertex add up to , and a wheel condition makes the edge lengths from the law of sines agree around each inner vertex. With these angles the flat mesh is built one triangle at a time. Every triangle of the result is counterclockwise and the map is one to one near every inner vertex, which least squares conformal maps do not guarantee. The boundary is free. The price is a nonlinear problem, solved by a Newton type iteration with Lagrange multipliers. It solves the mesh parameterization problem with low angle distortion.
In plain words
A flat map of a curved surface must change some angles. ABF decides first what every angle of every small triangle should be in the flat map, and only then draws the triangles.
It wants each flat angle close to the angle on the surface. But it cannot pick them freely. The three angles of a triangle must make a half turn. The angles around a point inside must make a full turn. And the triangles around a point must fit together, so that the sides that meet have the same length.
Among all choices that obey these rules, ABF takes the one with the smallest total change. Then it puts down one triangle, and lays each next triangle along a side that is already drawn.
The problem
The input is a triangle mesh with the topology of a disk, with faces oriented so that the outward normal follows the right-hand rule. The output is a point for each vertex such that each triangle is mapped linearly, every triangle is counterclockwise, and the angles of the flat triangles are close to the angles of the 3D triangles.
The algorithm
Let be the 3D angle of the corner . At an inner vertex, scale the of its corners so that they add up to ; these are the target angles. The unknowns are the planar angles , and the objective is
For a corner at in a triangle , let and be the corners of after and before . The constraints are
- triangle: for each triangle,
- vertex: for each inner vertex,
- wheel: for each inner vertex.
With for all constraints and its Jacobian , the KKT conditions are and . Each iteration solves the linearized system, a quadratic programming step with equality constraints. The code of this page takes , the Hessian of , and drops the second derivatives of the wheel constraint. Then is diagonal, and eliminating leaves a system in alone, .
ABF(M)- 1
β ← the 3D corner angles, scaled to 2π at each inner vertex - 2
α ← β - 3
repeat - 4
evaluate the constraints C(α), the gradient ∇F and the Jacobian J - 5
solve (J H⁻¹ Jᵀ) λ = C − J H⁻¹ ∇F - 6
δ ← −H⁻¹ (∇F + Jᵀ λ); α ← α + δ - 7
until |C(α)| ≤ ε and |δ| ≤ ε LAYOUT(M, α)- 8
place the first triangle: its first edge with its 3D length on the x axis, the third corner by α - 9
in breadth-first order, place each next triangle across an edge already placed, by the law of sines - 10
return x
In L9, the third corner of the triangle is at , where is the rotation by .
Degenerate cases. A 3D triangle with an angle of 0 or gives a target of 0 or a wheel term , so it is rejected. The iteration does not keep in by itself; Sheffer and de Sturler add the bounds , and the code of this page checks them at the end and raises an error. A mesh with no inner vertex has only triangle constraints, and the result is the target angles corrected to sum per triangle; the layout is then free of gaps by construction. A mesh with a hole or a handle must be cut into a disk first.
Example
Take the pyramid with base corners , , , (vertices 0 to 3), apex (vertex 4), and the four side triangles , , , . The apex is the only inner vertex.
| step | value |
|---|---|
| L1, 3D angles | at each base corner, at the apex |
| L1, scaling | the apex angles add up to , so they are scaled to each |
| L4, first pass | each triangle sum is , so for each triangle constraint; the vertex and wheel constraints are 0 |
| L5 to L6 | the base angles go to , the apex angles stay at |
| L7 | the second pass finds and and stops |
| objective | |
| L8 to L10 | , , , , |
The result is a square of side 2 split by its diagonals into four right isosceles triangles. The angle at the apex had to grow, and ABF spread the change equally over the base angles.
When the arithmetic is floating point. The angles come from an iteration with square roots, sines and logarithms, so the constraints hold only to rounding, about in the tests. The triangles then do not close exactly, and the position of a vertex depends slightly on the triangle that places it. The code measures this gap, below on bumps with up to 72 triangles. The terms and their derivatives grow without bound when an angle comes near 0 or , and for near loses relative accuracy by catastrophic cancellation, because the float is subtracted from a rounded . Whether a triangle of the layout is flipped is the sign of ORIENT2D, the orientation test, on the computed points; the tests evaluate it exactly on the floats converted to rationals, and exact predicates do the same faster. This is the robustness problem of geometry.
Correctness
If the angles meet the three constraints exactly and lie in , each triangle is fixed up to a similarity by its angles. The law of sines gives the ratio of two edges at an inner vertex in each triangle, and the wheel constraint says that the product of these ratios around the vertex is 1, so the edge lengths agree. The vertex constraint says that the turns around the vertex add up to a full turn, so the triangles close. The disk minus its inner vertices has loops around the inner vertices as generators of its fundamental group, so the layout is the same along any path. Each triangle is placed with a positive turn, so it is counterclockwise, and the triangles around an inner vertex cover a full turn once. A planar mesh meets the constraints with its own angles and objective 0, so it is mapped to a similar copy. The convergence of the iteration is not proved, only measured. The full proof is below.
Proof: Angles that satisfy the ABF constraints give a consistent flat mesh with every triangle counterclockwise and every inner vertex locally one to onefull
Setting. is a triangle mesh with the topology of a disk, with faces oriented so that the outward normal follows the right-hand rule. For each triangle we are given angles . For a corner of at , let and be the corners of that follow and precede in the order of . The ABF constraints are:
- (triangle) for every triangle,
- (vertex) for every inner vertex ,
- (wheel) for every inner vertex , which is the log form used in the code.
The layout fixes the first edge of the first triangle and then places each new triangle across an edge that is already placed, by the law of sines.
Claim. If the angles satisfy the three constraints exactly, then:
- There are edge lengths , unique up to one common factor, such that each triangle with the lengths of its edges has the given angles.
- The layout gives the same position to a vertex whichever triangle places it, so it is a well defined piecewise linear map .
- Every triangle of is counterclockwise, ORIENT2D , and is one to one on the star of every inner vertex.
- If is a planar mesh with counterclockwise triangles, its own angles minimize the objective with value 0, and the layout is a similarity of .
The layout need not be one to one globally: the claim says nothing about boundary vertices, and two far parts of the boundary can overlap.
Step 1 (a triangle from its angles). By the triangle constraint, each triangle has positive angles with sum , so a Euclidean triangle with these angles exists and is unique up to a similarity. By the law of sines, in the length of the edge opposite a corner is proportional to the sine of its angle.
Step 2 (lengths around an inner vertex). Let be an inner vertex with neighbours in the order of the faces, and , indices mod . In , and . By the law of sines in ,
Going once around multiplies the length of by the product of these ratios, which is 1 by the wheel constraint.
Step 3 (part 1). Give the first triangle a scale. Across each inner edge the neighbour triangle gets the scale that gives the shared edge the same length. This defines a scale for every triangle along every path in the dual graph, and the scale is well defined if it is the same along any two paths, that is, if the product of the ratios around every closed dual path is 1. A closed dual path is a closed curve in the disk that misses the vertices. The disk with the inner vertices removed has a fundamental group generated by small loops around the inner vertices, and the scale ratio along a path is a product of positive numbers, so it is a homomorphism to the commutative group , which is trivial on every generator by Step 2. So it is trivial, and the scales are well defined. Uniqueness up to one factor follows from the connectedness of the dual graph.
Step 4 (part 2). Now each triangle is a fixed Euclidean triangle, and two triangles that share an edge give it the same length. The layout places a triangle across a placed edge by a rotation and translation, which is unique once the edge is placed and the triangle is on the side given by its orientation. Developing along a dual path gives a rigid motion for each triangle, and the layout is well defined if the motion along any closed dual path is the identity. As in Step 3, it suffices to check a small loop around an inner vertex . Along that loop the image of stays fixed, because every triangle of the loop contains , and the image of the edge is turned by in turn, with lengths that agree by Step 2. The total turn is by the vertex constraint, so the motion is a rotation by about the image of , the identity. Rigid motions do not commute, but the motion along a loop is still a homomorphism from the fundamental group of the punctured disk, and it is trivial on the generators, so it is trivial. So a vertex placed by two triangles gets one position.
Step 5 (part 3). In the layout each triangle is placed with its corners in the order of the face and a turn of from the edge to the edge , so ORIENT2D. Around an inner vertex the triangles occupy the angular sectors at , which follow each other and add up to exactly . So they cover a small disk around once, and is one to one on the star of .
Step 6 (part 4). For a planar mesh with counterclockwise triangles, its own angles satisfy the triangle constraint, the vertex constraint (the angles around an inner vertex of a planar mesh fill a full turn), and the wheel constraint (the lengths of a real mesh agree, so the product of the length ratios of Step 2 is 1). The targets are the angles themselves, because the scaling at each inner vertex is by , so the objective is 0 there, its smallest value. By part 1 the layout has the edge lengths of times one factor and the same orientation, so it is a similarity of .
Termination. The layout visits each triangle once in breadth-first order over the dual graph and stops. The solver for the angles is an iteration with a fixed maximum number of steps, and it stops either with the constraints met to the tolerance or with an error. Its convergence is not proved here: the wheel constraint is not convex, and the iteration uses an approximate Hessian. The tests of the page measure it.
What the floating point result satisfies. The computed angles meet the constraints only up to rounding, so the triangles do not close exactly, and the position of a vertex depends slightly on the order. The code measures this as the largest distance between a vertex and the position that one of its triangles gives it, and the tests keep it below . Parts 2 and 3 hold for the exact angles; for the computed angles they hold up to that residual.
Complexity
There are unknowns and constraints, where is the number of inner vertices. One iteration builds in time. The system in has size ; dense elimination, as in the code of this page, takes time and space. Its sparsity follows the mesh, so a sparse factorization with nested dissection takes time. The 2005 version eliminates the triangle constraints as well and solves a system of size only. The number of iterations is small in practice: 7 to 9 on the bumps of the tests, 2 on the pyramid. The layout is one pass over the triangles, .
Properties
- Locally injective. With exact angles in , no triangle is flipped and every inner vertex has a one to one star. Boundary vertices are not constrained, so the boundary can overlap itself.
- Free boundary. No vertex is pinned; the scale comes from the first edge.
- Reproduction. A planar mesh is mapped to a similar copy, with .
- Angle based. The objective measures relative angle error. Areas are not controlled, as for any conformal method.
- Nonlinear. An iteration, not one solve. Each step is a sparse linear system.
Variants and improvements
- The fast version of Sheffer, Lévy, Mogilnitsky and Bogomyakov (2005). Their paper calls it ABF++. Its changes make ABF practical for much larger meshes than the first solver could handle. The Newton system is reduced by eliminating the angle unknowns and the triangle constraints, which leaves a much smaller sparse system. The positions are reconstructed from the angles by a least squares solve in the style of LSCM instead of the greedy layout, which spreads the small errors of the angles evenly. A hierarchical solver handles very large meshes.
- Linear ABF (Zayer, Lévy and Seidel 2007). Linearizes the wheel constraint about the target angles and solves one linear system, with results close to ABF.
- Bounds on the angles. The original method adds ; in practice the bound is rarely active and is often dropped.
- Boundary constraints. Adding the constraint that a boundary vertex has angle sum maps the mesh onto a region with a straight boundary there, which is used for charts with prescribed boundary shape.
When to use it
Use it for texture atlases and remeshing when angles matter and the charts are strongly curved, where LSCM gives large angle errors or folds. On the saddle-shaped wheel with six triangles of the LSCM page, where LSCM folds two triangles, ABF gives six equilateral triangles. Use the 2005 fast version for large meshes. If a map with no overlap at all is required, check the boundary or use a Tutte embedding as a start for a method with barriers. For a quick map of a nearly flat chart, LSCM is cheaper.
Pitfalls
- Dropping the wheel constraint. Without it, the triangle and vertex constraints are linear and easy, but the triangles around a vertex do not close. On the bumps of the tests the layout then has gaps from to , for edges of length about 1.
- The greedy layout. Laying out one triangle at a time adds up the rounding errors along long paths. The 2005 fast version uses a least squares reconstruction for this reason.
- Angles near 0 or . The wheel terms and their derivatives blow up. Remesh slivers first.
- Global overlap. Local injectivity does not exclude two far parts of the boundary landing on each other. Test it, for example with the Bentley-Ottmann algorithm on the boundary edges.
- Not converging. The iteration is not guaranteed to converge from the target angles. Check the constraint residual and the angle bounds before the layout.
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/angle-based-flattening/. The authors are listed in prov/1YT62Y.jsonl.
"""Angle-based flattening (Sheffer and de Sturler 2001).
The unknowns are the planar angles alpha of all triangle corners. The
objective is F(alpha) = sum (alpha - beta)^2 / beta^2, where beta are the 3D
angles, scaled at each inner vertex so that they add up to 2 pi. The
constraints are
triangle: the three angles of each triangle add up to pi,
vertex: the angles at each inner vertex add up to 2 pi,
wheel: at each inner vertex, sum log sin(next) - sum log sin(prev) = 0,
where next and prev are the corners after and before the vertex in each
triangle around it. The wheel condition makes the edge lengths given by the
law of sines agree around the vertex. The solver is a Lagrange-Newton
(sequential quadratic programming) iteration in which the Hessian is the
Hessian diag(2 / beta^2) of the objective only. The layout places the
triangles one by one across shared edges.
All of this is floating point. Faces are oriented so that the outward normal
follows the right-hand rule.
"""
import math
from collections import deque
from mp3geom import boundary_loop, directed_edges, solve
def corner_angles_3d(points, faces):
"""The angle of each corner, as a list indexed by 3 * face + corner."""
out = []
for f in faces:
for k in range(3):
p, a, b = (points[f[(k + j) % 3]] for j in range(3))
u = [float(a[i]) - float(p[i]) for i in range(len(p))]
v = [float(b[i]) - float(p[i]) for i in range(len(p))]
uv = sum(x * y for x, y in zip(u, v))
if len(p) == 2:
cr = abs(u[0] * v[1] - u[1] * v[0])
else:
cr = math.sqrt((u[1] * v[2] - u[2] * v[1]) ** 2 + (u[2] * v[0] - u[0] * v[2]) ** 2 + (u[0] * v[1] - u[1] * v[0]) ** 2)
out.append(math.atan2(cr, uv))
return out
def inner_vertices(faces):
bnd = set(boundary_loop(faces))
return sorted({v for f in faces for v in f} - bnd)
def corners_at(faces):
"""Map each vertex to the list of (face, corner) where it appears."""
at = {}
for i, f in enumerate(faces):
for k in range(3):
at.setdefault(f[k], []).append((i, k))
return at
def constraints(faces, alpha, inner, at, wheel=True):
"""The constraint values C and the rows of the Jacobian J, as sparse dicts."""
c, rows = [], []
for i in range(len(faces)):
c.append(alpha[3 * i] + alpha[3 * i + 1] + alpha[3 * i + 2] - math.pi)
rows.append({3 * i: 1.0, 3 * i + 1: 1.0, 3 * i + 2: 1.0})
for v in inner:
c.append(sum(alpha[3 * i + k] for i, k in at[v]) - 2 * math.pi)
rows.append({3 * i + k: 1.0 for i, k in at[v]})
if wheel:
for v in inner:
s, row = 0.0, {}
for i, k in at[v]:
nx, pv = 3 * i + (k + 1) % 3, 3 * i + (k + 2) % 3
s += math.log(math.sin(alpha[nx])) - math.log(math.sin(alpha[pv]))
row[nx] = row.get(nx, 0.0) + 1 / math.tan(alpha[nx])
row[pv] = row.get(pv, 0.0) - 1 / math.tan(alpha[pv])
c.append(s)
rows.append(row)
return c, rows
def target_angles(points, faces):
beta = corner_angles_3d(points, faces)
at = corners_at(faces)
for v in inner_vertices(faces):
total = sum(beta[3 * i + k] for i, k in at[v])
for i, k in at[v]:
beta[3 * i + k] *= 2 * math.pi / total
return beta
def objective(alpha, beta):
return sum((a - b) ** 2 / (b * b) for a, b in zip(alpha, beta))
def abf_angles(points, faces, tol=1e-13, max_iter=60, wheel=True):
"""Solve for the planar angles. Returns (alpha, number of iterations)."""
inner = inner_vertices(faces)
at = corners_at(faces)
beta = target_angles(points, faces) # @line L1
hinv = [b * b / 2 for b in beta]
alpha = list(beta) # @line L2
for it in range(1, max_iter + 1): # @line L3
c, rows = constraints(faces, alpha, inner, at, wheel) # @line L4
g = [2 * (a - b) / (b * b) for a, b in zip(alpha, beta)]
m = len(rows)
# Schur complement: (J H^-1 J^T) lam = C - J H^-1 g
s = [[0.0] * m for _ in range(m)]
rhs = [[c[r] - sum(val * hinv[j] * g[j] for j, val in rows[r].items())] for r in range(m)]
for r in range(m):
for q in range(r, m):
common = rows[r].keys() & rows[q].keys()
val = sum(rows[r][j] * hinv[j] * rows[q][j] for j in common)
s[r][q] = s[q][r] = val
lam = [x[0] for x in solve(s, rhs, tol=1e-300)] # @line L5
step = [-hinv[j] * g[j] for j in range(len(alpha))]
for r in range(m):
for j, val in rows[r].items():
step[j] -= hinv[j] * val * lam[r]
alpha = [a + d for a, d in zip(alpha, step)] # @line L6
if max(abs(x) for x in c) <= tol and max(abs(d) for d in step) <= tol: # @line L7
break
else:
raise ValueError("no convergence")
if not all(0 < a < math.pi for a in alpha):
raise ValueError("an angle is outside (0, pi)")
return alpha, it
def layout(points, faces, alpha):
"""Place the triangles across shared edges in breadth-first order. Returns {vertex: (x, y)}."""
de = directed_edges(faces)
f0 = faces[0]
p0, p1 = points[f0[0]], points[f0[1]]
length = math.sqrt(sum((float(a) - float(b)) ** 2 for a, b in zip(p0, p1)))
x = {f0[0]: (0.0, 0.0), f0[1]: (length, 0.0)} # @line L8
def third(face, k):
"""Position of the corner k+2 of the face from the corners k and k+1."""
a, b, c = (faces[face][(k + j) % 3] for j in range(3))
aa, ab, ac = (alpha[3 * face + (k + j) % 3] for j in range(3))
r = math.sin(ab) / math.sin(ac)
dx, dy = x[b][0] - x[a][0], x[b][1] - x[a][1]
co, si = math.cos(aa), math.sin(aa)
return c, (x[a][0] + r * (co * dx - si * dy), x[a][1] + r * (si * dx + co * dy))
c, pos = third(0, 0)
x[c] = pos
seen, queue = {0}, deque([0])
while queue: # @line L9
f = queue.popleft()
for k in range(3):
i, j = faces[f][k], faces[f][(k + 1) % 3]
if (j, i) in de:
g, kg = de[(j, i)]
if g not in seen:
seen.add(g)
c, pos = third(g, kg)
if c not in x:
x[c] = pos
queue.append(g)
return x # @line L10
def layout_residual(faces, alpha, x):
"""The largest distance between a placed vertex and where its triangle puts it."""
worst = 0.0
for f, tri in enumerate(faces):
for k in range(3):
a, b, c = (tri[(k + j) % 3] for j in range(3))
aa, ab, ac = (alpha[3 * f + (k + j) % 3] for j in range(3))
r = math.sin(ab) / math.sin(ac)
dx, dy = x[b][0] - x[a][0], x[b][1] - x[a][1]
co, si = math.cos(aa), math.sin(aa)
px, py = x[a][0] + r * (co * dx - si * dy), x[a][1] + r * (si * dx + co * dy)
worst = max(worst, math.hypot(px - x[c][0], py - x[c][1]))
return worst
def angle_based_flattening(points, faces):
alpha, _ = abf_angles(points, faces)
return layout(points, faces, alpha)
mp3geom.py 136 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mp3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes, used by the mp3 pages.
Points are tuples of int, fractions.Fraction or float. The predicates are
exact when the coordinates are int or Fraction. A mesh is a list of faces,
each a tuple of three vertex indices, oriented so that the outward normal
follows the right-hand rule (counterclockwise seen from outside).
"""
from fractions import Fraction
def sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def add(a, b):
return tuple(x + y for x, y in zip(a, b))
def scale(s, a):
return tuple(s * x for x in a)
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
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 orient2d(a, b, c):
"""Twice the signed area of triangle abc: > 0 if counterclockwise."""
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def orient3d(a, b, c, d):
"""((b - a) x (c - a)) . (d - a): > 0 if d is on the side of the normal of abc."""
return dot(cross(sub(b, a), sub(c, a)), sub(d, a))
def sign(x):
return (x > 0) - (x < 0)
def solve(a, b, tol=0.0):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a list of n rows of length n, b is a list of n rows of length m
(m right-hand sides). Entries are Fraction (exact) or float. Returns the
n rows of x. Raises ValueError if a pivot has absolute value <= tol, so
an exact singular matrix always raises when tol is 0.
"""
n = len(a)
m = len(b[0]) if n else 0
rows = [list(a[i]) + list(b[i]) for i in range(n)]
for col in range(n):
piv = max(range(col, n), key=lambda r: abs(rows[r][col]))
if abs(rows[piv][col]) <= tol:
raise ValueError("singular matrix")
rows[col], rows[piv] = rows[piv], rows[col]
pr = rows[col]
inv = 1 / pr[col] if isinstance(pr[col], float) else Fraction(1) / pr[col]
for r in range(col + 1, n):
f = rows[r][col]
if f:
f = f * inv
row = rows[r]
for k in range(col, n + m):
if pr[k]:
row[k] -= f * pr[k]
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
row = rows[i]
for k in range(m):
s = row[n + k]
for j in range(i + 1, n):
if row[j]:
s -= row[j] * x[j][k]
x[i][k] = s / row[i] if isinstance(s, float) or isinstance(row[i], float) else Fraction(s) / row[i]
return x
def directed_edges(faces):
"""Map each directed edge (i, j) to (face index, corner of i). Raises on a repeated directed edge."""
out = {}
for f, tri in enumerate(faces):
for k in range(3):
e = (tri[k], tri[(k + 1) % 3])
if e in out:
raise ValueError("directed edge %r used twice: not an oriented manifold" % (e,))
out[e] = (f, k)
return out
def neighbours(faces):
"""Map each vertex to the set of its neighbours."""
nb = {}
for tri in faces:
for k in range(3):
i, j = tri[k], tri[(k + 1) % 3]
nb.setdefault(i, set()).add(j)
nb.setdefault(j, set()).add(i)
return nb
def boundary_loop(faces):
"""The boundary of an oriented disk as one vertex loop, in the order of the face orientation."""
de = directed_edges(faces)
nxt = {}
for i, j in de:
if (j, i) not in de:
if i in nxt:
raise ValueError("boundary vertex %r is not manifold" % (i,))
nxt[i] = j
if not nxt:
raise ValueError("the mesh has no boundary")
start = min(nxt)
loop = [start]
while True:
v = nxt[loop[-1]]
if v == start:
break
loop.append(v)
if len(loop) != len(nxt):
raise ValueError("the boundary has more than one loop")
return loop
def euler_characteristic(faces):
verts = {v for tri in faces for v in tri}
edges = {frozenset((tri[k], tri[(k + 1) % 3])) for tri in faces for k in range(3)}
return len(verts) - len(edges) + len(faces)
test_angle_based_flattening.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/angle-based-flattening/. The authors are listed in prov/1YT62Y.jsonl.
import math
import random
from fractions import Fraction
from angle_based_flattening import (
abf_angles,
constraints,
corner_angles_3d,
corners_at,
inner_vertices,
layout,
layout_residual,
objective,
target_angles,
)
from mp3geom import orient2d
def grid(rng, nx, ny, jitter):
"""A planar grid with random diagonals and rational jitter, all triangles counterclockwise."""
while True:
pts = {}
for i in range(nx + 1):
for j in range(ny + 1):
dx = Fraction(rng.randint(-jitter, jitter), 4 * jitter + 1) if jitter else 0
dy = Fraction(rng.randint(-jitter, jitter), 4 * jitter + 1) if jitter else 0
pts[i * (ny + 1) + j] = (i + dx, j + dy)
faces = []
for i in range(nx):
for j in range(ny):
a, b, c, d = i * (ny + 1) + j, (i + 1) * (ny + 1) + j, (i + 1) * (ny + 1) + j + 1, i * (ny + 1) + j + 1
faces += [(a, b, c), (a, c, d)] if rng.random() < 0.5 else [(a, b, d), (b, c, d)]
if all(orient2d(pts[a], pts[b], pts[c]) > 0 for a, b, c in faces):
return pts, faces
def bump(rng, n, height=1.5):
pts, faces = grid(rng, n, n, 0)
out = {}
for v, (x, y) in pts.items():
r2 = (float(x) - n / 2) ** 2 + (float(y) - n / 2) ** 2
out[v] = (float(x), float(y), height * math.exp(-r2 / 2))
return out, faces
def exact_orient(x, f):
"""ORIENT2D of the computed float points, evaluated exactly."""
return orient2d(*([Fraction(c) for c in x[v]] for v in f))
def similarity_error(pts, x, v0, v1):
p = {v: complex(float(a), float(b)) for v, (a, b) in pts.items()}
q = {v: complex(*x[v]) for v in x}
a = (q[v1] - q[v0]) / (p[v1] - p[v0])
b = q[v0] - a * p[v0]
return max(abs(a * p[v] + b - q[v]) for v in p)
def test_flat_mesh_maps_to_a_similar_copy() -> None:
rng = random.Random(2001)
for _ in range(10):
pts, faces = grid(rng, rng.randint(1, 4), rng.randint(1, 4), 3)
alpha, _ = abf_angles(pts, faces)
x = layout(pts, faces, alpha)
assert similarity_error(pts, x, faces[0][0], faces[0][1]) < 1e-9
assert objective(alpha, target_angles(pts, faces)) < 1e-20
def test_constraints_layout_and_orientation_on_a_bump() -> None:
rng = random.Random(11)
for n, height in ((3, 1.0), (4, 1.5), (5, 2.5)):
pts, faces = bump(rng, n, height)
alpha, iters = abf_angles(pts, faces)
c, _ = constraints(faces, alpha, inner_vertices(faces), corners_at(faces))
assert max(abs(v) for v in c) < 1e-10
assert iters <= 20
x = layout(pts, faces, alpha)
assert layout_residual(faces, alpha, x) < 1e-9
assert all(exact_orient(x, f) > 0 for f in faces)
def test_without_the_wheel_condition_the_layout_does_not_close() -> None:
rng = random.Random(11)
pts, faces = bump(rng, 4, 1.5)
alpha, _ = abf_angles(pts, faces, wheel=False)
x = layout(pts, faces, alpha)
assert layout_residual(faces, alpha, x) > 1e-3
def test_objective_not_above_other_valid_flattenings() -> None:
# Measured, not proved: the angles of other valid flat meshes with the same
# connectivity satisfy the constraints, and ABF finds a lower objective.
rng = random.Random(23)
pts, faces = bump(rng, 4, 1.5)
beta = target_angles(pts, faces)
best = objective(abf_angles(pts, faces)[0], beta)
for _ in range(10):
flat, _ = grid(random.Random(rng.random()), 4, 4, 3)
flat_faces_ok = all(orient2d(flat[a], flat[b], flat[c]) > 0 for a, b, c in faces)
if not flat_faces_ok:
continue
other = corner_angles_3d(flat, faces)
assert best <= objective(other, beta) + 1e-12
proj = {v: (p[0], p[1]) for v, p in pts.items()}
assert best < objective(corner_angles_3d(proj, faces), beta)
def test_saddle_wheel_does_not_fold() -> None:
n, h = 6, 2.0
pts = {i: (math.cos(2 * math.pi * i / n), math.sin(2 * math.pi * i / n), h * (-1) ** i) for i in range(n)}
pts[n] = (0.0, 0.0, 0.0)
faces = [(i, (i + 1) % n, n) for i in range(n)]
alpha, _ = abf_angles(pts, faces)
assert all(abs(a - math.pi / 3) < 1e-12 for a in alpha)
x = layout(pts, faces, alpha)
assert all(exact_orient(x, f) > 0 for f in faces)
def test_example_of_the_page() -> None:
pts = {0: (-1, -1, 0), 1: (1, -1, 0), 2: (1, 1, 0), 3: (-1, 1, 0), 4: (0, 0, 1)}
faces = [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 0, 4)]
beta3 = corner_angles_3d(pts, faces)
assert abs(beta3[2] - math.acos(1 / 3)) < 1e-12
assert abs(beta3[0] - math.atan(math.sqrt(2))) < 1e-12
beta = target_angles(pts, faces)
assert abs(beta[2] - math.pi / 2) < 1e-12
alpha, iters = abf_angles(pts, faces)
assert iters == 2
for f in range(4):
assert abs(alpha[3 * f] - math.pi / 4) < 1e-12
assert abs(alpha[3 * f + 1] - math.pi / 4) < 1e-12
assert abs(alpha[3 * f + 2] - math.pi / 2) < 1e-12
b = math.atan(math.sqrt(2))
assert abs(objective(alpha, beta) - 8 * ((math.pi / 4 - b) / b) ** 2) < 1e-12
x = layout(pts, faces, alpha)
want = {0: (0, 0), 1: (2, 0), 2: (2, 2), 3: (0, 2), 4: (1, 1)}
for v, (u, w) in want.items():
assert abs(x[v][0] - u) < 1e-12 and abs(x[v][1] - w) < 1e-12
History
Alla Sheffer and Eric de Sturler introduced angle-based flattening in 2001 for meshing faceted surfaces in engineering, with the observation that a set of angles defines a valid flat mesh exactly when it satisfies the triangle, vertex and wheel conditions. The first solver was slow. In 2005 Sheffer, Bruno Lévy, Maxim Mogilnitsky and Alexander Bogomyakov published a fast version, which reduced the linear algebra, reconstructed the positions robustly and made the method one of the standard unwrapping methods. Zayer, Lévy and Seidel gave a linearized version in 2007.
References
- Alla Sheffer and Eric de Sturler, Parameterization of faceted surfaces for meshing using angle-based flattening, Engineering with Computers 17(3), 2001, 326 to 337, the angle objective, the triangle, vertex and wheel constraints, and the proof that angles that meet them define a valid flat mesh
- Alla Sheffer, Bruno Lévy, Maxim Mogilnitsky and Alexander Bogomyakov, ABF++, fast and robust angle based flattening, ACM Transactions on Graphics 24(2), 2005, 311 to 330, the reduction of the Newton system to a smaller one, the reconstruction of positions from angles by least squares, and the hierarchical solution
- Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 5, Parametrization (angle-based flattening among the conformal methods)
- Alla Sheffer, Emil Praun and Kenneth Rose, Mesh parameterization methods and their applications, Foundations and Trends in Computer Graphics and Vision 2(2), 2006, 105 to 171, the section on angle-based methods
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 1YT62Y Edit this page History Report an error Markdown