Algorithmadvanced
Green coordinates
Also called Green cage coordinates.
Cage coordinates from Green's third identity that use both the cage vertices and face normals, giving conformal deformations in 2D.
- Solves
- Shape deformation
- Time
- Θ(N n) allΘ(n) per_point
- Space
- Θ(n) extra
- Where
- N = the number of points to deform; n = the number of cage vertices and edges
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
Green coordinates are cage coordinates with two kinds of weights: one weight per cage vertex and one weight per cage edge, or per face in 3D. A point inside the cage moves to , where are the moved vertices, the moved edge normals, and the factor by which edge grew. The weights come from Green's third identity applied to the coordinate functions, and they have closed forms. Yaron Lipman, David Levin and Daniel Cohen-Or (2008) introduced them. The normal terms make the difference: in 2D the deformation is a conformal map, so small shapes inside the cage keep their angles, where other cage coordinates shear them.
In plain words
Other cage methods move a point by a weighted mix of the cage corners. Green coordinates also listen to the sides of the cage: how each side turns, and how much it stretches. If a side turns, the points near it turn with it, and if it gets longer, the shape near it grows in both directions, not only along the side. That is why a small circle drawn inside the shape stays a small circle, only moved, turned and resized, even when the cage bends. The price is that the shape no longer touches the cage exactly: the moved cage is a guide, not a hard wall.
The problem
The input is a cage, a simple polygon in counterclockwise order, with edge from to and its outward unit normal , and a point inside it. The output is the weights and such that
and the deformed point for a moved cage . With and the hat function of vertex on the boundary, the weights are
The algorithm
On edge with and , let . The integrals , and have closed forms with one arctangent and two logarithms.
GREEN(η, v)- 1
φ ← 0, ψ ← 0 - 2
for each edge j from a = v_j to b = v_{j+1} do - 3
n_j ← the outward unit normal of edge j - 4
h ← (a - η) · n_j - 5
compute I_0, I_1 and Λ for edge j - 6
φ_j ← φ_j + (h|b - a|/2π)(I_0 - I_1); φ_{j+1} ← φ_{j+1} + (h|b - a|/2π) I_1 - 7
ψ_j ← -(|b - a|/4π) Λ - 8
return φ, ψ DEFORM(η, v, v')- 9
return Σ_i φ_i v'_i + Σ_j ψ_j s_j n'_j, with s_j = |v'_{j+1} - v'_j| / |v_{j+1} - v_j|
Line L4 uses that is the same for every on edge , so there. Line L6 splits the integral of line L4 between the two ends of the edge with the hat functions and . Line L7 uses . With and : , , and . If is on the line of the edge, and only is needed, without the term in .
Example
For the unit square and its center , symmetry gives for every vertex, and every edge has . The four normals sum to 0, so , as it must. Now shear the cage by . The center goes to , which is the sheared center. But the point goes to about , not to the sheared point : a shear is not conformal, so Green coordinates cannot reproduce it. A rotation with a scale and a translation of the cage, on the other hand, moves every inside point by exactly the same map; the tests check this on an L-shaped cage.
Correctness
The proof proves the following. Green's third identity says that a function that is harmonic inside satisfies . For this gives , and for , with and on the boundary, it gives . If the moved cage is with a rotation times a scale , then and , so line L9 returns : similarities are reproduced. In complex notation, the map of line L9 equals the Cauchy integral of the piecewise linear map of the cage onto the moved cage, by an integration by parts on each edge. A Cauchy integral is holomorphic inside the cage, so the deformation is conformal wherever its derivative is not 0. The tests check the closed forms against Gauss-Legendre quadrature, the equality with the Cauchy integral, and the Cauchy-Riemann equations by finite differences.
Proof: Green coordinates reproduce the point and the constants, reproduce similarities, and give a holomorphic map in 2Dfull
We use the notation of the page. is the inside of the cage, , and , which satisfies . On edge we write with and , so .
The closed forms of lines L4 to L7
Lemma 1. On edge , for every on the edge, , and .
Proof. , and . , so . The last claim is .
So gets from edge , and gets , which is line L6. And , which is line L7. The antiderivatives of , and for a quadratic with no real zero are standard; the tests compare the closed forms with Gauss-Legendre quadrature on 384 points per edge.
Reproduction
Theorem 1. For every : and .
Proof. Green's second identity on for a function that is harmonic on a neighbourhood of the closure of , and for , gives Green's third identity:
For the second term is 0, and on the boundary, so . For , applied to each coordinate, on edge , and on the boundary, because and on edge . So .
Corollary. With , line L9 returns , because then and .
Similarities
Theorem 2. Let for every , where with a rotation and . Then line L9 returns .
Proof. Every edge vector becomes , so , and the outward normal becomes , because is a rotation and keeps the orientation. So , and line L9 gives , by Theorem 1.
The map is a Cauchy integral
We identify with . Let be the piecewise linear map of the cage boundary onto the moved cage: on edge , , with and . So on edge with . For a counterclockwise cage, the outward normal of edge is , and then .
Lemma 2. On edge , with : and , the derivative of along the edge.
Proof. . Its imaginary part is , and for , because and . So the imaginary part is by Lemma 1. Its real part is .
Theorem 3. Line L9 returns .
Proof. for every complex . So, by Lemma 2,
Integrate the last term by parts: , and . So . Sum over all edges. The bracket terms cancel, because and are continuous at every vertex and the boundary is closed. The first terms add up to , since on the boundary. So the sum is , which is line L9.
Corollary (conformal in 2D). is holomorphic in , so it satisfies the Cauchy-Riemann equations, and it keeps angles at every point where .
Proof. is bounded on the boundary, and is holomorphic in with derivatives bounded uniformly for in a compact subset of , so differentiation under the integral sign shows that is complex differentiable in . A holomorphic map with is conformal.
Theorem 3 also explains Theorem 2 and the shear of the example: if extends to a holomorphic map on , Cauchy's formula gives ; a similarity is holomorphic, while a shear is not, and it is not reproduced.
Complexity
Each edge costs , with two logarithms and two arctangents, so the weights of one point take time and line L9 takes . points cost ; storing the weights takes memory, and the work per point needs . There is no precomputation beyond the weights: unlike harmonic coordinates there is no grid and no solve.
Properties
- Reproduction and partition of unity (proved). and , so the rest cage gives the identity.
- Similarities reproduced (proved). Rotating, scaling and moving the cage does the same to the shape.
- Conformal in 2D (proved). The map is holomorphic inside the cage; it keeps angles wherever its derivative is not 0.
- General affine maps not reproduced (proved by the example). A shear or a scale in one direction of the cage is not a conformal map, so the inside follows it only roughly.
- Not interpolating. The deformed shape does not pass through the moved cage vertices, and points near the cage do not follow the cage boundary exactly. A Cauchy integral has the boundary values only when extends to a holomorphic map, as for a similarity.
- Signed weights (measurement). can be negative for concave cages: on a grid of step inside the L-shaped cage of the tests, the smallest is about . has no fixed sign. Because of the normal terms, the weights are not barycentric coordinates in the strict sense.
- 3D quasi-conformal (stated by the paper, not checked here). In 3D, with triangle faces in place of edges, Lipman, Levin and Cohen-Or describe the map as quasi-conformal; no 3D code or proof is on this page.
Variants and improvements
- 3D cages. The same identity with triangle faces gives weights per vertex and per face, with closed forms over triangles.
- Complex coordinates. In 2D, writing the map as a Cauchy integral leads to complex-valued cage coordinates, and to other holomorphic choices of the boundary map than the piecewise linear one.
- Harmonic and mean value coordinates. Harmonic coordinates and mean value coordinates use vertex weights only; they reproduce all affine maps and interpolate the cage, but do not keep angles.
- Rigid shapes by optimization. As-rigid-as-possible shape manipulation keeps local shapes by a solve over a mesh instead of a closed form.
When to use it
Use Green coordinates when a cage should bend a shape while keeping its details from shearing, as for the face of a cartoon character, text on a curved band or a pattern on a surface. They cost the same as other closed-form cage coordinates. Do not use them when the shape must follow the cage exactly, or when the user expects an affine edit of the cage, such as a stretch along one axis, to stretch the shape the same way.
Pitfalls
- Orientation. The formulas assume a counterclockwise cage with outward normals; a clockwise cage flips the signs of and of the normals.
- Points on the boundary. On an edge, has a zero and a singularity, and the weights are not defined. Keep the shape strictly inside the cage.
- Cancellation. Compute as , not as , which loses many digits near the line of the edge.
- Forgetting . Without the edge stretch , a uniformly scaled cage no longer scales the shape.
- Large edits. Conformal maps can grow or shrink a region a lot; a cage that is pinched hard shrinks the shape near the pinch strongly.
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/green-coordinates/. The authors are listed in prov/2QKV5N.jsonl.
"""2D Green coordinates (Lipman, Levin and Cohen-Or 2008).
The cage is a simple polygon v_0..v_{n-1} in counterclockwise order. Edge j
runs from v_j to v_{j+1} and has the outward unit normal n_j. For a point
eta inside the cage, Green's third identity applied to the coordinate
functions gives
eta = sum_i phi_i(eta) v_i + sum_j psi_j(eta) n_j,
with G(xi, eta) = (1 / 2 pi) ln |xi - eta| and
phi_i = integral over the two edges at v_i of Gamma_i(xi) dG/dn(xi, eta),
psi_j = - integral over edge j of G(xi, eta),
where Gamma_i is the hat function of v_i on the boundary. The integrals
have closed forms, computed below. The deformed point is
f(eta) = sum_i phi_i v'_i + sum_j psi_j s_j n'_j, s_j = |e'_j| / |e_j|.
"""
import math
TWO_PI = 2.0 * math.pi
def outward_normal(a, b):
"""Return the outward unit normal of the edge a -> b of a counterclockwise polygon."""
dx, dy = b[0] - a[0], b[1] - a[1]
ln = math.hypot(dx, dy)
return (dy / ln, -dx / ln)
def edge_integrals(a, b, eta, eps=1e-14):
"""Return (I0, I1, L) for the edge a -> b and the point eta.
With xi(t) = a + t (b - a) and q(t) = |xi(t) - eta|^2 = Q t^2 + R t + S:
I0 = int_0^1 dt / q(t), I1 = int_0^1 t dt / q(t), L = int_0^1 ln q(t) dt.
"""
dx, dy = b[0] - a[0], b[1] - a[1]
wx, wy = a[0] - eta[0], a[1] - eta[1]
q = dx * dx + dy * dy
r = 2.0 * (wx * dx + wy * dy)
s = wx * wx + wy * wy
srt = 2.0 * abs(dx * wy - dy * wx) # sqrt(4 Q S - R^2), computed without cancellation
l0 = math.log(s)
l1 = math.log(q + r + s)
l10 = l1 - l0
if srt <= eps * q:
# eta lies on the line of the edge (but not on the edge): h = 0, so
# I0 and I1 are not needed, and the arctangent term of L vanishes.
return 0.0, 0.0, l1 + r / (2 * q) * l10 - 2.0
a10 = (math.atan((2 * q + r) / srt) - math.atan(r / srt)) / srt
i0 = 2.0 * a10
i1 = l10 / (2 * q) - (r / q) * a10
big_l = l1 + r / (2 * q) * l10 - 2.0 + (4 * s - r * r / q) * a10
return i0, i1, big_l
def green_coordinates(eta, cage):
"""Return (phi, psi): n vertex coordinates and n edge coordinates."""
n = len(cage)
phi = [0.0] * n # @line L1
psi = [0.0] * n
for j in range(n): # @line L2
a, b = cage[j], cage[(j + 1) % n]
nx, ny = outward_normal(a, b) # @line L3
length = math.hypot(b[0] - a[0], b[1] - a[1])
h = (a[0] - eta[0]) * nx + (a[1] - eta[1]) * ny # @line L4
i0, i1, big_l = edge_integrals(a, b, eta) # @line L5
c = h * length / TWO_PI
phi[j] += c * (i0 - i1) # @line L6
phi[(j + 1) % n] += c * i1
psi[j] = -length / (2 * TWO_PI) * big_l # @line L7
return phi, psi # @line L8
def deform(eta, cage, new_cage):
"""Return f(eta) for the moved cage new_cage."""
phi, psi = green_coordinates(eta, cage)
n = len(cage)
x = sum(p * v[0] for p, v in zip(phi, new_cage))
y = sum(p * v[1] for p, v in zip(phi, new_cage))
for j in range(n):
a, b = cage[j], cage[(j + 1) % n]
a2, b2 = new_cage[j], new_cage[(j + 1) % n]
s = math.hypot(b2[0] - a2[0], b2[1] - a2[1]) / math.hypot(b[0] - a[0], b[1] - a[1])
nx, ny = outward_normal(a2, b2)
x += psi[j] * s * nx # @line L9
y += psi[j] * s * ny
return (x, y)
test_green_coordinates.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/green-coordinates/. The authors are listed in prov/2QKV5N.jsonl.
import math
import random
from green_coordinates import deform, edge_integrals, green_coordinates, outward_normal
L_SHAPE = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (1.0, 1.0), (1.0, 2.0), (0.0, 2.0)]
SQUARE = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
def gauss_legendre(m):
"""Nodes and weights on [0, 1], by Newton's method on the Legendre polynomial."""
xs, ws = [], []
for k in range(1, m + 1):
x = math.cos(math.pi * (k - 0.25) / (m + 0.5))
for _ in range(100):
p0, p1 = 1.0, x
for j in range(2, m + 1):
p0, p1 = p1, ((2 * j - 1) * x * p1 - (j - 1) * p0) / j
dp = m * (x * p1 - p0) / (x * x - 1)
dx = p1 / dp
x -= dx
if abs(dx) < 1e-16:
break
xs.append((1 - x) / 2)
ws.append(1 / ((1 - x * x) * dp * dp))
return xs, ws
GX, GW = gauss_legendre(24)
def quad(f, pieces=16):
total = 0.0
for p in range(pieces):
for x, w in zip(GX, GW):
total += f((p + x) / pieces) * w / pieces
return total
def inside_points(rng, cage, count):
from math import isclose
out = []
while len(out) < count:
p = (rng.uniform(0.05, 1.95), rng.uniform(0.05, 1.95))
if cage is L_SHAPE and p[0] > 0.95 and p[1] > 0.95:
continue
if cage is SQUARE and not (0.05 < p[0] < 0.95 and 0.05 < p[1] < 0.95):
continue
if not isclose(p[0], 1.0, abs_tol=0.05) or cage is SQUARE:
out.append(p)
return out
def test_closed_form_matches_quadrature():
rng = random.Random(51)
for eta in inside_points(rng, L_SHAPE, 8):
for j in range(len(L_SHAPE)):
a, b = L_SHAPE[j], L_SHAPE[(j + 1) % len(L_SHAPE)]
def q(t):
x, y = a[0] + t * (b[0] - a[0]) - eta[0], a[1] + t * (b[1] - a[1]) - eta[1]
return x * x + y * y
i0, i1, big_l = edge_integrals(a, b, eta)
assert abs(i0 - quad(lambda t: 1 / q(t))) < 1e-10
assert abs(i1 - quad(lambda t: t / q(t))) < 1e-10
assert abs(big_l - quad(lambda t: math.log(q(t)))) < 1e-10
def test_point_on_line_of_edge():
# The point (1, 0.5) lies on the line x = 1 of the edge (1, 1) -> (1, 2), below the edge.
a, b, eta = (1.0, 1.0), (1.0, 2.0), (1.0, 0.5)
i0, i1, big_l = edge_integrals(a, b, eta)
want = quad(lambda t: math.log((0.5 + t) ** 2))
assert abs(big_l - want) < 1e-10
def test_partition_of_unity_and_reproduction():
rng = random.Random(52)
for cage in (L_SHAPE, SQUARE):
for eta in inside_points(rng, cage, 15):
phi, psi = green_coordinates(eta, cage)
assert abs(sum(phi) - 1) < 1e-12
x = sum(p * v[0] for p, v in zip(phi, cage))
y = sum(p * v[1] for p, v in zip(phi, cage))
for j in range(len(cage)):
nx, ny = outward_normal(cage[j], cage[(j + 1) % len(cage)])
x += psi[j] * nx
y += psi[j] * ny
assert abs(x - eta[0]) < 1e-12 and abs(y - eta[1]) < 1e-12
def similarity(p, ang=0.7, sc=1.6, t=(0.3, -1.2)):
c, s = math.cos(ang), math.sin(ang)
return (sc * (c * p[0] - s * p[1]) + t[0], sc * (s * p[0] + c * p[1]) + t[1])
def test_similarity_is_reproduced_and_shear_is_not():
rng = random.Random(53)
moved = [similarity(v) for v in L_SHAPE]
for eta in inside_points(rng, L_SHAPE, 10):
assert math.dist(deform(eta, L_SHAPE, moved), similarity(eta)) < 1e-11
sheared = [(x + 0.5 * y, y) for x, y in SQUARE]
eta = (0.5, 0.5)
f = deform(eta, SQUARE, sheared)
assert math.dist(f, (0.75, 0.5)) < 1e-12
eta = (0.25, 0.3)
f = deform(eta, SQUARE, sheared)
assert math.dist(f, (eta[0] + 0.5 * eta[1], eta[1])) > 1e-3
def cauchy(eta, cage, new_cage):
"""Return (1 / 2 pi i) times the integral over the old cage of g(xi) / (xi - eta).
Here g is the piecewise linear boundary image: g(a + t (b - a)) = a' + t (b' - a').
"""
z = complex(*eta)
total = 0j
n = len(cage)
for j in range(n):
a, b = complex(*cage[j]), complex(*cage[(j + 1) % n])
a2, b2 = complex(*new_cage[j]), complex(*new_cage[(j + 1) % n])
total += quad(lambda t: ((a2 + t * (b2 - a2)) / (a + t * (b - a) - z)).real) * (b - a)
total += 1j * quad(lambda t: ((a2 + t * (b2 - a2)) / (a + t * (b - a) - z)).imag) * (b - a)
return total / (2j * math.pi)
def test_equals_cauchy_integral_of_boundary_image():
rng = random.Random(54)
moved = [(x + rng.uniform(-0.3, 0.3), y + rng.uniform(-0.3, 0.3)) for x, y in L_SHAPE]
for eta in inside_points(rng, L_SHAPE, 6):
f = deform(eta, L_SHAPE, moved)
g = cauchy(eta, L_SHAPE, moved)
assert abs(complex(*f) - g) < 1e-9
def test_cauchy_riemann_so_the_map_is_conformal():
rng = random.Random(55)
moved = [(x + rng.uniform(-0.3, 0.3), y + rng.uniform(-0.3, 0.3)) for x, y in L_SHAPE]
h = 1e-5
for eta in inside_points(rng, L_SHAPE, 6):
fx1 = deform((eta[0] + h, eta[1]), L_SHAPE, moved)
fx0 = deform((eta[0] - h, eta[1]), L_SHAPE, moved)
fy1 = deform((eta[0], eta[1] + h), L_SHAPE, moved)
fy0 = deform((eta[0], eta[1] - h), L_SHAPE, moved)
ux, vx = (fx1[0] - fx0[0]) / (2 * h), (fx1[1] - fx0[1]) / (2 * h)
uy, vy = (fy1[0] - fy0[0]) / (2 * h), (fy1[1] - fy0[1]) / (2 * h)
assert abs(ux - vy) < 1e-7
assert abs(uy + vx) < 1e-7
def test_worked_example():
# The center of the unit square. By symmetry each phi_i is 1/4.
phi, psi = green_coordinates((0.5, 0.5), SQUARE)
assert all(abs(p - 0.25) < 1e-12 for p in phi)
want = -(1 / (4 * math.pi)) * quad(lambda t: math.log((t - 0.5) ** 2 + 0.25))
assert all(abs(p - want) < 1e-12 for p in psi)
assert abs(psi[0] - 0.0893138431) < 1e-9
# A shear of the cage is not reproduced inside.
sheared = [(x + 0.5 * y, y) for x, y in SQUARE]
f = deform((0.25, 0.3), SQUARE, sheared)
assert abs(f[0] - 0.4468487) < 1e-6 and abs(f[1] - 0.3609747) < 1e-6
History
Lipman, Levin and Cohen-Or presented Green coordinates at SIGGRAPH 2008, after mean value coordinates (Ju, Schaefer and Warren 2005) and harmonic coordinates (Joshi and others 2007) had made cages a common deformation tool. They presented the coordinates as shape preserving: other cage coordinates reproduce affine maps, and so they shear details, while Green coordinates keep angles in 2D. The equality of 2D Green coordinates with a Cauchy integral connects them with complex analysis.
References
- Yaron Lipman, David Levin and Daniel Cohen-Or, Green coordinates, SIGGRAPH 2008, ACM Transactions on Graphics 27(3), 2008, the whole paper (the coordinates from Green's third identity, the scaled normals of the deformed cage, and the conformal and quasi-conformal behaviour in 2D and 3D)
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 2QKV5N Edit this page History Report an error Markdown