Algorithm Search⌘K

Algorithmcore

Free-form deformation

Also called Sederberg-Parry deformation, lattice deformation.

Embed an object in a trivariate Bezier lattice and move its points with the lattice control points, so that any shape deforms smoothly.

Time
Θ(N l m n) allΘ(l m n) per_point
Space
Θ(l m n) extra
Where
N = the number of points to deform; l = the lattice degree along S; m = the lattice degree along T; n = the lattice degree along U
Properties
deterministicexactonlineiterative

Free-form deformation (FFD) bends space, and with it any object that lies in that space. The object sits inside a box with a grid of control points, the lattice. Each point of the object gets its coordinates in the box once, and its new position is a trivariate Bernstein polynomial of those coordinates with the moved control points as coefficients. Thomas Sederberg and Scott Parry (1986) introduced the method. It works for polygon meshes, parametric surfaces and point clouds alike, because it moves points and does not care what they belong to.

In plain words

Put a soft object inside a block of clear jelly. Grab the jelly at a few marked points and pull them. The jelly bends, and the object bends with it, smoothly and without tears. FFD is that jelly. The marked points are the control points of a grid that fills a box around the object. At the start each point of the object is told where it sits in the box, as three numbers between 0 and 1. When the control points move, each object point takes a weighted mix of all the control points, with weights that depend only on those three numbers. If no control point moves, every point stays where it is.

The problem

The input is a lattice and a set of points. The lattice is a parallelepiped with the corner X0X_0 and the edge vectors SS, TT and UU, and the degrees ll, mm and nn. It has the (l+1)(m+1)(n+1)(l + 1)(m + 1)(n + 1) control points PijkP_{ijk}, which start at the regular grid

Pijk=X0+ilS+jmT+knUP_{ijk} = X_0 + \frac{i}{l}S + \frac{j}{m}T + \frac{k}{n}U

and are then moved by the user. The output is the new position X′X' of each point XX. Points inside the lattice should move smoothly with the control points, and the map should be the identity while the lattice is at rest.

The algorithm

Bil(s)=(li)(1−s)l−isiB_i^l(s) = \binom{l}{i}(1 - s)^{l - i}s^i is the Bernstein polynomial of degree ll.

  1. FFD(X, X_0, S, T, U, P)
  2. 1s ← (T × U)·(X - X_0) / ((T × U)·S)
  3. 2t ← (S × U)·(X - X_0) / ((S × U)·T)
  4. 3u ← (S × T)·(X - X_0) / ((S × T)·U)
  5. 4if s, t or u is outside [0, 1] then return X
  6. 5X' ← 0
  7. 6for i ← 0..l, j ← 0..m, k ← 0..n do X' ← X' + B_i^l(s) B_j^m(t) B_k^n(u) P_ijk
  8. 7return X'

Lines L1 to L3 compute the local coordinates, the unique (s,t,u)(s, t, u) with X=X0+sS+tT+uUX = X_0 + sS + tT + uU. Each is a dot product with a fixed vector, so they can be computed once per point and kept while the user edits the lattice. Line L4 leaves the points outside the lattice where they are. Line L6 evaluates the Bezier volume; the de Casteljau algorithm applied along each of the three directions gives the same result.

Example

Take the unit cube as the lattice, with l=m=n=2l = m = n = 2, so it has 27 control points on the grid with spacing 1/21/2. Move only the center control point P111P_{111} from (1/2,1/2,1/2)(1/2, 1/2, 1/2) to (1/2,1/2,1)(1/2, 1/2, 1). Its weight at the center of the cube is B12(1/2)3=(1/2)3=1/8B_1^2(1/2)^3 = (1/2)^3 = 1/8, so the center point moves up by 1/81/8 of 1/21/2, to (1/2,1/2,9/16)(1/2, 1/2, 9/16). At (1/4,1/4,1/4)(1/4, 1/4, 1/4) the weight is B12(1/4)3=(3/8)3=27/512B_1^2(1/4)^3 = (3/8)^3 = 27/512, and the point moves to (1/4,1/4,283/1024)(1/4, 1/4, 283/1024). The corners of the cube do not move, because every Bernstein weight of an inner control point is 0 there. The Jacobian at (1/2,1/2,1/4)(1/2, 1/2, 1/4) is diag⁡(1,1,9/8)\operatorname{diag}(1, 1, 9/8): the region below the moved control point is stretched up by 12.5%12.5\% in volume, and the region above it is compressed. The implementation reproduces these numbers exactly with fractions.Fraction.

