Algorithm Search⌘K

Algorithmresearch

Boundary first flattening

Also called BFF.

Sawhney and Crane's conformal flattening that first fixes boundary scale factors or angles, then extends them inside by harmonic functions, with a few linear solves.

Time
O(n^3) worstO(n^(3/2)) nested_dissectionO(n^2 + m) new_target
Space
O(n^2) extraO(n log n) nested_dissection
Where
m = the number of boundary vertices; n = the number of vertices
Properties
deterministicnot exactiterative
Origin
Rohan Sawhney, Keenan Crane, 2017

Boundary first flattening, BFF, computes a conformal flattening of a triangle mesh with the topology of a disk, and lets the user choose the shape of the boundary. A conformal map keeps angles and changes only the local scale, by a factor eue^{u}. On a smooth surface, the Cherrier formula says how uu changes the curvature of the boundary, so the user can give either the scale factors on the boundary or the turning angles of the boundary, and the other one follows from a linear solve. BFF builds the boundary curve first and then fills in the interior with a harmonic map. All the steps are linear, and they use one Laplace matrix, so a new boundary target costs only solves with a factored matrix. It solves the mesh parameterization problem.

In plain words

To flatten a curved patch without bending its small angles, each small piece may only grow or shrink. How much each piece grows is one number per point, and these numbers are tied to the curvature of the surface.

BFF uses this tie at the edge of the patch. You say either how much the edge should stretch, or how sharply the flat outline should turn at each edge point, for example to get a rectangle. The method computes the other one, draws the flat outline from the turns and the lengths, and closes it with the smallest change.

The inside is then filled the smoothest way that fits the outline, the way a soap film fills a wire loop.

The problem

The input is a triangle mesh MM with nn vertices, with the topology of a disk, whose triangles all have positive area and whose faces are oriented so that the outward normal follows the right-hand rule. The boundary is one loop b1,…,bmb_1, \dots, b_m, in the order of the face orientation. The input also has one of two targets:

  • Scale factors. A number ubu_b for each boundary vertex. The image of a boundary edge ijij should have the length e(ui+uj)/2 ℓije^{(u_i + u_j)/2}\, \ell_{ij}. With ub=0u_b = 0 the boundary keeps its lengths.
  • Turning angles. An angle k~b\tilde k_b for each boundary vertex, with ∑bk~b=2π\sum_b \tilde k_b = 2\pi. The image of the boundary should turn left by k~b\tilde k_b at bb. A polygon with pp corners has k~=2π/p\tilde k = 2\pi / p at its corners, or any other angles that add up to 2π2\pi, and 0 at the other boundary vertices.

The output is a point in the plane for each vertex. The map should be close to conformal and meet the target on the boundary.

The algorithm

The smooth relation. If a metric gg is changed to e2uge^{2u} g, the Gaussian curvature KK and the geodesic curvature κ\kappa of the boundary change as

K~=e−2u(K−Δu),κ~=e−u(κ+∂nu),\tilde K = e^{-2u}(K - \Delta u), \qquad \tilde \kappa = e^{-u}(\kappa + \partial_n u),

where Δ\Delta is the Laplace-Beltrami operator and ∂n\partial_n is the derivative along the outward normal. The second equation is the Cherrier formula. A flat image needs K~=0\tilde K = 0, that is Δu=K\Delta u = K inside. Given uu on the boundary, this Poisson problem fixes uu, and then ∂nu\partial_n u gives the new boundary curvature. Given the new boundary curvature, the same problem with Neumann data fixes uu up to a constant.

The discrete relation. Let Ωi=2π−∑θ\Omega_i = 2\pi - \sum \theta be the angle defect at an inner vertex ii, the discrete Gaussian curvature, and kb=π−∑θk_b = \pi - \sum \theta the turning angle at a boundary vertex bb, where ∑θ\sum \theta is the sum of the corner angles at the vertex. Let AA be the cotangent Laplacian with Aij=−12(cot⁡αij+cot⁡βij)A_{ij} = -\frac12 (\cot \alpha_{ij} + \cot \beta_{ij}) for an edge ijij and rows that add up to 0. BFF uses

Ω~I=ΩI+(Au)I,k~B=kB+(Au)B,\tilde \Omega_I = \Omega_I + (A u)_I, \qquad \tilde k_B = k_B + (A u)_B,

and asks for Ω~I=0\tilde \Omega_I = 0. The subscripts II and BB are the inner and boundary vertices.

  1. BFF(M, target)
  2. 1compute the corner angles, Ω_I, k_B and the cotangent Laplacian A
  3. 2if the target is the scale factors u_B then
  4. 3solve A_II u_I = −Ω_I − A_IB u_B ▷ Dirichlet problem
  5. 4k̃_B ← k_B + (A u)_B
  6. 5else ▷ the target is k̃_B, with Σ k̃_B = 2π
  7. 6solve A u = (−Ω_I, k̃_B − k_B), with u = 0 at one vertex ▷ Neumann problem
  8. 7l̃_t ← e^{(u_i + u_j)/2} ℓ_ij for each boundary edge t = (b_t, b_{t+1})
  9. 8φ_t ← k̃_1 + ⋯ + k̃_t; T_t ← (cos φ_t, sin φ_t)
  10. 9l*_t ← l̃_t − l̃_t (λ · T_t), with λ such that Σ_t l*_t T_t = 0
  11. 10γ(b_1) ← 0; γ(b_{t+1}) ← γ(b_t) + l*_t T_t
  12. 11solve A_II x_I = −A_IB γ for each of the two coordinates ▷ harmonic extension
  13. 12return (γ on the boundary, x inside)

Lines L2 to L6 turn one kind of boundary data into the other. Line L3 is a Poisson problem with the curvature as its source, and line L4 reads off the new turning angles. Line L6 is the inverse: the system is singular because AA kills the constants, and it is solvable because the right side adds up to 0 (see the correctness section), so one vertex is fixed.

