Algorithmadvanced
Harmonic coordinates
Also called harmonic cage coordinates.
Cage coordinates that solve Laplace's equation inside the cage on a grid; they are nonnegative and decay with distance inside the cage, even for concave cages.
- Solves
- Shape deformation
- Time
- O(G^4 + n G^3 + N n) allO(n) per_pointO(G^4 + n G^3) precompute
- Space
- O(G^3 + n G^2) extra
- Where
- G = the number of grid cells across the cage; N = the number of points to deform; n = the number of cage vertices
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Harmonic coordinates are the weights of a cage-based deformation that come from the Laplace equation. The coordinate of cage vertex is the harmonic function inside the cage that equals 1 at vertex , 0 at the other vertices, and is linear along each cage edge. A point then moves to , where are the moved cage vertices. Pushkar Joshi, Mark Meyer, Tony DeRose, Brian Green and Tom Sanocki (2007) introduced them at Pixar for posing characters with cages. Unlike mean value coordinates, harmonic coordinates are never negative, so a vertex on the far side of a concave part of the cage cannot pull a point the wrong way. They have no closed form; this page computes them in 2D with a finite difference solve on a grid.
In plain words
Think of the cage as a wire frame that holds a flat sheet of soap film. Lift one corner of the frame to height 1 and keep the other corners at 0, with the wire straight between corners. The film takes the smoothest shape that the frame allows, and its height at a point is the coordinate of that corner at the point. The film never dips below the lowest wire, so the height is never negative. It also cannot see through walls: around a sharp inner corner of the frame, the film has to go around it. Do this once for each corner, and each point of the shape has one weight per corner, which add up to 1.
The problem
The input is a cage, a simple polygon with the vertices in counterclockwise order, and the grid spacing . On the boundary of the cage, the hat function of vertex is 1 at , 0 at every other vertex, and linear on each edge. The harmonic coordinate is the solution of
The output is a discrete at the nodes of a grid with the spacing , and then at any point inside the cage, for the deformation .
The algorithm
Each interior node has four arms to its neighbours. An arm that leaves the cage is cut at its first crossing with the boundary, so its length is at most ; this is the Shortley-Weller stencil.
HARMONIC(cage, δ)- 1
U ← the grid nodes strictly inside the cage - 2
for each node p in U, cut each arm of p at its first crossing with the cage, giving the length ℓ ≤ δ - 3
give the arm of length ℓ, opposite an arm of length ℓ', the weight a = 2 / (ℓ(ℓ + ℓ')) - 4
if the arm ends on the cage at q then add a φ_i(q) to b_i[p] for each i, else put -a in the row of p of A - 5
factor A = LU, with the diagonal of A equal to the sum of the weights of the arms of each node - 6
for each vertex i, solve A x_i = b_i - 7
h_i(p) ← x_i[p] for every p in U DEFORM(p, c')- 8
return Σ_i h_i(p) c'_i, with h_i(p) by bilinear interpolation of the nodes
Lines L2 to L4 discretize at each node with the uneven three-point formula in each direction. Line L5 factors the matrix once; it is banded, with a band of width about when the nodes are numbered row by row, and it needs no pivoting because it is an M-matrix. For line L8, a grid node outside the cage takes the boundary data at its nearest boundary point. The paper of Joshi and others also uses a grid; the details of its solver are not repeated here.
Example
The cage is the L shape with the vertices , , , , , ; the vertex is the inner, reflex corner. The grid has cells across the cage, so , with 161 interior nodes. At the node in the upper arm of the L, the six harmonic coordinates are about
The vertex is hidden from behind the reflex corner: the segment from to it leaves the cage. Its harmonic coordinate is small and positive, . The mean value coordinates at the same point are about , with a negative weight for that vertex. So if the user drags to the right, the mean value deformation moves to the left, against the drag, while the harmonic deformation moves it a little to the right. The tests check these values, the nonnegativity at all nodes, the sum 1, the exact reproduction of linear functions at the nodes, and that the coordinate of peaks close to .
Correctness
The claims here are about the discrete coordinates, and the proof proves them.
- The constant 1 solves the discrete problem with the data , and the solution is unique, so at every node.
- The Shortley-Weller formula is exact on quadratic polynomials, so a linear function satisfies the discrete equation with its own boundary values. The data is the identity on the boundary, because each is linear on edges. So at every node: linear precision.
- The matrix has a positive diagonal, nonpositive entries off it, row sums at least 0, and a strictly dominant row in every connected set of nodes. So it is a nonsingular M-matrix with . The right sides are nonnegative, so : a discrete maximum principle.
- Bilinear interpolation in L8 keeps the sum 1 and the nonnegativity, and keeps linear precision in cells whose four nodes are interior.
For the continuous problem, the strong maximum principle gives strictly inside the cage when the cage has at least three vertices, and is smooth inside. The coordinates are not local in the strict sense: each is positive everywhere inside. They do decay with the distance from vertex measured inside the cage, which the test of the peak measures for one cage; this decay is an observed property, not a bound proved here.
Proof: The discrete harmonic coordinates exist, are unique and nonnegative, sum to 1, and reproduce linear functions at the grid nodesfull
We use the notation of the page. For a node and one axis, let the two arms along that axis have the lengths and , at most , and end at the points and . An end is either a node of , with the unknown value there, or a point on the cage, with the value of the boundary data there. The arm weights are , and the discrete Laplacian at is
The system of lines L4 to L6 is for every , with the boundary data , after the known boundary values are moved to the right side. We assume that every arm whose neighbour node is not in ends at a crossing with the cage. The implementation has a fallback for rounding cases where the crossing is not found, and there the exactness claims hold only up to the rounding.
Exactness on quadratics
Lemma 1. For every polynomial and all : .
Proof. The left side is .
So if is a polynomial whose restriction to each horizontal and each vertical line has degree at most 2, exactly at every node. This holds for , , , , and .
A discrete maximum principle
Lemma 2. Every connected set of nodes of , where two nodes are joined when an arm of one ends at the other, contains a node with an arm that ends on the cage.
Proof. Take the node of the set with the largest , and among those the largest . Its right arm cannot end at a node of , because that node is joined to and has a larger . So it ends on the cage.
Lemma 3. If on with boundary data , then on . If the boundary data are 0, then .
Proof. Let and assume , with . says that is the weighted mean, with the positive weights , of the values at the ends of its four arms. Each end value is : a node value by the choice of , a boundary value because it is . So all end values equal ; in particular no arm of ends on the cage, and every neighbour node in also has the value . Repeating the argument, every node of the connected set of has the value and no arm on the cage, which Lemma 2 forbids. So . With the data 0, the same argument applied to and to gives and .
Theorem 1. The matrix is nonsingular, so each exists and is unique, and at every node.
Proof. If , then solves with the data 0, so by Lemma 3. The data are , so by Lemma 3.
This is the M-matrix property: has a positive diagonal, nonpositive entries off it and . It is also why the LU factorization without pivoting of line L5 is stable: the Schur complements of a nonsingular M-matrix are M-matrices, so every pivot is positive.
Partition of unity and linear precision
Lemma 4. On the cage boundary, and .
Proof. A point on the edge from to at the fraction has , and otherwise. So the sum is 1, and .
Theorem 2. At every node : and .
Proof. The system is linear in the data, so solves with the data , and solves it with the data , which is the coordinate of the boundary point by Lemma 4. applied to the constant 1 or to the coordinate function gives 0 exactly, by Lemma 1, and these functions have the same boundary values. By Theorem 1 the solution is unique, so and ; the same holds for .
Theorem 3. If the cage is an axis-aligned rectangle with the corners as its four vertices, the discrete at every node equal the bilinear coordinates of the rectangle.
Proof. Each bilinear coordinate, such as for the rectangle , is linear on each edge and equals 1 at its corner and 0 at the others, so it agrees with on the boundary. On each horizontal or vertical line it is linear, so of it is 0 by Lemma 1. By uniqueness it is the discrete solution.
Evaluation between nodes
Line L8 interpolates the four corner nodes of the grid cell that holds with the bilinear weights, which are and sum to 1. A corner outside takes at its nearest boundary point , which is and sums to 1 by Lemma 4. So and at every point. If all four corners are in , bilinear interpolation of the nodal values of a linear function gives that function, so . If a corner is not in , its value reproduces instead of ; the segment from to crosses the cage and has the length at most , so , and .
The continuous coordinates
For the exact of the Laplace equation, the weak maximum principle gives , and the strong maximum principle gives inside when is not constant, which holds for a cage with at least three vertices. These are standard facts about harmonic functions and are not proved here.
Complexity
Let be the number of cells across the cage, so there are unknowns. Lines L1 to L4 test each node against the cage and cut each arm in time, so they cost . The band LU of line L5 has a band of width , so it costs time and memory; each solve of line L6 costs , and there are of them. The values take memory. One evaluation of line L8 reads four nodes with values each, plus a nearest boundary point in for outside nodes, so it costs . A multigrid or conjugate gradient solver makes the precomputation close to linear in the number of unknowns; the band LU is used here because it is short and exact up to rounding.
Properties
- Partition of unity (proved). , so a translation of the cage translates the shape.
- Linear precision (proved, at the nodes). at every node, so the rest cage gives the identity there. Between nodes near the boundary, the bilinear interpolation leaves an error of order .
- Nonnegative (proved). at every node, for every simple cage, convex or not.
- Interpolation on the boundary (by definition). On the cage boundary , so the cage edges map linearly onto the moved cage edges.
- Bilinear on rectangles (proved). On an axis-aligned rectangle the discrete coordinates are exactly the bilinear coordinates, because bilinear functions are harmonic and the stencil is exact on them.
- Decay inside the cage (measurement). The coordinate of a vertex is largest near the vertex and small at points that are far from it along paths inside the cage.
- Discretization error (known, not proved here). The Shortley-Weller scheme converges with order for smooth solutions; at reflex corners the exact is not smooth, and the convergence there is slower.
Variants and improvements
- 3D cages. The same definition works for a closed polyhedral cage with triangle faces and linear data on each face; Joshi and others work with 3D character cages.
- Faster solvers. Multigrid, conjugate gradients, Gauss-Seidel or successive over-relaxation replace the band LU for large grids.
- Finite elements. A triangulation of the cage interior with the finite element method follows the boundary exactly instead of cutting grid arms.
- Closed forms. Mean value coordinates are closed form but can be negative, and Green coordinates add the edge normals to keep shapes conformal in 2D.
- Bounded biharmonic weights. Bounded biharmonic weights solve a fourth-order problem with bound constraints, for handles that are points and bones as well as cages.
When to use it
Use harmonic coordinates when the cage is concave, for example a cage around the legs or fingers of a character, and mean value coordinates would let one part pull on another across a gap. The precomputation is heavy but runs once per cage, and after it each point has fixed weights, so posing is as cheap as for any cage. If the cage is convex or nearly so, or if the weights must have a closed form, mean value coordinates are simpler.
Pitfalls
- Grid too coarse. Thin parts of the cage that are narrower than the grid spacing have no interior nodes and get only boundary data; choose well below the smallest feature.
- Nodes on the boundary. A node that lies on the cage within rounding must be treated as a boundary node, or the cut arm has length near 0 and the weight blows up.
- Outside points. The coordinates are defined only inside the cage. Points of the shape that stick out need a cage that encloses them.
- Linear precision between nodes. Near the boundary, the interpolated coordinates reproduce linear functions only up to order , so the rest cage moves such points a little.
- Storage. One value per node per vertex is a lot in 3D; store only the coordinates at the points of the shape after the solve.
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/harmonic-coordinates/. The authors are listed in prov/XS2ZCM.jsonl.
"""Harmonic coordinates of a 2D cage (Joshi, Meyer, DeRose, Green and Sanocki 2007).
The coordinate h_i of cage vertex i is the solution of the Laplace equation
inside the cage, with the boundary value equal to the piecewise linear hat
function of vertex i on the cage boundary. This module solves the equation
on a uniform grid with the Shortley-Weller five-point stencil: an arm of
the stencil that leaves the cage is cut at the first boundary crossing, and
the stencil weights use the shorter arm length. The stencil is exact on
quadratic functions, so the discrete coordinates reproduce linear
functions exactly at the grid nodes. The matrix is an M-matrix, so the
coordinates are nonnegative and the LU factorization needs no pivoting.
The cage is a simple polygon with the vertices in counterclockwise order.
"""
import math
def _cross(ax, ay, bx, by):
return ax * by - ay * bx
def point_in_polygon(p, poly):
"""Even-odd rule. The result on the boundary is not defined; callers test that first."""
x, y = p
inside = False
n = len(poly)
for i in range(n):
(x1, y1), (x2, y2) = poly[i], poly[(i + 1) % n]
if (y1 > y) != (y2 > y):
xc = x1 + (y - y1) * (x2 - x1) / (y2 - y1)
if xc > x:
inside = not inside
return inside
def nearest_on_boundary(p, poly):
"""Return (distance, edge index, s) of the boundary point closest to p."""
best = (math.inf, 0, 0.0)
n = len(poly)
for k in range(n):
(ax, ay), (bx, by) = poly[k], poly[(k + 1) % n]
dx, dy = bx - ax, by - ay
dd = dx * dx + dy * dy
s = min(1.0, max(0.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / dd))
d = math.hypot(p[0] - ax - s * dx, p[1] - ay - s * dy)
if d < best[0]:
best = (d, k, s)
return best
def hat_values(poly, k, s):
"""Return the boundary data of all n coordinates at the point with parameter s on edge k."""
n = len(poly)
out = [0.0] * n
out[k] += 1.0 - s
out[(k + 1) % n] += s
return out
def first_crossing(p, q, poly, eps=1e-12):
"""Return (t, edge index, s) of the first crossing of the segment p + t (q - p), t in (0, 1].
Edges parallel to the segment are skipped; their end points are found
through the neighbouring edges. Return None if there is no crossing.
"""
best = None
n = len(poly)
rx, ry = q[0] - p[0], q[1] - p[1]
for k in range(n):
(ax, ay), (bx, by) = poly[k], poly[(k + 1) % n]
ex, ey = bx - ax, by - ay
den = _cross(rx, ry, ex, ey)
if abs(den) < eps * (abs(rx) + abs(ry)) * (abs(ex) + abs(ey)):
continue
wx, wy = ax - p[0], ay - p[1]
t = _cross(wx, wy, ex, ey) / den
s = _cross(wx, wy, rx, ry) / den
if -eps <= s <= 1 + eps and eps < t <= 1 + eps:
if best is None or t < best[0]:
best = (min(t, 1.0), k, min(1.0, max(0.0, s)))
return best
class BandLU:
"""LU factorization without pivoting of a band matrix, for M-matrices.
The matrix is given as rows of {column: value}. Fill-in stays inside
the band, so the cost is O(N p q) for the factorization and O(N (p + q))
for each solve.
"""
def __init__(self, rows):
self.n = n = len(rows)
p = q = 0
for i, row in enumerate(rows):
for j in row:
p = max(p, i - j)
q = max(q, j - i)
self.p, self.q = p, q
width = p + q + 1
band = [[0.0] * width for _ in range(n)]
for i, row in enumerate(rows):
for j, v in row.items():
band[i][j - i + p] += v
for k in range(n):
piv = band[k][p]
if piv <= 0:
raise ValueError("a pivot is not positive; the matrix is not an M-matrix")
for i in range(k + 1, min(n, k + p + 1)):
lik = band[i][k - i + p]
if lik == 0:
continue
lik /= piv
band[i][k - i + p] = lik
ri, rk = band[i], band[k]
for j in range(k + 1, min(n, k + q + 1)):
ukj = rk[j - k + p]
if ukj != 0:
ri[j - i + p] -= lik * ukj
self.band = band
def solve(self, b):
n, p, q, band = self.n, self.p, self.q, self.band
y = list(b)
for i in range(n):
s = y[i]
for k in range(max(0, i - p), i):
s -= band[i][k - i + p] * y[k]
y[i] = s
for i in range(n - 1, -1, -1):
s = y[i]
for j in range(i + 1, min(n, i + q + 1)):
s -= band[i][j - i + p] * y[j]
y[i] = s / band[i][p]
return y
class HarmonicCoordinates:
"""Discrete harmonic coordinates of a 2D cage on a grid with n_cells cells across."""
def __init__(self, cage, n_cells=32, on_boundary=1e-9):
self.cage = [tuple(map(float, c)) for c in cage]
n = len(self.cage)
xs = [c[0] for c in self.cage]
ys = [c[1] for c in self.cage]
size = max(max(xs) - min(xs), max(ys) - min(ys))
self.h = h = size / n_cells
self.x0, self.y0 = min(xs) - h, min(ys) - h
self.nx = int(math.ceil((max(xs) - self.x0) / h)) + 2
self.ny = int(math.ceil((max(ys) - self.y0) / h)) + 2
tol = on_boundary * size
# L1: the nodes strictly inside the cage are the unknowns.
self.index = {}
for j in range(self.ny): # @line L1
for i in range(self.nx):
p = self.node(i, j)
if nearest_on_boundary(p, self.cage)[0] > tol and point_in_polygon(p, self.cage):
self.index[(i, j)] = len(self.index)
rows, rhs = [], []
for (i, j), r in sorted(self.index.items(), key=lambda kv: kv[1]):
p = self.node(i, j)
row, b = {}, [0.0] * n
diag = 0.0
arms = {}
for di, dj in ((-1, 0), (1, 0), (0, -1), (0, 1)):
q = self.node(i + di, j + dj)
hit = first_crossing(p, q, self.cage) # @line L2
if hit is not None and (hit[0] < 1.0 or (i + di, j + dj) not in self.index):
t, k, s = hit
arms[(di, dj)] = (t * h, hat_values(self.cage, k, s))
elif (i + di, j + dj) in self.index:
arms[(di, dj)] = (h, self.index[(i + di, j + dj)])
else:
d, k, s = nearest_on_boundary(q, self.cage)
arms[(di, dj)] = (h, hat_values(self.cage, k, s))
for lo, hi in (((-1, 0), (1, 0)), ((0, -1), (0, 1))):
hl, hr = arms[lo][0], arms[hi][0]
for arm, length in ((arms[lo], hl), (arms[hi], hr)):
a = 2.0 / (length * (hl + hr)) # @line L3
diag += a
target = arm[1]
if isinstance(target, int):
row[target] = row.get(target, 0.0) - a
else:
for v in range(n):
b[v] += a * target[v] # @line L4
row[r] = diag
rows.append(row)
rhs.append(b)
self.rows, self.rhs = rows, rhs
lu = BandLU(rows) # @line L5
cols = []
for v in range(n):
cols.append(lu.solve([b[v] for b in rhs])) # @line L6
self.values = [[cols[v][r] for v in range(n)] for r in range(len(rows))] # @line L7
def node(self, i, j):
return (self.x0 + i * self.h, self.y0 + j * self.h)
def node_coordinates(self, i, j):
"""Return the n coordinates at grid node (i, j).
Nodes outside the cage or on its boundary take the boundary data at
the closest boundary point.
"""
r = self.index.get((i, j))
if r is not None:
return list(self.values[r])
_, k, s = nearest_on_boundary(self.node(i, j), self.cage)
return hat_values(self.cage, k, s)
def coordinates(self, p):
"""Return the n coordinates at the point p by bilinear interpolation of the nodes."""
fx = (p[0] - self.x0) / self.h
fy = (p[1] - self.y0) / self.h
i = min(max(int(math.floor(fx)), 0), self.nx - 2)
j = min(max(int(math.floor(fy)), 0), self.ny - 2)
a, b = fx - i, fy - j
out = [0.0] * len(self.cage)
for di, dj, w in ((0, 0, (1 - a) * (1 - b)), (1, 0, a * (1 - b)), (0, 1, (1 - a) * b), (1, 1, a * b)):
if w != 0:
for v, c in enumerate(self.node_coordinates(i + di, j + dj)):
out[v] += w * c
return out
def deform(self, p, new_cage):
"""Return sum_i h_i(p) c'_i."""
w = self.coordinates(p)
return (sum(wi * c[0] for wi, c in zip(w, new_cage)), sum(wi * c[1] for wi, c in zip(w, new_cage))) # @line L8
def gauss_seidel(rows, b, iters=5000, tol=1e-13):
"""Solve the same system by Gauss-Seidel iteration. Used by the tests as a second method."""
n = len(rows)
x = [0.0] * n
for _ in range(iters):
change = 0.0
for i, row in enumerate(rows):
s = b[i]
for j, v in row.items():
if j != i:
s -= v * x[j]
new = s / row[i]
change = max(change, abs(new - x[i]))
x[i] = new
if change < tol:
break
return x
test_harmonic_coordinates.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/harmonic-coordinates/. The authors are listed in prov/XS2ZCM.jsonl.
import math
import random
from harmonic_coordinates import BandLU, HarmonicCoordinates, gauss_seidel, point_in_polygon
L_SHAPE = [(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2)]
RECT = [(0, 0), (3, 0), (3, 2), (0, 2)]
STAR = [(math.cos(2 * math.pi * k / 10) * (1.0 if k % 2 == 0 else 0.45), math.sin(2 * math.pi * k / 10) * (1.0 if k % 2 == 0 else 0.45)) for k in range(10)]
_CACHE = {}
def hc(cage, n_cells):
key = (tuple(cage), n_cells)
if key not in _CACHE:
_CACHE[key] = HarmonicCoordinates(cage, n_cells)
return _CACHE[key]
def mvc(p, poly):
"""2D mean value coordinates, for comparison."""
n = len(poly)
d = [(c[0] - p[0], c[1] - p[1]) for c in poly]
r = [math.hypot(*v) for v in d]
tan_half = []
for i in range(n):
a, b = d[i], d[(i + 1) % n]
cr = a[0] * b[1] - a[1] * b[0]
tan_half.append(cr / (r[i] * r[(i + 1) % n] + (a[0] * b[0] + a[1] * b[1])))
w = [(tan_half[i - 1] + tan_half[i]) / r[i] for i in range(n)]
s = sum(w)
return [x / s for x in w]
def test_partition_of_unity_and_nonnegative():
for cage, cells in ((L_SHAPE, 16), (STAR, 20)):
h = hc(cage, cells)
for vals in h.values:
assert abs(sum(vals) - 1) < 1e-12
assert min(vals) >= -1e-14
def test_linear_precision_at_nodes():
for cage, cells in ((L_SHAPE, 16), (STAR, 20)):
h = hc(cage, cells)
for (i, j), r in h.index.items():
x, y = h.node(i, j)
vals = h.values[r]
px = sum(v * c[0] for v, c in zip(vals, cage))
py = sum(v * c[1] for v, c in zip(vals, cage))
assert abs(px - x) < 1e-11 and abs(py - y) < 1e-11
def test_rectangle_gives_bilinear_coordinates():
h = hc(RECT, 12)
for (i, j), r in h.index.items():
x, y = h.node(i, j)
a, b = x / 3, y / 2
want = [(1 - a) * (1 - b), a * (1 - b), a * b, (1 - a) * b]
assert all(abs(u - v) < 1e-12 for u, v in zip(h.values[r], want))
def test_band_lu_matches_gauss_seidel():
h = hc(L_SHAPE, 10)
lu = BandLU(h.rows)
for v in range(len(L_SHAPE)):
b = [row[v] for row in h.rhs]
x1 = lu.solve(b)
x2 = gauss_seidel(h.rows, b)
assert max(abs(a - c) for a, c in zip(x1, x2)) < 1e-10
def test_band_lu_on_random_m_matrix():
rng = random.Random(41)
n = 30
rows = []
for i in range(n):
row = {}
off = 0.0
for j in range(max(0, i - 3), min(n, i + 4)):
if j != i and rng.random() < 0.7:
row[j] = -rng.uniform(0.1, 1.0)
off += -row[j]
row[i] = off + rng.uniform(0.1, 1.0)
rows.append(row)
x = [rng.uniform(-1, 1) for _ in range(n)]
b = [sum(v * x[j] for j, v in row.items()) for row in rows]
y = BandLU(rows).solve(b)
assert max(abs(a - c) for a, c in zip(x, y)) < 1e-12
def test_harmonic_stays_nonnegative_where_mean_value_goes_negative():
h = hc(L_SHAPE, 16)
worst_mvc = 0.0
for (i, j), r in h.index.items():
p = h.node(i, j)
worst_mvc = min(worst_mvc, min(mvc(p, L_SHAPE)))
assert min(h.values[r]) >= -1e-14
assert worst_mvc < -0.009
# The worked example: at (0.875, 1.375) the mean value weight of the
# vertex (2, 1) is about -0.0097, and its harmonic coordinate is positive.
p = (0.875, 1.375)
assert abs(mvc(p, L_SHAPE)[2] + 0.0097336) < 1e-6
r = h.index[(round((p[0] - h.x0) / h.h), round((p[1] - h.y0) / h.h))]
assert 0.003 < h.values[r][2] < 0.0032
def test_interpolation_and_deformation():
h = hc(L_SHAPE, 16)
rng = random.Random(42)
for _ in range(20):
p = (rng.uniform(0, 2), rng.uniform(0, 2))
if not point_in_polygon(p, L_SHAPE):
continue
w = h.coordinates(p)
assert abs(sum(w) - 1) < 1e-12
assert min(w) >= -1e-14
# The identity cage gives back the node, and a translated cage translates it.
(i, j) = next(iter(h.index))
p = h.node(i, j)
q = h.deform(p, L_SHAPE)
assert math.dist(p, q) < 1e-11
moved = [(x + 0.5, y - 0.25) for x, y in L_SHAPE]
q = h.deform(p, moved)
assert math.dist((p[0] + 0.5, p[1] - 0.25), q) < 1e-11
def test_vertex_coordinate_peaks_near_its_vertex():
h = hc(L_SHAPE, 16)
# The coordinate of the reflex vertex (1, 1) is largest close to it.
best = max(h.index.items(), key=lambda kv: h.values[kv[1]][3])
x, y = h.node(*best[0])
assert math.hypot(x - 1, y - 1) < 0.3
History
Joshi, Meyer, DeRose, Green and Sanocki presented harmonic coordinates at SIGGRAPH 2007, from work on character articulation at Pixar. They showed that the mean value coordinates of Ju, Schaefer and Warren (2005) can be negative inside concave cages and proposed the solutions of the Laplace equation instead, computed numerically. Floater (2015) surveys harmonic coordinates together with the other generalized barycentric coordinates.
References
- Pushkar Joshi, Mark Meyer, Tony DeRose, Brian Green and Tom Sanocki, Harmonic coordinates for character articulation, SIGGRAPH 2007, ACM Transactions on Graphics 26(3), article 71, 2007, the whole paper (the definition by the Laplace equation with piecewise linear boundary data, the nonnegativity and the comparison with mean value coordinates on concave cages, and the numerical solution on a grid)
- Michael S. Floater, Generalized barycentric coordinates and applications, Acta Numerica 24, 161-214, 2015, the whole survey (harmonic coordinates among the generalized barycentric coordinates)
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 XS2ZCM Edit this page History Report an error Markdown