Correctness

The Bernstein polynomials satisfy ∑iBil(s)=1\sum_i B_i^l(s) = 1 and ∑iilBil(s)=s\sum_i \frac{i}{l} B_i^l(s) = s. With the control points at rest, line L6 gives X0+sS+tT+uUX_0 + sS + tT + uU, which is XX by lines L1 to L3. So the rest lattice gives the identity, exactly in rational arithmetic. The same two identities show that an affine map AA applied to every control point gives X′=A(X)X' = A(X) for every point inside the lattice. The Jacobian of the map is J=∂X′∂(s,t,u) ∂(s,t,u)∂XJ = \frac{\partial X'}{\partial(s, t, u)}\,\frac{\partial(s, t, u)}{\partial X}, where the rows of the second factor are the three vectors of lines L1 to L3; the volume of a deformed region VV is ∫V∣det⁡J∣ dX\int_V |\det J|\,dX, a statement Sederberg and Parry use to control the volume. The proof gives these arguments and the continuity across the lattice boundary.

Proof: Free-form deformation is the identity at rest, reproduces affine maps, and is continuous across a face whose control points are at restfull

We use the notation of the page. The lattice has the corner X0X_0, the edge vectors SS, TT, UU with (S×T)⋅U≠0(S \times T)\cdot U \ne 0, and the degrees l,m,n≥1l, m, n \ge 1. The map is F(s,t,u)=∑i,j,kBil(s)Bjm(t)Bkn(u)PijkF(s, t, u) = \sum_{i,j,k} B_i^l(s)B_j^m(t)B_k^n(u)P_{ijk} and X′=F(s(X),t(X),u(X))X' = F(s(X), t(X), u(X)) for a point XX inside the lattice.

The local coordinates

Lemma 1. For every point XX, lines L1 to L3 return the unique (s,t,u)(s, t, u) with X=X0+sS+tT+uUX = X_0 + sS + tT + uU.

Proof. SS, TT, UU are linearly independent, so the coefficients exist and are unique. Write X−X0=sS+tT+uUX - X_0 = sS + tT + uU and take the dot product with T×UT \times U. The terms in TT and UU vanish, because T×UT \times U is orthogonal to both, so (T×U)⋅(X−X0)=s (T×U)⋅S(T \times U)\cdot(X - X_0) = s\,(T \times U)\cdot S. The divisor is the triple product ±(S×T)⋅U≠0\pm(S \times T)\cdot U \ne 0, and this is line L1. Lines L2 and L3 follow in the same way with S×US \times U and S×TS \times T. □\square

The Bernstein identities

Lemma 2. For every l≥1l \ge 1 and every real ss: ∑i=0lBil(s)=1\sum_{i=0}^{l} B_i^l(s) = 1 and ∑i=0lilBil(s)=s\sum_{i=0}^{l} \frac{i}{l}B_i^l(s) = s.

Proof. The first sum is ((1−s)+s)l=1((1 - s) + s)^l = 1 by the binomial theorem. For the second, il(li)=(l−1i−1)\frac{i}{l}\binom{l}{i} = \binom{l-1}{i-1} for i≥1i \ge 1, so the sum is s∑i=1l(l−1i−1)(1−s)l−isi−1=s((1−s)+s)l−1=ss\sum_{i=1}^{l}\binom{l-1}{i-1}(1 - s)^{l-i}s^{i-1} = s((1 - s) + s)^{l-1} = s. □\square

Identity and affine invariance

Theorem 1. If every control point is at rest, Pijk=X0+ilS+jmT+knUP_{ijk} = X_0 + \frac{i}{l}S + \frac{j}{m}T + \frac{k}{n}U, then X′=XX' = X for every point XX inside the lattice.