Lines L7 to L10 draw the boundary. The edge tt leaves btb_t in the direction TtT_t, after the curve has turned by k~t\tilde k_t at btb_t. The asked lengths l~\tilde l and the angles k~\tilde k do not in general give a closed polygon, because the discrete relation is only an approximation of the smooth one. Line L9 changes the lengths by the least amount, in the weighted norm ∑t(lt∗−l~t)2/l~t\sum_t (l^*_t - \tilde l_t)^2 / \tilde l_t, that closes the polygon. The minimizer has the form of line L9 by a Lagrange multiplier λ∈R2\lambda \in \mathbb{R}^2, and λ\lambda solves the 2×22 \times 2 system (∑tl~tTtTt⊤)λ=∑tl~tTt\big(\sum_t \tilde l_t T_t T_t^\top\big) \lambda = \sum_t \tilde l_t T_t. The angles are not changed.

Line L11 extends the boundary curve inside. The two coordinates of a conformal map are harmonic functions, so in the smooth setting the harmonic extension of the boundary values is the conformal map itself. Sawhney and Crane also give a variant that extends one coordinate and takes the other as its harmonic conjugate, which is closer to conformal on coarse meshes.

Degenerate cases. Turning angles that do not add up to 2π2\pi have no solution, and the code raises an error. If all the directions TtT_t are parallel, the 2×22 \times 2 system of line L9 is singular. If the asked polygon is far from closed, line L9 can give a length that is 0 or negative, and the output boundary then crosses itself.

Example

Take the pyramid of the LSCM and ARAP pages: base corners x0=(−1,−1,0)x_0 = (-1, -1, 0), x1=(1,−1,0)x_1 = (1, -1, 0), x2=(1,1,0)x_2 = (1, 1, 0), x3=(−1,1,0)x_3 = (-1, 1, 0), apex x4=(0,0,1)x_4 = (0, 0, 1), side triangles (0,1,4)(0, 1, 4), (1,2,4)(1, 2, 4), (2,3,4)(2, 3, 4), (3,0,4)(3, 0, 4). The boundary loop is 0,1,2,30, 1, 2, 3.

Target uB=0u_B = 0, keep the boundary lengths.

step value
L1 apex angles 70.53°70.53° each, so Ω4=77.88°=1.3593\Omega_4 = 77.88° = 1.3593; base corners have two angles of 54.74°54.74°, so kb=70.53°k_b = 70.53°; A44=2.8284A_{44} = 2.8284, Ab4=−0.7071A_{b4} = -0.7071
L3 u4=−Ω4/A44=−0.4806u_4 = -\Omega_4 / A_{44} = -0.4806
L4 (Au)b=0.7071⋅0.4806=0.3398=19.47°(A u)_b = 0.7071 \cdot 0.4806 = 0.3398 = 19.47°, so k~b=70.53°+19.47°=90°\tilde k_b = 70.53° + 19.47° = 90° at each corner
L7 l~t=2\tilde l_t = 2 for all four edges
L9 the square closes, so l∗=l~l^* = \tilde l, no change
L10 γ=(0,0),(0,2),(−2,2),(−2,0)\gamma = (0, 0), (0, 2), (-2, 2), (-2, 0)
L11 apex at (−1,1)(-1, 1), the centre

The image is a square of side 2 with the apex at its centre, so the four side edges have length 2=1.414\sqrt2 = 1.414 instead of 3=1.732\sqrt3 = 1.732. The apex has the scale factor e−0.48=0.62e^{-0.48} = 0.62, so the region near it shrinks, as a conformal map must do near a point of positive curvature. ARAP gives a square of side 2.2762.276 on the same pyramid instead, because it trades angles for lengths.

Target turning angles (120°,120°,120°,0°)(120°, 120°, 120°, 0°), a triangle. Line L6 gives u=(0,0.2468,0,−1.7278,−0.8508)u = (0, 0.2468, 0, -1.7278, -0.8508) for the vertices 00 to 44. Line L7 asks for the lengths 2.2627,2.2627,0.8430,0.84302.2627, 2.2627, 0.8430, 0.8430, which do not close. Line L9 changes them to 2.0312,2.0312,1.0156,1.01562.0312, 2.0312, 1.0156, 1.0156. The output is an equilateral triangle of side 2.03122.0312 with vertex 3 at the midpoint of the side from vertex 2 to vertex 0, and its turning angles are 120°,120°,120°,0°120°, 120°, 120°, 0° to 10−1410^{-14}. The large change of the lengths comes from the coarse mesh: four triangles are a poor model of a conformal map.

Measured on finer meshes. On 5 random disks of 37 vertices and 18 boundary vertices (a hexagonal grid with jitter, lifted to a random quadratic surface, seeds 0 to 4):

target largest relative change of a length at L9 turning angles met to flipped triangles
uB=0u_B = 0 4.5×10−74.5 \times 10^{-7} to 8.6×10−48.6 \times 10^{-4} (not asked) 0
rectangle, k~=90°\tilde k = 90° at 4 vertices 0.0120.012 to 0.0400.040 1.2×10−151.2 \times 10^{-15} 0

The flips were checked with ORIENT2D, the orientation test, evaluated exactly on the float coordinates converted to rationals. A float evaluation of that sign is not reliable for tiny triangles, because of catastrophic cancellation; exact predicates avoid it. This is the robustness problem of geometry. The numbers are measurements on these meshes, not bounds.

Correctness

The proof in proofs/correctness.md shows the following.

  1. For every choice of uBu_B, the angles of line L4 add up to 2π2\pi. This uses the discrete Gauss-Bonnet theorem, ∑IΩi+∑Bkb=2πχ=2π\sum_I \Omega_i + \sum_B k_b = 2\pi\chi = 2\pi for a disk, and the fact that the columns of AA add up to 0.
  2. AIIA_{II} is positive definite, so lines L3 and L11 have unique solutions. The system of line L6 has a solution exactly when ∑Bk~b=2π\sum_B \tilde k_b = 2\pi, and the solution is unique up to a constant. Lines L3 to L4 and line L6 are inverse maps: from the k~B\tilde k_B of line L4, line L6 gives back uu up to a constant.
  3. Key invariant. The polygon of line L10 is closed, its turning angle at each btb_t is k~t\tilde k_t (when all lt∗>0l^*_t > 0), and l∗l^* is the unique closest closed choice of lengths to l~\tilde l in the weighted norm. If the asked polygon closes, l∗=l~l^* = \tilde l.
  4. If MM is planar and uB=0u_B = 0, the output is congruent to the input.

So the turning angles that were asked for are met exactly, up to rounding, and the lengths that were asked for are met up to the smallest change that closes the boundary. The proof does not show that the interior map has no flipped triangle, or that the output is exactly conformal in any discrete sense.

Proof: BFF turns boundary scale factors into turning angles and back, meets the asked angles exactly, and changes the asked lengths by the least amount that closes the boundaryfull

Setting. MM is a connected triangle mesh with the topology of a disk, with VIV_I inner vertices, VB=mV_B = m boundary vertices in one loop b1,…,bmb_1, \dots, b_m, EE edges and FF triangles, all of positive area. Ωi=2π−∑θ\Omega_i = 2\pi - \sum\theta at an inner vertex and kb=π−∑θk_b = \pi - \sum\theta at a boundary vertex, where ∑θ\sum \theta is the sum of the corner angles at the vertex. AA is the cotangent Laplacian, Aij=−12(cot⁡αij+cot⁡βij)A_{ij} = -\frac12(\cot\alpha_{ij} + \cot\beta_{ij}) for an edge ijij with opposite angles αij\alpha_{ij} and βij\beta_{ij} (one of them absent on the boundary), Aij=0A_{ij} = 0 for non-adjacent i≠ji \ne j, and Aii=−∑j≠iAijA_{ii} = -\sum_{j \ne i} A_{ij}. The algorithm and its lines L1 to L12 are as on the page.

Claim.

  1. For every uBu_B, the angles k~B\tilde k_B of line L4 satisfy ∑Bk~b=2π\sum_B \tilde k_b = 2\pi.
  2. AIIA_{II} is positive definite. The system Au=rA u = r of line L6 has a solution if and only if ∑Bk~b=2π\sum_B \tilde k_b = 2\pi; the solution is unique up to adding a constant, and fixing uu at one vertex makes it unique. Lines L3 to L4 and line L6 are inverse to each other, up to the constant.
  3. The polygon of line L10 is closed, its turning angle at btb_t is k~t\tilde k_t when all lt∗>0l^*_t > 0 and k~t∈(−π,π)\tilde k_t \in (-\pi, \pi), and l∗l^* is the unique minimizer of ∑t(lt−l~t)2/l~t\sum_t (l_t - \tilde l_t)^2 / \tilde l_t over all ll with ∑tltTt=0\sum_t l_t T_t = 0, provided the directions TtT_t are not all parallel. If ∑tl~tTt=0\sum_t \tilde l_t T_t = 0 then l∗=l~l^* = \tilde l.
  4. If MM lies in the plane, its triangles are counterclockwise and it is embedded, then with uB=0u_B = 0 the output is the image of the input under a rotation and a translation.
  5. (Termination.) The algorithm does a fixed, finite number of operations: one pass over the triangles, at most three linear solves, one 2×22 \times 2 solve and two passes over the boundary.

Step 1 (discrete Gauss-Bonnet for a disk). Every triangle has angle sum π\pi, so the sum of all corner angles is πF\pi F. Each triangle has three edges, inner edges lie in two triangles and the mm boundary edges in one, so 3F=2E−m3F = 2E - m. Then

∑IΩi+∑Bkb=2πVI+πm−πF=2π(VI+m−3F+m2+F)=2π(V−E+F)=2πχ=2π,\sum_I \Omega_i + \sum_B k_b = 2\pi V_I + \pi m - \pi F = 2\pi\Big(V_I + m - \frac{3F + m}{2} + F\Big) = 2\pi (V - E + F) = 2\pi\chi = 2\pi,

since a disk has Euler characteristic χ=1\chi = 1.

Step 2 (part 1). AA is symmetric and its rows add up to 0, so its columns add up to 0, and ∑v(Au)v=0\sum_{v} (A u)_v = 0 for every uu. Line L3 says (Au)I=AIIuI+AIBuB=−ΩI(A u)_I = A_{II} u_I + A_{IB} u_B = -\Omega_I. So

∑Bk~b=∑Bkb+∑B(Au)b=∑Bkb−∑I(Au)i=∑Bkb+∑IΩi=2π.\sum_B \tilde k_b = \sum_B k_b + \sum_B (A u)_b = \sum_B k_b - \sum_I (A u)_i = \sum_B k_b + \sum_I \Omega_i = 2\pi.

Step 3 (the Dirichlet energy). For a function xx on the vertices, extend it linearly over each triangle tt, of area AtA_t. The same computation as in Steps 1 and 2 of the proof of the ARAP parameterization page, done for a scalar function, gives At∥∇x∥2=12∑cot⁡θm(xk−xl)2A_t \lVert \nabla x \rVert^2 = \frac12 \sum \cot\theta_m (x_k - x_l)^2 over the three edges {k,l}\{k, l\} of tt, with θm\theta_m the angle opposite. Adding over the triangles, x⊤Ax=∑tAt∥∇x∥2≥0x^\top A x = \sum_t A_t \lVert \nabla x \rVert^2 \ge 0. If x⊤Ax=0x^\top A x = 0, then ∇x=0\nabla x = 0 on each triangle, so xx is constant on each triangle, and since MM is connected, xx is one constant. So AA is positive semidefinite with kernel the constants. Differentiating x⊤Axx^\top A x in xix_i also gives (Ax)i=∑t∋iAt∇φi⋅∇x(A x)_i = \sum_{t \ni i} A_t \nabla\varphi_i \cdot \nabla x, where φi\varphi_i is the hat function of vertex ii.