Proof. Write bijk=Bil(s)Bjm(t)Bkn(u)b_{ijk} = B_i^l(s)B_j^m(t)B_k^n(u). By the first identity of Lemma 2 applied three times, ∑bijk=1\sum b_{ijk} = 1, so the X0X_0 terms give X0X_0. The SS terms give S∑iilBil(s)∑jBjm(t)∑kBkn(u)=sSS\sum_i \frac{i}{l}B_i^l(s)\sum_j B_j^m(t)\sum_k B_k^n(u) = sS, and in the same way the TT and UU terms give tTtT and uUuU. So X′=X0+sS+tT+uU=XX' = X_0 + sS + tT + uU = X by Lemma 1. □\square

The proof uses only ring operations on the inputs, so it holds exactly in rational arithmetic, and the implementation checks it with fractions.Fraction.

Theorem 2. Let A(Y)=MY+cA(Y) = MY + c be an affine map. If every control point is moved to A(Pijk)A(P_{ijk}), then X′=A(X)X' = A(X) for every point XX inside the lattice.

Proof. ∑bijkA(Pijk)=M∑bijkPijk+c∑bijk=MX+c\sum b_{ijk}A(P_{ijk}) = M\sum b_{ijk}P_{ijk} + c\sum b_{ijk} = M X + c, by Theorem 1 for the rest points and by ∑bijk=1\sum b_{ijk} = 1. □\square

The Jacobian and the volume