Step 4 (part 2). For y≠0y \ne 0 on the inner vertices, extend it by 0 on the boundary to xx. Then y⊤AIIy=x⊤Ax>0y^\top A_{II} y = x^\top A x > 0, because xx is not constant (it is 0 on the boundary and not 0 somewhere). So AIIA_{II} is positive definite and line L3 has one solution. For line L6, AA is symmetric with kernel the constants, so its range is the set of vectors orthogonal to the constants: Au=rA u = r has a solution if and only if ∑vrv=0\sum_v r_v = 0. Here ∑vrv=−∑IΩi+∑B(k~b−kb)=∑Bk~b−2π\sum_v r_v = -\sum_I \Omega_i + \sum_B (\tilde k_b - k_b) = \sum_B \tilde k_b - 2\pi by Step 1. Two solutions differ by an element of the kernel, a constant. With uf=0u_f = 0 fixed at one vertex ff, the matrix AA without row and column ff is positive definite by the argument above with {f}\{f\} in place of the boundary, so the reduced system has one solution. That solution also satisfies row ff: all rows of Au−rA u - r add up to ∑v(Au)v−∑vrv=0−0\sum_v (A u)_v - \sum_v r_v = 0 - 0, and all rows but row ff are 0.

For the inverse property, let uu and k~B\tilde k_B come from lines L3 and L4. Then (Au)I=−ΩI(A u)_I = -\Omega_I and (Au)B=k~B−kB(A u)_B = \tilde k_B - k_B, so uu solves the system of line L6 with these k~B\tilde k_B, and line L6 returns u−ufu - u_f. Conversely, if uu comes from line L6, then uIu_I solves line L3 with its own uBu_B, by the inner rows of the system, and line L3 has only one solution; line L4 then gives back k~B\tilde k_B by the boundary rows.

Step 5 (part 3). By line L9, ∑tlt∗Tt=∑tl~tTt−(∑tl~tTtTt⊤)λ=0\sum_t l^*_t T_t = \sum_t \tilde l_t T_t - \big(\sum_t \tilde l_t T_t T_t^\top\big) \lambda = 0, by the choice of λ\lambda. The matrix G=∑tl~tTtTt⊤G = \sum_t \tilde l_t T_t T_t^\top is positive semidefinite, and μ⊤Gμ=∑tl~t(Tt⋅μ)2=0\mu^\top G \mu = \sum_t \tilde l_t (T_t \cdot \mu)^2 = 0 only if μ\mu is orthogonal to every TtT_t, which for μ≠0\mu \ne 0 means that all TtT_t are parallel. So GG is invertible when they are not. The problem min⁡∑t(lt−l~t)2/l~t\min \sum_t (l_t - \tilde l_t)^2 / \tilde l_t subject to ∑tltTt=0\sum_t l_t T_t = 0 has a strictly convex objective, since every l~t>0\tilde l_t > 0, and linear constraints. Its Lagrange condition is 2(lt−l~t)/l~t+μ⋅Tt=02 (l_t - \tilde l_t) / \tilde l_t + \mu \cdot T_t = 0 for all tt, that is, lt=l~t−l~t(λ⋅Tt)l_t = \tilde l_t - \tilde l_t (\lambda \cdot T_t) with λ=μ/2\lambda = \mu / 2. For a convex objective with linear constraints this condition is sufficient for a minimum, and strict convexity makes the minimizer unique. l∗l^* meets the condition and the constraint, so it is the minimizer. If ∑tl~tTt=0\sum_t \tilde l_t T_t = 0 then λ=0\lambda = 0 and l∗=l~l^* = \tilde l.

By line L10, the edge tt goes from γ(bt)\gamma(b_t) in the direction TtT_t, at the angle φt\varphi_t, when lt∗>0l^*_t > 0. The turning angle at btb_t is the angle from Tt−1T_{t-1} to TtT_t, which is φt−φt−1=k~t\varphi_t - \varphi_{t-1} = \tilde k_t for t≥2t \ge 2, and for t=1t = 1 it is φ1−φm=k~1−2π\varphi_1 - \varphi_m = \tilde k_1 - 2\pi by part 1, the same direction change. Since k~t∈(−π,π)\tilde k_t \in (-\pi, \pi), this is the signed turning angle. After the last edge the polygon is back at γ(b1)\gamma(b_1) because ∑tlt∗Tt=0\sum_t l^*_t T_t = 0.

Step 6 (part 4). An embedded planar mesh with counterclockwise triangles has angle sum 2π2\pi at each inner vertex, so ΩI=0\Omega_I = 0, and at each boundary vertex kbk_b is the turning angle of the input boundary polygon. With uB=0u_B = 0, line L3 is AIIuI=0A_{II} u_I = 0, so u=0u = 0, line L4 gives k~B=kB\tilde k_B = k_B, and line L7 gives l~=ℓ\tilde l = \ell, the input lengths. The input boundary is a closed polygon with these lengths and turning angles, so ∑tl~tTt′=0\sum_t \tilde l_t T'_t = 0 for its own edge directions Tt′T'_t, which are the TtT_t turned by one fixed angle. Hence ∑tl~tTt=0\sum_t \tilde l_t T_t = 0 too, and by part 3, l∗=l~l^* = \tilde l. A polygon is fixed up to a rotation and a translation by its edge lengths and its turning angles, so γ=ρ(x)\gamma = \rho(x) on the boundary for a rotation and translation ρ\rho.

For line L11, let ff be an affine function of the plane, such as a coordinate of ρ\rho. At an inner vertex ii, by Step 3, (Af)i=∇f⋅∑t∋iAt∇φi=∇f⋅∫S∇φi dA(A f)_i = \nabla f \cdot \sum_{t \ni i} A_t \nabla \varphi_i = \nabla f \cdot \int_S \nabla\varphi_i \, dA, where SS is the star of ii, because ∇f\nabla f is constant. By the divergence theorem, ∫S∇φi dA=∮∂Sφi n ds=0\int_S \nabla \varphi_i \, dA = \oint_{\partial S} \varphi_i\, n \, ds = 0, because φi=0\varphi_i = 0 on the boundary of the star. So the coordinates of ρ(x)\rho(x) solve line L11, and by part 2 they are its only solution. So the output is ρ\rho applied to the input.

Step 7 (part 5). The steps are the ones listed in part 5. Each solve is with a positive definite matrix by part 2, or with GG of Step 5, so the elimination finishes without a zero pivot in exact arithmetic. There is no loop whose length depends on the data except the passes over the vertices, triangles and boundary.

What is not claimed. The proof does not show that the interior map of line L11 has every triangle counterclockwise, that the output boundary is a simple curve when some lt∗≤0l^*_t \le 0, or that the result is close to conformal by any stated bound. ■\blacksquare

Complexity

For nn vertices and mm boundary vertices, line L1 takes O(n)O(n) time. Lines L3, L6 and L11 are solves with AIIA_{II} or with AA without one row and column, which do not depend on the target. With dense elimination, as in the code of this page, each takes O(n3)O(n^3) time and O(n2)O(n^2) space. With sparse Cholesky factorization and nested dissection on the planar mesh graph, the factorization takes O(n3/2)O(n^{3/2}) time and O(nlog⁡n)O(n \log n) space, and each solve O(nlog⁡n)O(n \log n) time. Lines L7 to L10 take O(m)O(m) time. The matrices are factored once, so a new target costs only back substitutions, O(n2)O(n^2) dense or O(nlog⁡n)O(n \log n) sparse, and O(m)O(m) for the boundary.

Properties

  • Proved. Exact boundary angles: the output boundary turns by the asked angles, up to rounding.
  • Proved. The asked lengths are changed only by the smallest weighted change that closes the polygon, and not at all when the asked polygon closes.
  • Proved. A planar mesh with uB=0u_B = 0 comes back congruent to itself.
  • Linear. Every step is a linear solve with a fixed matrix, or a 2 by 2 solve. There is no iteration and no start map.
  • Not guaranteed. The interior can have flipped triangles, because the cotangent weights can be negative, and the boundary can cross itself when the asked target is far from what the surface allows.
  • Approximately conformal. The discrete relation is a discretization of the smooth one, and the page proves no bound on the angle distortion of the result.

Variants and improvements

  • Cone singularities. The paper puts curvature at a few inner vertices, the cones, and cuts the mesh through them. Then the area distortion of a conformal map can be made much smaller. Choosing the cones is a separate problem.
  • Target shapes. The paper uses the same two boundary maps to flatten onto a disk and onto a given boundary curve.
  • Harmonic conjugate. Line L11 can extend only one coordinate and compute the other as its conjugate, which is closer to conformal.
  • Nonlinear discrete conformal maps. Discrete conformal equivalence changes the lengths exactly by e(ui+uj)/2e^{(u_i + u_j)/2} and solves a convex nonlinear problem for exact target angles inside and on the boundary. It is slower but its result is exactly a discrete conformal map in its sense.
  • Other conformal maps. LSCM also needs one linear solve, but it does not let the user choose the boundary. ARAP trades angles for lengths.

When to use it

Use it when a conformal map must have a given outline, for example a rectangle for a texture atlas or a polygon that fits a cutting sheet, or when a user changes the boundary target many times and each change must be fast. With uB=0u_B = 0 it is a good default free-boundary conformal map. It needs a disk; cut a closed or higher-genus surface first along a cut graph. Check the result with an exact orientation test. If injectivity is required, use a method that guarantees it.

Pitfalls

  • Angles that do not add up to 2π2\pi. A user who asks for a rectangle by setting four angles to π/2\pi/2 and forgets to set all other boundary angles to 0 gives line L6 a right side that does not add up to 0. A solver that ignores the singular row then returns a uu that meets none of the angles.
  • Wrong sign of the Laplacian. Some texts use the negative semidefinite Laplacian. Putting that matrix into lines L3 and L6 without changing the signs of the right sides gives −u-u instead of uu. With a turning-angle target, line L7 then asks for e−ue^{-u} times the lengths, the regions that should shrink grow, and line L9 must make large changes to close the curve.
  • Exterior angle against interior angle. kbk_b is π\pi minus the angle sum, the turning of the boundary. Using the angle sum itself at line L4 gives angles whose sum is not 2π2\pi, so the directions of line L8 do not wind around once, and no change of the lengths at line L9 gives a simple closed curve.
  • Expecting exact lengths. The asked lengths are met only if the asked polygon closes. Line L9 changes them, by up to 4%4\% in the rectangle test above and 20%20\% on the coarse pyramid. A target that needs exact lengths must allow the angles to change instead.
  • Clamping cotangents. Setting negative cotangent weights to 0 at line L1 keeps the rows of AA adding up to 0, so the angles still add up to 2π2\pi, but line L11 then no longer reproduces linear functions, and a planar mesh does not come back congruent to itself.

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.

boundary_first_flattening.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-first-flattening/. The authors are listed in prov/HE01QC.jsonl.

"""Boundary first flattening (Sawhney and Crane 2017), with a dense solver.

A conformal change of metric with log scale factor u changes the discrete
curvature by the cotangent Laplacian A (positive semidefinite, with
A_ij = -(cot a + cot b)/2 for an edge ij):

    new curvature = old curvature + A u,

at interior vertices (angle defect Omega) and at boundary vertices (turning
angle k). A flat image needs the new Omega to be 0 at the interior vertices.
Given the scale factors on the boundary (Dirichlet data), the code finds the
new turning angles, and given the turning angles (Neumann data), it finds
the scale factors. It then builds the boundary polygon, closes it by the
smallest weighted change of its lengths, and extends it to the interior by
a harmonic map.
"""