Lemma 3. Inside the lattice, ∂X′∂X=D C\frac{\partial X'}{\partial X} = D\,C, where the columns of DD are ∂F/∂s\partial F/\partial s, ∂F/∂t\partial F/\partial t, ∂F/∂u\partial F/\partial u and the rows of CC are the vectors (T×U)/((T×U)⋅S)(T \times U)/((T \times U)\cdot S), (S×U)/((S×U)⋅T)(S \times U)/((S \times U)\cdot T) and (S×T)/((S×T)⋅U)(S \times T)/((S \times T)\cdot U). The derivative of a Bernstein polynomial is ddsBil(s)=l(Bi−1l−1(s)−Bil−1(s))\frac{d}{ds}B_i^l(s) = l(B_{i-1}^{l-1}(s) - B_i^{l-1}(s)), with B−1l−1=Bll−1=0B_{-1}^{l-1} = B_l^{l-1} = 0.

Proof. (s,t,u)(s, t, u) is a linear function of XX with the matrix CC by Lemma 1, so the chain rule gives DCDC. The derivative formula follows from the product rule and l(l−1i−1)=i(li)l\binom{l-1}{i-1} = i\binom{l}{i}, l(l−1i)=(l−i)(li)l\binom{l-1}{i} = (l - i)\binom{l}{i}. □\square

By the change of variables formula, the deformed image of a region VV inside the lattice, if the map is one to one on VV, has the volume ∫V∣det⁡(DC)∣ dX\int_V |\det(DC)|\,dX. If det⁡(DC)<0\det(DC) < 0 somewhere, the map turns the orientation there, and the object is folded.

Continuity across the lattice boundary

Theorem 3. Take the face s=0s = 0 of the lattice. If the control points P0jkP_{0jk} are at rest, then X′X' is continuous across this face: the points just inside and just outside map to nearby points. If all the control points PijkP_{ijk} with i≤ri \le r are at rest, all derivatives of X′X' of order at most rr agree on both sides of the face.

Proof. At s=0s = 0, Bil(0)=0B_i^l(0) = 0 for i≥1i \ge 1 and B0l(0)=1B_0^l(0) = 1, so F(0,t,u)=∑j,kBjm(t)Bkn(u)P0jkF(0, t, u) = \sum_{j,k} B_j^m(t)B_k^n(u)P_{0jk}. If these points are at rest, this is X0+tT+uUX_0 + tT + uU by Lemma 2, which is the identity, the map outside. For the derivatives, the qq-th derivative in ss of BilB_i^l at s=0s = 0 is 0 for i>qi > q, so ∂sqF(0,t,u)\partial_s^q F(0, t, u) and all its derivatives in tt and uu depend only on the control points with i≤qi \le q. If those with i≤ri \le r are at rest, every mixed derivative of order at most rr at the face equals that of the rest map, which is the identity by Theorem 1. Outside the lattice the map is the identity, so all derivatives of order at most rr match. □\square

If a control point on the face moves, the map jumps at the face, and the object tears there; the implementation leaves points outside the lattice in place, so it shows this jump.

Complexity

Lines L1 to L4 take O(1)O(1) time. The Bernstein values take O(l+m+n)O(l + m + n) time, and line L6 takes Θ(lmn)\Theta(lmn) time, so one point costs Θ(lmn)\Theta(lmn) and NN points cost Θ(N lmn)\Theta(N\,lmn). The lattice holds Θ(lmn)\Theta(lmn) control points. The weights of each point can be stored once, which makes each later edit a sparse matrix product, but the dense weights cost Θ(N lmn)\Theta(N\,lmn) memory.

Properties

  • Identity at rest (proved). The rest lattice gives X′=XX' = X, by the linear precision of the Bernstein basis.
  • Affine invariance (proved). Moving the lattice by an affine map moves the object by the same map.
  • Smooth inside (proved). The map is a polynomial of degree l+m+nl + m + n in XX inside the lattice, so it is C∞C^\infty there.
  • Boundary continuity (proved). The map is continuous across a face of the lattice if the control points on that face are at rest, and CkC^k if the k+1k + 1 outer layers of control points at that face are at rest.
  • Not interpolating. A point at a control point does not follow it: only the corners of the lattice are interpolated.
  • No volume guarantee. The volume changes by det⁡J\det J, which can be negative: a lattice folded too far turns the object inside out.

Variants and improvements

  • Other lattice shapes. Extended free-form deformation (Coquillart 1990) joins Bezier volumes of other shapes, such as cylinders, and finds the local coordinates by Newton iteration.
  • B-spline lattices. A B-spline volume instead of a Bezier volume makes each control point act only on nearby cells, so large lattices stay local and cheap.
  • Direct manipulation. The user drags a point of the object, and a least squares solve finds the control point moves that put it there.
  • Cages. Cage-based deformation replaces the box by a coarse mesh around the object and the Bernstein weights by generalized barycentric coordinates.
  • Simple global maps. Barr's global deformations taper, twist and bend with a closed form and no lattice.

When to use it

Use FFD to shape an object with a few handles when its own representation is detailed, mixed, or not editable, such as a dense mesh or a point cloud. It is the right tool for broad, smooth changes of shape: bulges, bends, squashes. For a shape that should follow a coarse mesh around it, prefer cage-based deformation, whose cage can fit the object closely. For a deformation along a curve, such as a wrinkle or a lip, use wires. For deformations that should keep the local detail of a surface rigid, use a surface method such as Laplacian surface editing or as-rigid-as-possible deformation.

Pitfalls

  • Points outside the lattice. They do not move, so a lattice that cuts through an object tears it unless the boundary layers of control points stay at rest.
  • Folding. A control point moved past its neighbours can make det⁡J<0\det J < 0 and turn part of the object inside out; check the sign of det⁡J\det J if this matters.
  • Normals. Transform normals with the inverse transpose of JJ, not with JJ, as for Barr's deformations.
  • Polygon meshes. FFD moves vertices only, so large curvature on large triangles shows as facets; refine the mesh first.
  • Degree. A high degree makes each control point act on the whole lattice; for local control, raise the number of cells with a spline lattice, not the degree.

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.

free_form_deformation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/free-form-deformation/. The authors are listed in prov/5QACBN.jsonl.
"""Free-form deformation of Sederberg and Parry (1986).

A lattice is a parallelepiped with the corner X0 and the edge vectors S, T
and U. A point X inside it has the local coordinates (s, t, u) in [0, 1]^3
with X = X0 + s S + t T + u U. The lattice holds (l + 1)(m + 1)(n + 1)
control points P[i][j][k]. The deformed point is the trivariate Bernstein
polynomial

    X' = sum_ijk B_i^l(s) B_j^m(t) B_k^n(u) P[i][j][k],

with B_i^l(s) = C(l, i) (1 - s)^(l - i) s^i. In the undeformed lattice,
P[i][j][k] = X0 + (i / l) S + (j / m) T + (k / n) U, and X' = X.

All arithmetic works with int, float or fractions.Fraction. With Fraction
inputs the result is exact.
"""

from fractions import Fraction
from math import comb


def _sub(a, b):
    return tuple(x - y for x, y in zip(a, b))


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 bernstein(deg, x):
    """Return the list [B_0^deg(x), ..., B_deg^deg(x)]."""
    return [comb(deg, i) * (1 - x) ** (deg - i) * x ** i for i in range(deg + 1)]


def bernstein_derivative(deg, x):
    """Return the derivatives d/dx B_i^deg(x) for i = 0..deg."""
    if deg == 0:
        return [0 * x]
    low = bernstein(deg - 1, x)
    out = []
    for i in range(deg + 1):
        a = low[i - 1] if i >= 1 else 0
        b = low[i] if i <= deg - 1 else 0
        out.append(deg * (a - b))
    return out


class Lattice:
    """A parallelepiped lattice of degree (l, m, n) with movable control points."""

    def __init__(self, x0, s_axis, t_axis, u_axis, l, m, n):
        self.x0 = tuple(x0)
        self.axes = (tuple(s_axis), tuple(t_axis), tuple(u_axis))
        self.deg = (l, m, n)
        s, t, u = self.axes
        # Each local coordinate is a dot product with a fixed covector:
        # s = (T x U).(X - X0) / ((T x U).S), and the same for t and u.
        self.covectors = []
        for a, b, c in ((t, u, s), (s, u, t), (s, t, u)):
            w = _cross(a, b)
            den = _dot(w, c)
            if den == 0:
                raise ValueError("the lattice axes are linearly dependent")
            self.covectors.append(tuple(_div(x, den) for x in w))
        self.points = self.rest_points()

    def rest_points(self):
        """Return the control points of the undeformed lattice."""
        l, m, n = self.deg
        s, t, u = self.axes
        pts = []
        for i in range(l + 1):
            plane = []
            for j in range(m + 1):
                row = []
                for k in range(n + 1):
                    row.append(tuple(
                        self.x0[d] + _frac(i, l) * s[d] + _frac(j, m) * t[d] + _frac(k, n) * u[d]
                        for d in range(3)
                    ))
                plane.append(row)
            pts.append(plane)
        return pts

    def local(self, x):
        """Return the local coordinates (s, t, u) of the point x."""
        r = _sub(x, self.x0)
        return tuple(_dot(c, r) for c in self.covectors)

    def deform(self, x):
        """Return the deformed position of x. Points outside the lattice do not move."""
        r = _sub(x, self.x0)
        s = _dot(self.covectors[0], r)  # @line L1
        t = _dot(self.covectors[1], r)  # @line L2
        u = _dot(self.covectors[2], r)  # @line L3
        if not (0 <= s <= 1 and 0 <= t <= 1 and 0 <= u <= 1):  # @line L4
            return tuple(x)
        return self.evaluate(s, t, u)

    def evaluate(self, s, t, u):
        """Return sum_ijk B_i^l(s) B_j^m(t) B_k^n(u) P[i][j][k]."""
        l, m, n = self.deg
        bs, bt, bu = bernstein(l, s), bernstein(m, t), bernstein(n, u)
        out = [0 * s, 0 * s, 0 * s]  # @line L5
        for i in range(l + 1):
            for j in range(m + 1):
                wij = bs[i] * bt[j]
                for k in range(n + 1):  # @line L6
                    w = wij * bu[k]
                    p = self.points[i][j][k]
                    out[0] += w * p[0]
                    out[1] += w * p[1]
                    out[2] += w * p[2]
        return tuple(out)  # @line L7

    def jacobian(self, x):
        """Return the 3 by 3 matrix dX'/dX at a point x inside the lattice.

        By the chain rule, dX'/dX = (dX'/d(s, t, u)) (d(s, t, u)/dX), and the
        second factor has the three covectors as its rows.
        """
        l, m, n = self.deg
        s, t, u = self.local(x)
        bs, bt, bu = bernstein(l, s), bernstein(m, t), bernstein(n, u)
        ds, dt, du = bernstein_derivative(l, s), bernstein_derivative(m, t), bernstein_derivative(n, u)
        cols = [[0 * s] * 3 for _ in range(3)]
        for i in range(l + 1):
            for j in range(m + 1):
                for k in range(n + 1):
                    p = self.points[i][j][k]
                    ws = (ds[i] * bt[j] * bu[k], bs[i] * dt[j] * bu[k], bs[i] * bt[j] * du[k])
                    for a in range(3):
                        for d in range(3):
                            cols[a][d] += ws[a] * p[d]
        # cols[a] is the derivative by the local coordinate a.
        return [[sum(cols[a][r] * self.covectors[a][c] for a in range(3)) for c in range(3)] for r in range(3)]


def _frac(i, n):
    """Return i / n as a Fraction; a degree of 0 gives 0."""
    if n == 0:
        return Fraction(0)
    return Fraction(i, n)


def _div(x, d):
    """Return x / d, as an exact Fraction when both are int."""
    if isinstance(x, int) and isinstance(d, int):
        return Fraction(x, d)
    return x / d


def det3(a):
    """Return the determinant of a 3 by 3 matrix."""
    return (
        a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
        - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
        + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
    )


def de_casteljau_volume(points, s, t, u):
    """Evaluate the same trivariate Bezier volume by repeated linear interpolation.

    This is an independent second method, used by the tests.
    """

    def lerp_list(pts, x):
        while len(pts) > 1:
            pts = [tuple((1 - x) * a + x * b for a, b in zip(p, q)) for p, q in zip(pts, pts[1:])]
        return pts[0]

    rows = []
    for plane in points:
        cols = [lerp_list(list(row), u) for row in plane]
        rows.append(lerp_list(cols, t))
    return lerp_list(rows, s)
test_free_form_deformation.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/free-form-deformation/. The authors are listed in prov/5QACBN.jsonl.
import random
from fractions import Fraction as F

from free_form_deformation import Lattice, bernstein, de_casteljau_volume, det3


def unit_lattice(l=2, m=2, n=2):
    return Lattice((0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), l, m, n)


def skew_lattice(l, m, n):
    return Lattice((1, -2, 3), (2, 1, 0), (F(1, 2), 3, 1), (0, 1, 4), l, m, n)


def rand_point_inside(lat, rng):
    s, t, u = (F(rng.randint(0, 64), 64) for _ in range(3))
    a, b, c = lat.axes
    return tuple(lat.x0[d] + s * a[d] + t * b[d] + u * c[d] for d in range(3))


def test_bernstein_partition_of_unity():
    for deg in range(6):
        for x in (F(0), F(1, 3), F(5, 7), F(1)):
            assert sum(bernstein(deg, x)) == 1


def test_local_coordinates_are_inverse_of_embedding():
    lat = skew_lattice(3, 2, 1)
    rng = random.Random(1)
    for _ in range(20):
        s, t, u = (F(rng.randint(-10, 10), 7) for _ in range(3))
        a, b, c = lat.axes
        x = tuple(lat.x0[d] + s * a[d] + t * b[d] + u * c[d] for d in range(3))
        assert lat.local(x) == (s, t, u)


def test_rest_lattice_is_exact_identity():
    rng = random.Random(2)
    for deg in ((1, 1, 1), (2, 2, 2), (3, 2, 1), (4, 1, 3)):
        lat = skew_lattice(*deg)
        for _ in range(10):
            x = rand_point_inside(lat, rng)
            assert lat.deform(x) == x


def test_affine_motion_of_lattice_is_reproduced_exactly():
    rng = random.Random(3)
    a = [[F(rng.randint(-5, 5), 3) for _ in range(3)] for _ in range(3)]
    b = [F(rng.randint(-5, 5), 2) for _ in range(3)]

    def aff(p):
        return tuple(sum(a[r][c] * p[c] for c in range(3)) + b[r] for r in range(3))

    lat = skew_lattice(3, 2, 2)
    lat.points = [[[aff(p) for p in row] for row in plane] for plane in lat.points]
    for _ in range(10):
        x = rand_point_inside(lat, rng)
        assert lat.deform(x) == aff(x)


def test_matches_de_casteljau():
    rng = random.Random(4)
    lat = unit_lattice(3, 2, 4)
    lat.points = [[[tuple(F(rng.randint(-20, 20), 5) for _ in range(3)) for _ in row] for row in plane] for plane in lat.points]
    for _ in range(10):
        s, t, u = (F(rng.randint(0, 30), 30) for _ in range(3))
        assert lat.evaluate(s, t, u) == de_casteljau_volume(lat.points, s, t, u)


def test_worked_example_center_point():
    lat = unit_lattice(2, 2, 2)
    lat.points[1][1][1] = (F(1, 2), F(1, 2), F(1))
    y = lat.deform((F(1, 2), F(1, 2), F(1, 2)))
    assert y == (F(1, 2), F(1, 2), F(9, 16))
    assert all(isinstance(v, F) for v in y)
    assert lat.deform((F(1, 4), F(1, 4), F(1, 4))) == (F(1, 4), F(1, 4), F(283, 1024))
    # Below the center the lattice is stretched along z: det J = 9/8 at (1/2, 1/2, 1/4).
    assert det3(lat.jacobian((F(1, 2), F(1, 2), F(1, 4)))) == F(9, 8)
    # The corner points of the lattice do not move.
    assert lat.deform((0, 0, 0)) == (0, 0, 0)
    assert lat.deform((1, 1, 1)) == (1, 1, 1)


def test_point_outside_does_not_move():
    lat = unit_lattice()
    lat.points[1][1][1] = (F(1, 2), F(1, 2), F(3))
    for x in ((F(-1, 10), F(1, 2), F(1, 2)), (2, 0, 0), (F(1, 2), F(1, 2), F(11, 10))):
        assert lat.deform(x) == x


def test_jacobian_matches_finite_differences():
    rng = random.Random(5)
    lat = skew_lattice(2, 3, 2)
    lat.points = [[[tuple(float(v) + rng.uniform(-0.3, 0.3) for v in p) for p in row] for row in plane] for plane in lat.points]
    h = 1e-6
    for _ in range(5):
        x = tuple(float(v) for v in rand_point_inside(lat, rng))
        s, t, u = lat.local(x)
        if not all(0.01 < c < 0.99 for c in (s, t, u)):
            continue
        j = lat.jacobian(x)
        for c in range(3):
            xp = list(x)
            xm = list(x)
            xp[c] += h
            xm[c] -= h
            fp, fm = lat.deform(xp), lat.deform(xm)
            for r in range(3):
                assert abs((fp[r] - fm[r]) / (2 * h) - j[r][c]) < 1e-6


def test_rest_jacobian_is_identity_and_affine_det_is_volume_ratio():
    lat = skew_lattice(2, 2, 2)
    x = rand_point_inside(lat, random.Random(6))
    j = lat.jacobian(x)
    assert j == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    scale = (2, 3, F(1, 2))
    lat.points = [[[tuple(scale[d] * p[d] for d in range(3)) for p in row] for row in plane] for plane in lat.points]
    assert det3(lat.jacobian(x)) == 3

History

Sederberg and Parry presented FFD at SIGGRAPH 1986 as a tool for solid modeling. They took the lattice from Bezier volumes and showed that the method keeps the algebraic form of the object (a deformed polynomial surface stays polynomial), and that the volume change is the Jacobian determinant. Barr's global deformations of 1984 were the earlier closed-form space deformations. Coquillart (1990) extended the lattice to other shapes, and later work moved from lattices to cages and to surface-based methods.

References

  1. Thomas W. Sederberg and Scott R. Parry, Free-form deformation of solid geometric models, SIGGRAPH 86, Computer Graphics 20(4), 151-160, 1986, the whole paper (the parallelepiped lattice, the local coordinates, the trivariate Bernstein polynomial, the volume change and the continuity across the lattice boundary)
  2. Sabine Coquillart, Extended free-form deformation: a sculpturing tool for 3D geometric modeling, SIGGRAPH 90, Computer Graphics 24(4), 187-196, 1990, the whole paper (lattices that are not parallelepipeds)

Where this leads

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.all
  • a full proof of time.per_point
  • a full proof of space.extra
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
  • History with a source
  • at least three sources
  • a scene preset for the example