import math

from mx2geom import boundary_loop, corner_angle, length, solve


def curvatures_and_laplacian(vertices, faces):
    """The cotangent Laplacian (dense), the angle sum at each vertex and the boundary loop."""
    n = len(vertices)
    a = [[0.0] * n for _ in range(n)]
    angle_sum = [0.0] * n
    for tri in faces:
        ls = [length(vertices[tri[(k + 1) % 3]], vertices[tri[(k + 2) % 3]]) for k in range(3)]
        for k in range(3):
            # ls[k] is the edge opposite corner k.
            theta = corner_angle(ls[k], ls[(k + 1) % 3], ls[(k + 2) % 3])
            angle_sum[tri[k]] += theta
            w = 0.5 / math.tan(theta)
            i, j = tri[(k + 1) % 3], tri[(k + 2) % 3]
            a[i][j] -= w
            a[j][i] -= w
            a[i][i] += w
            a[j][j] += w
    return a, angle_sum, boundary_loop(faces)


def dirichlet_to_neumann(a, angle_sum, loop, u_boundary):
    """Scale factors u_B on the boundary -> (u at all vertices, new turning angles k~ on the boundary)."""
    n = len(a)
    on_b = set(loop)
    inner = [v for v in range(n) if v not in on_b]
    u = [0.0] * n
    for v, x in zip(loop, u_boundary):
        u[v] = x
    if inner:
        rows = [[a[i][j] for j in inner] for i in inner]
        rhs = [[-(2 * math.pi - angle_sum[i]) - sum(a[i][b] * u[b] for b in loop)] for i in inner]
        for i, x in zip(inner, solve(rows, rhs)):  # @line L3
            u[i] = x[0]
    k_new = [(math.pi - angle_sum[b]) + sum(a[b][j] * u[j] for j in range(n)) for b in loop]  # @line L4
    return u, k_new


def neumann_to_dirichlet(a, angle_sum, loop, k_target):
    """Turning angles k~ on the boundary (adding up to 2 pi) -> u at all vertices, with u = 0 at loop[0]."""
    n = len(a)
    if abs(sum(k_target) - 2 * math.pi) > 1e-9:
        raise ValueError("the target turning angles must add up to 2 pi")
    target = [-(2 * math.pi - angle_sum[v]) for v in range(n)]
    for b, k in zip(loop, k_target):
        target[b] = k - (math.pi - angle_sum[b])
    # A u = target has a one-dimensional kernel (the constants); fix u at loop[0].
    fix = loop[0]
    free = [v for v in range(n) if v != fix]
    rows = [[a[i][j] for j in free] for i in free]
    x = solve(rows, [[target[i]] for i in free])  # @line L6
    u = [0.0] * n
    for v, xv in zip(free, x):
        u[v] = xv[0]
    return u


def boundary_polygon(vertices, loop, u, k_new):
    """The closed boundary polygon with turning angles k_new and lengths near e^((u_i+u_j)/2) l_ij.

    Returns the points, the asked lengths and the lengths after closing.
    """
    m = len(loop)
    lt = []
    for t in range(m):
        i, j = loop[t], loop[(t + 1) % m]
        lt.append(math.exp((u[i] + u[j]) / 2) * length(vertices[i], vertices[j]))  # @line L7
    phi, tang = 0.0, []
    for t in range(m):
        # The edge from loop[t] to loop[t+1] leaves vertex loop[t], where the curve turns by k_new[t].
        phi += k_new[t]
        tang.append((math.cos(phi), math.sin(phi)))  # @line L8
    # Close the curve: minimize sum (l* - l~)^2 / l~ subject to sum l* T = 0, a 2 x 2 system.
    g = [[sum(lt[t] * tang[t][r] * tang[t][c] for t in range(m)) for c in range(2)] for r in range(2)]
    gap = [sum(lt[t] * tang[t][r] for t in range(m)) for r in range(2)]
    lam = solve(g, [[gap[0]], [gap[1]]])
    ls = [lt[t] - lt[t] * (tang[t][0] * lam[0][0] + tang[t][1] * lam[1][0]) for t in range(m)]  # @line L9
    pts, p = {}, (0.0, 0.0)
    for t in range(m):
        pts[loop[t]] = p  # @line L10
        p = (p[0] + ls[t] * tang[t][0], p[1] + ls[t] * tang[t][1])
    return pts, lt, ls


def harmonic_extension(a, loop, pts, n):
    """Extend the boundary positions to the interior: (A x)_i = 0 at every interior vertex."""
    on_b = set(loop)
    inner = [v for v in range(n) if v not in on_b]
    out = [pts.get(v) for v in range(n)]
    if inner:
        rows = [[a[i][j] for j in inner] for i in inner]
        rhs = [[-sum(a[i][b] * pts[b][c] for b in loop) for c in range(2)] for i in inner]
        for i, x in zip(inner, solve(rows, rhs)):  # @line L11
            out[i] = (x[0], x[1])
    return out


def bff(vertices, faces, u_boundary=None, k_target=None):
    """Flatten a disk mesh. Give the boundary scale factors u_boundary or the turning angles k_target.

    With neither, u_boundary = 0 (keep the boundary lengths). Returns (points, info), where info has
    the boundary loop, the scale factors u, the turning angles k, the asked boundary lengths and the
    boundary lengths after closing, in the order of the loop.
    """
    a, angle_sum, loop = curvatures_and_laplacian(vertices, faces)  # @line L1
    if k_target is None:  # @line L2
        if u_boundary is None:
            u_boundary = [0.0] * len(loop)
        u, k_new = dirichlet_to_neumann(a, angle_sum, loop, u_boundary)
    else:  # @line L5
        k_new = list(k_target)
        u = neumann_to_dirichlet(a, angle_sum, loop, k_new)
    pts, asked, closed = boundary_polygon(vertices, loop, u, k_new)
    out = harmonic_extension(a, loop, pts, len(vertices))
    return out, {"loop": loop, "u": u, "k": k_new, "asked": asked, "lengths": closed}  # @line L12
mx2geom.py 150 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mx2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small tools for triangle meshes, used by the mx2 pages.

Points are tuples of int, fractions.Fraction or float. ORIENT2D is 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).
"""

import math
from fractions import Fraction


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 exact_orient2d(a, b, c):
    """ORIENT2D with the float coordinates converted to rationals first, so the sign is exact."""
    return orient2d(*[tuple(Fraction(x) for x in p) for p in (a, b, c)])


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), float or complex.
    Raises ValueError if a pivot has absolute value <= tol.
    """
    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]
        for r in range(col + 1, n):
            f = rows[r][col]
            if f:
                f = Fraction(f) / pr[col] if isinstance(f, int) and isinstance(pr[col], int) else f / pr[col]
                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] = Fraction(s) / row[i] if isinstance(s, int) and isinstance(row[i], int) else s / row[i]
    return x


def cholesky(a):
    """The lower triangular factor l with a = l l^T of a symmetric positive definite float matrix."""
    n = len(a)
    l = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(l[i][k] * l[j][k] for k in range(j))
            if i == j:
                if s <= 0:
                    raise ValueError("matrix is not positive definite")
                l[i][i] = math.sqrt(s)
            else:
                l[i][j] = s / l[j][j]
    return l


def cholesky_solve(l, b):
    """Solve l l^T x = b for one right-hand side b, a list of floats."""
    n = len(l)
    y = [0.0] * n
    for i in range(n):
        y[i] = (b[i] - sum(l[i][k] * y[k] for k in range(i))) / l[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][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 undirected_edges(faces):
    """The sorted list of edges, each a sorted pair of vertex indices."""
    return sorted({tuple(sorted((tri[k], tri[(k + 1) % 3]))) for tri in faces for k in range(3)})


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):
    """V - E + F of the mesh, counting only the vertices used by faces."""
    verts = {v for tri in faces for v in tri}
    return len(verts) - len(undirected_edges(faces)) + len(faces)


def length(p, q):
    return math.sqrt(sum((float(a) - float(b)) ** 2 for a, b in zip(p, q)))


def corner_angle(a, b, c):
    """The angle opposite the side of length a in a triangle with sides a, b, c (law of cosines)."""
    x = (b * b + c * c - a * a) / (2 * b * c)
    return math.acos(max(-1.0, min(1.0, x)))


def triangle_frame(p0, p1, p2):
    """Corners of a congruent counterclockwise 2D triangle: p0 at 0, p1 on the positive x-axis."""
    l01, l12, l20 = length(p0, p1), length(p1, p2), length(p2, p0)
    a0 = corner_angle(l12, l01, l20)
    return (0.0, 0.0), (l01, 0.0), (l20 * math.cos(a0), l20 * math.sin(a0))
test_boundary_first_flattening.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-first-flattening/. The authors are listed in prov/HE01QC.jsonl.

import math
import random

from boundary_first_flattening import bff, curvatures_and_laplacian, dirichlet_to_neumann, neumann_to_dirichlet
from mx2geom import exact_orient2d


def hex_disk(r, rng, bend, jitter=0.15):
    """A hexagonal patch of the triangular lattice, jittered and lifted to z = a x^2 + b y^2 + c x y."""
    pts, index = [], {}
    for i in range(-r, r + 1):
        for j in range(-r, r + 1):
            if abs(i + j) <= r:
                index[(i, j)] = len(pts)
                pts.append((i + 0.5 * j + rng.uniform(-jitter, jitter), j * math.sqrt(3) / 2 + rng.uniform(-jitter, jitter)))
    a, b, c = [rng.uniform(-bend, bend) for _ in range(3)]
    verts = [(x, y, a * x * x + b * y * y + c * x * y) for x, y in pts]
    faces = []
    for (i, j), v in index.items():
        if (i + 1, j) in index and (i, j + 1) in index:
            faces.append((v, index[(i + 1, j)], index[(i, j + 1)]))
        if (i + 1, j) in index and (i + 1, j - 1) in index:
            faces.append((v, index[(i + 1, j - 1)], index[(i + 1, j)]))
    return verts, faces


def turning_angles(pts, loop):
    """The signed exterior angle of the output polygon at each boundary vertex."""
    m, out = len(loop), []
    for t in range(m):
        p0, p1, p2 = pts[loop[t - 1]], pts[loop[t]], pts[loop[(t + 1) % m]]
        d0 = (p1[0] - p0[0], p1[1] - p0[1])
        d1 = (p2[0] - p1[0], p2[1] - p1[1])
        out.append(math.atan2(d0[0] * d1[1] - d0[1] * d1[0], d0[0] * d1[0] + d0[1] * d1[1]))
    return out


def boundary_lengths(pts, loop):
    return [math.dist(pts[loop[t]], pts[loop[(t + 1) % len(loop)]]) for t in range(len(loop))]


def rectangle_angles(m):
    k = [0.0] * m
    for c in range(4):
        k[(c * m) // 4] = math.pi / 2
    return k


PYRAMID_V = [(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0), (0, 0, 1)]
PYRAMID_F = [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 0, 4)]


def test_new_turning_angles_add_up_to_two_pi():
    for seed in range(5):
        rng = random.Random(seed)
        v, f = hex_disk(3, rng, 0.4)
        a, s, loop = curvatures_and_laplacian(v, f)
        _, k = dirichlet_to_neumann(a, s, loop, [rng.uniform(-0.5, 0.5) for _ in loop])
        assert abs(sum(k) - 2 * math.pi) < 1e-12


def test_dirichlet_and_neumann_maps_are_inverse():
    for seed in range(5):
        rng = random.Random(10 + seed)
        v, f = hex_disk(3, rng, 0.4)
        a, s, loop = curvatures_and_laplacian(v, f)
        u, k = dirichlet_to_neumann(a, s, loop, [rng.uniform(-0.5, 0.5) for _ in loop])
        u2 = neumann_to_dirichlet(a, s, loop, k)
        c = u[loop[0]] - u2[loop[0]]
        assert max(abs(u[x] - u2[x] - c) for x in range(len(v))) < 1e-12


def test_asked_turning_angles_are_met():
    for seed in range(5):
        rng = random.Random(seed)
        v, f = hex_disk(3, rng, 0.4)
        _, info = bff(v, f)
        m = len(info["loop"])
        raw = [rng.uniform(0.0, 1.0) for _ in range(m)]
        targets = [rectangle_angles(m), [2 * math.pi * x / sum(raw) for x in raw]]
        for kt in targets:
            pts, info = bff(v, f, k_target=kt)
            got = turning_angles(pts, info["loop"])
            assert max(abs(x - y) for x, y in zip(got, kt)) < 1e-9
            got_len = boundary_lengths(pts, info["loop"])
            assert max(abs(x - y) for x, y in zip(got_len, info["lengths"])) < 1e-9


def test_rectangle_and_length_modes_have_no_flips_on_small_disks():
    for seed in range(5):
        rng = random.Random(seed)
        v, f = hex_disk(3, rng, 0.4)
        for kt in (None, rectangle_angles(18)):
            pts, _ = bff(v, f, k_target=kt)
            for x, y, z in f:
                assert exact_orient2d(pts[x], pts[y], pts[z]) > 0


def test_planar_disk_keeps_all_lengths():
    for seed in range(3):
        rng = random.Random(seed)
        v, f = hex_disk(3, rng, 0.0)
        pts, info = bff(v, f)
        assert max(abs(x - y) for x, y in zip(info["asked"], info["lengths"])) < 1e-12
        for x, y, z in f:
            for p, q in ((x, y), (y, z), (z, x)):
                assert abs(math.dist(pts[p], pts[q]) - math.dist(v[p], v[q])) < 1e-9


def test_asked_lengths_are_met_up_to_the_smallest_closing_change():
    for seed in range(5):
        rng = random.Random(seed)
        v, f = hex_disk(3, rng, 0.4)
        a, s, loop = curvatures_and_laplacian(v, f)
        ub = [rng.uniform(-0.3, 0.3) for _ in loop]
        pts, info = bff(v, f, u_boundary=ub)
        assert max(abs(x - y) for x, y in zip(boundary_lengths(pts, loop), info["lengths"])) < 1e-9
        asked, got, m = info["asked"], info["lengths"], len(loop)
        tang, phi = [], 0.0
        for t in range(m):
            phi += info["k"][t]
            tang.append((math.cos(phi), math.sin(phi)))
        cost = sum((x - y) ** 2 / y for x, y in zip(got, asked))
        # Every other closed polygon with the same directions changes the asked lengths at least as much.
        for _ in range(200):
            d = [rng.gauss(0, 0.05) for _ in range(m)]
            # Project d onto the closing directions: sum d_t T_t = 0.
            g = [[sum(tang[t][r] * tang[t][c] for t in range(m)) for c in range(2)] for r in range(2)]
            h = [sum(d[t] * tang[t][r] for t in range(m)) for r in range(2)]
            det = g[0][0] * g[1][1] - g[0][1] * g[1][0]
            lam = ((g[1][1] * h[0] - g[0][1] * h[1]) / det, (g[0][0] * h[1] - g[1][0] * h[0]) / det)
            d = [d[t] - tang[t][0] * lam[0] - tang[t][1] * lam[1] for t in range(m)]
            other = [x + y for x, y in zip(got, d)]
            assert sum((x - y) ** 2 / y for x, y in zip(other, asked)) >= cost - 1e-15


def test_pyramid_example():
    pts, info = bff(PYRAMID_V, PYRAMID_F)
    assert all(abs(k - math.pi / 2) < 1e-12 for k in info["k"])
    assert abs(info["u"][4] + 0.480602) < 1e-6
    assert max(abs(x - 2) for x in info["lengths"]) < 1e-12
    centre = ((pts[0][0] + pts[2][0]) / 2, (pts[0][1] + pts[2][1]) / 2)
    assert math.dist(centre, pts[4]) < 1e-12
    k_t = [math.radians(x) for x in (120, 120, 120, 0)]
    pts, info = bff(PYRAMID_V, PYRAMID_F, k_target=k_t)
    got = turning_angles(pts, info["loop"])
    assert max(abs(x - y) for x, y in zip(got, k_t)) < 1e-12
    assert abs(info["lengths"][0] - 2.031153) < 1e-6

History

Rohan Sawhney and Keenan Crane published boundary first flattening in ACM Transactions on Graphics in 2017. Earlier conformal flattenings either fixed the boundary completely, as in harmonic maps, or left it free, as in LSCM, and the nonlinear methods of discrete conformal geometry could prescribe the boundary angles but needed an iterative solver. BFF uses the Cherrier formula, known from conformal geometry, to turn boundary data of one kind into the other by one linear solve, and so gives boundary control at the cost of a few back substitutions with one factored matrix.

References

  1. Rohan Sawhney and Keenan Crane, Boundary first flattening, ACM Transactions on Graphics 37(1), Article 5, 2017, the Cherrier formula and its discrete form, the Dirichlet-to-Neumann and Neumann-to-Dirichlet maps, the closing of the boundary curve, and the extension to the interior
  2. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 5, Parametrization (conformal maps and the discrete Laplacian)

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.nested_dissection
  • a full proof of time.new_target
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of space.nested_dissection
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
  • at least three sources
  • a scene preset for the example