Algorithm Search⌘K

Algorithmcore

Surface skinning

Also called lofting, lofted surface.

Builds a B-spline surface through an ordered set of section curves, after making them compatible in degree and knot vector, by interpolating across them.

Time
O(K^3 + K^2 n + K n^2) worst
Space
Θ(K n) extra
Where
K = the number of sections minus one; n = the number of control points of a section after the knot merge, minus one
Properties
deterministicofflineiterative
Origin
Charles D. Woodward, 1988

Skinning, also called lofting, builds one surface through an ordered list of section curves C0(u),…,CK(u)C_0(u), \dots, C_K(u). The surface S(u,v)S(u, v) contains each section as an iso-curve: S(u,vk)=Ck(u)S(u, v_k) = C_k(u) for chosen parameters v0<⋯<vKv_0 < \dots < v_K. With B-spline sections the method has three steps. It makes the sections compatible, so that all have the same degree and the same knot vector. It chooses the parameters vkv_k. Then it interpolates each column of control points across the sections with a B-spline curve in vv. The result is one tensor product B-spline surface, and the proof that it holds every section is one line once the sections share a knot vector.

In plain words

Think of the frames of a boat, cut from wood and set up in a row. A thin sheet bent over all the frames gives the hull. Skinning does this with curves. Each frame is a curve with its own control points. First the method gives every frame the same number of control points, in the same arrangement, without changing its shape. Now the first control points of all frames form a row from the bow to the stern, and so do the second ones, and so on. The method draws a smooth curve through each such row. These curves together are the control points of a surface, and that surface passes through every frame. Between the frames the surface takes the shape of the smooth rows.

The problem

Input. Section curves C0,…,CKC_0, \dots, C_K, K≥1K \ge 1, each a clamped B-spline curve of one degree pp on the same parameter interval, with its own knot vector. A degree qq in vv. Optionally, parameters v0<⋯<vKv_0 < \dots < v_K.

Output. A B-spline surface S(u,v)S(u, v) of degree (p,min⁡(q,K))(p, \min(q, K)) with S(u,vk)=Ck(u)S(u, v_k) = C_k(u) for every kk and every uu.

Sections of different degrees must first be raised to the highest degree, which does not change them. Sections on different parameter intervals must first be reparametrized to one interval.

The algorithm

  1. SKIN(C_0..C_K, q, v_0..v_K optional)
  2. 1U ← the merge of the knot vectors of all C_k; refine each C_k to U by knot insertion; P_k ← its control points P_{k,0}, .., P_{k,n}
  3. 2if no parameters are given: for each column i, take the chord length parameters of P_{0,i}, .., P_{K,i}; v_k ← their average over the columns
  4. 3q ← min(q, K); V ← the averaged knots of degree q for v_0, .., v_K; for each column i, solve for Q_{i,0}, .., Q_{i,K} with Σ_l M_l(v_k) Q_{i,l} = P_{k,i} for all k
  5. 4the control net of the surface is Q_{i,l}, with i along u and l along v
  6. 5return the surface of degree (p, q) on U × V with the net Q

Line L1 is the key step. The merged knot vector UU takes each knot value with its largest multiplicity in any section, and knot insertion puts every section on UU without changing its shape. After that, all sections are combinations of the same basis functions N0(u),…,Nn(u)N_0(u), \dots, N_n(u): Ck(u)=∑iNi(u)Pk,iC_k(u) = \sum_i N_i(u) P_{k,i}. Line L2 is the parameter choice of Piegl and Tiller: for each column of control points it takes the chord length parameters, which divide [0,1][0, 1] in proportion to the distances between consecutive points, and it averages them over the columns. A column whose points all coincide, such as a pole, carries no information and is skipped. Line L3 is global curve interpolation with the averaged knots tj+q=(vj+⋯+vj+q−1)/qt_{j+q} = (v_j + \dots + v_{j+q-1})/q, done once for each column. All columns share the same matrix Akl=Ml(vk)A_{kl} = M_l(v_k), so one elimination serves all of them.

Example

Take three quadratic sections (p=2p = 2) in space, in planes y=0,1,2y = 0, 1, 2. The section C0C_0 is the straight line from (0,0,0)(0, 0, 0) to (2,0,0)(2, 0, 0) with control points (0,0,0),(1,0,0),(2,0,0)(0, 0, 0), (1, 0, 0), (2, 0, 0) on the knots (0,0,0,1,1,1)(0, 0, 0, 1, 1, 1). The section C2C_2 is the line from (0,2,1)(0, 2, 1) to (2,2,1)(2, 2, 1), built in the same way. The middle section C1C_1 is a bump on the knots H=(0,0,0,12,1,1,1)H = (0, 0, 0, \frac12, 1, 1, 1) with control points (0,1,0),(12,1,2),(32,1,0),(2,1,0)(0, 1, 0), (\frac12, 1, 2), (\frac32, 1, 0), (2, 1, 0), so C1(14)=(12,1,54)C_1(\frac14) = (\frac12, 1, \frac54). Use q=2q = 2 and the given parameters v=0,12,1v = 0, \frac12, 1.

  • L1. The merged knot vector is U=HU = H. Inserting 12\frac12 into C0C_0 gives (0,0,0),(12,0,0),(32,0,0),(2,0,0)(0, 0, 0), (\frac12, 0, 0), (\frac32, 0, 0), (2, 0, 0), and the same for C2C_2 at y=2y = 2, z=1z = 1.
  • L3. Three parameters and q=2q = 2 give V=(0,0,0,1,1,1)V = (0, 0, 0, 1, 1, 1), so each column is interpolated by a quadratic Bezier curve. For the column i=1i = 1 the points are (12,0,0)(\frac12, 0, 0), (12,1,2)(\frac12, 1, 2), (12,2,1)(\frac12, 2, 1). The quadratic with these values at 0,12,10, \frac12, 1 has the middle control point 2⋅(12,1,2)−12((12,0,0)+(12,2,1))=(12,1,72)2 \cdot (\frac12, 1, 2) - \frac12 \bigl((\frac12, 0, 0) + (\frac12, 2, 1)\bigr) = (\frac12, 1, \frac72).
  • L4. The middle row of the net is (0,1,−12)(0, 1, -\frac12), (12,1,72)(\frac12, 1, \frac72), (32,1,−12)(\frac32, 1, -\frac12), (2,1,−12)(2, 1, -\frac12). The outer rows are the refined control points of C0C_0 and C2C_2.

The surface passes through all three sections. For example S(14,12)=(12,1,54)=C1(14)S(\frac14, \frac12) = (\frac12, 1, \frac54) = C_1(\frac14). Between the sections it follows the quadratics in vv: S(14,14)=(12,12,1316)S(\frac14, \frac14) = (\frac12, \frac12, \frac{13}{16}), above the straight line z=14z = \frac14 that a ruled surface between C0C_0 and C1C_1 would give. The middle row of the net lies off the middle section, at height 72\frac72 over a bump of height 22, because a quadratic through three points overshoots its middle value.

With the default parameters of line L2, three columns have the distances 11 and 2\sqrt2, and the column i=1i = 1 has 5\sqrt5 and 2\sqrt2. The average of the four ratios is

v1=14(31+2+55+2)≈0.4638.v_1 = \frac14 \Bigl(\frac{3}{1 + \sqrt2} + \frac{\sqrt5}{\sqrt5 + \sqrt2}\Bigr) \approx 0.4638.

Correctness

After line L1 every section is Ck(u)=∑i=0nNi(u)Pk,iC_k(u) = \sum_{i=0}^{n} N_i(u) P_{k,i} with the same basis NiN_i on UU, because knot insertion does not change a curve. The matrix Akl=Ml(vk)A_{kl} = M_l(v_k) of line L3 is nonsingular by the Schoenberg-Whitney theorem, since each averaged inner knot lies strictly between the parameters around it. So line L3 finds QQ with ∑lMl(vk)Qi,l=Pk,i\sum_l M_l(v_k) Q_{i,l} = P_{k,i}. Then

S(u,vk)=∑iNi(u)∑lMl(vk)Qi,l=∑iNi(u)Pk,i=Ck(u).S(u, v_k) = \sum_i N_i(u) \sum_l M_l(v_k) Q_{i,l} = \sum_i N_i(u) P_{k,i} = C_k(u).

The common knot vector is what makes the second equality an identity of curves and not only of points. Without line L1 the sections would have control points on different bases, and the rows of control points would not mean anything. The full proof is in the proof file.

Proof: The skinned surface contains every sectionfull

We use the pseudocode and the notation of the page. The sections C0,…,CKC_0, \dots, C_K, K≥1K \ge 1, are clamped B-spline curves of one degree pp on one parameter interval, and the parameters v0<⋯<vKv_0 < \dots < v_K increase, whether they are given or come from line L2.

Lemma 1 (common basis)

After line L1 there are control points Pk,iP_{k,i} with Ck(u)=∑i=0nNi(u)Pk,iC_k(u) = \sum_{i=0}^{n} N_i(u) P_{k,i} for every kk and every uu, where N0,…,NnN_0, \dots, N_n are the B-spline basis functions of degree pp on the merged knot vector UU.

Proof. The merged vector UU contains each knot vector of a section as a sub-multiset, because each knot value appears in UU with its largest multiplicity in any section. The end knots of all sections are the same, so every missing knot is an inner knot of UU, and its multiplicity in UU is at most pp because it is at most pp in the section where it is largest. So the missing knots of CkC_k can be inserted one at a time, and by the theorem on the Boehm knot insertion page each insertion gives new control points on the larger knot vector that define the same curve. After the last insertion the knot vector is UU for every kk. □\square

Lemma 2 (the interpolation in vv)

Let q′=min⁡(q,K)q' = \min(q, K), let VV be the averaged knot vector of degree q′q' for v0,…,vKv_0, \dots, v_K, with basis M0,…,MKM_0, \dots, M_K, and let Akl=Ml(vk)A_{kl} = M_l(v_k). Then AA is nonsingular.

Proof. Number the knots of VV as t0,…,tK+q′+1t_0, \dots, t_{K+q'+1}. They are t0=⋯=tq′=v0t_0 = \dots = t_{q'} = v_0, the inner knots tj+q′=(vj+⋯+vj+q′−1)/q′t_{j+q'} = (v_j + \dots + v_{j+q'-1})/q' for j=1,…,K−q′j = 1, \dots, K - q', and tK+1=⋯=tK+q′+1=vKt_{K+1} = \dots = t_{K+q'+1} = v_K. So there are K+1K + 1 basis functions, one for each parameter, and MlM_l is non zero only on (tl,tl+q′+1)(t_l, t_{l+q'+1}). Take 0<l<K0 < l < K. If l≤q′l \le q' then tl=v0<vlt_l = v_0 < v_l. If l>q′l > q' then tlt_l is the mean of vl−q′,…,vl−1v_{l-q'}, \dots, v_{l-1}, which are all less than vlv_l. If l+1≤K−q′l + 1 \le K - q' then tl+q′+1t_{l+q'+1} is the mean of vl+1,…,vl+q′v_{l+1}, \dots, v_{l+q'}, which are all greater than vlv_l, and otherwise tl+q′+1=vK>vlt_{l+q'+1} = v_K > v_l. So tl<vl<tl+q′+1t_l < v_l < t_{l+q'+1} for 0<l<K0 < l < K, while v0v_0 and vKv_K are the end knots, where M0(v0)=MK(vK)=1M_0(v_0) = M_K(v_K) = 1. These are the conditions of the Schoenberg-Whitney theorem, so AA is nonsingular. □\square

Theorem

The surface SS returned in line L5 satisfies S(u,vk)=Ck(u)S(u, v_k) = C_k(u) for every k=0,…,Kk = 0, \dots, K and every uu.

Proof. By Lemma 2, line L3 has a unique solution: for each column ii, the points Qi,0,…,Qi,KQ_{i,0}, \dots, Q_{i,K} with ∑lMl(vk)Qi,l=Pk,i\sum_l M_l(v_k) Q_{i,l} = P_{k,i} for all kk. The system is solved for each coordinate of each column, and these are independent linear systems with the same matrix. The surface of line L5 is

S(u,v)=∑i=0n∑l=0KNi(u)Ml(v)Qi,l.S(u, v) = \sum_{i=0}^{n} \sum_{l=0}^{K} N_i(u) M_l(v) Q_{i,l}.

Fix kk and put v=vkv = v_k. Then

S(u,vk)=∑iNi(u)(∑lMl(vk)Qi,l)=∑iNi(u)Pk,i=Ck(u),S(u, v_k) = \sum_i N_i(u) \Bigl(\sum_l M_l(v_k) Q_{i,l}\Bigr) = \sum_i N_i(u) P_{k,i} = C_k(u),

where the second equality is line L3 and the third is Lemma 1. □\square

Why the common knot vector is needed

The second equality holds for each ii separately: it says that the iso-curve of SS at vkv_k has the control points Pk,0,…,Pk,nP_{k,0}, \dots, P_{k,n} on the knots UU. The third equality needs that all sections use the same functions NiN_i. If the sections kept their own knot vectors, the column ii would collect control points that multiply different basis functions in different sections, and no single surface of the form above would reproduce them all: a tensor product surface has one basis in uu for all values of vv.

The parameters of line L2

The chord length parameters of one column are 00, then the partial sums of the distances ∣Pk,i−Pk−1,i∣|P_{k,i} - P_{k-1,i}| divided by their total, so they increase strictly when no two consecutive points of the column coincide, and they do not decrease in any case. Their average over the columns that are not a single point starts at 00, ends at 11, and increases strictly unless two consecutive sections have the same control points in every column, that is, unless two consecutive sections are the same curve. In that case the parameters are not increasing, line L3 has no solution, and the implementation reports it. Any other choice of increasing parameters also satisfies the theorem.

Complexity

Let K+1K + 1 be the number of sections and n+1n + 1 the number of control points of a section after line L1. Line L1 inserts at most nn knots into each section. The implementation copies the control polygon at each insertion, which costs O(Kn2)O(K n^2) in total, and an insertion in place costs O(Knp)O(K n p). Line L2 computes (K+1)(n+1)(K + 1)(n + 1) distances. Line L3 solves one (K+1)×(K+1)(K + 1) \times (K + 1) system with n+1n + 1 right sides by dense Gauss-Jordan elimination, in O(K3+K2n)O(K^3 + K^2 n) operations. The total is O(K3+K2n+Kn2)O(K^3 + K^2 n + K n^2). The matrix of line L3 is banded, with at most qq non zero entries beside the diagonal in each row, so a banded solver and insertion in place give Θ(Kn)\Theta(K n) for fixed degrees, which is the size of the output. The extra space is the net, Θ(Kn)\Theta(K n).

Properties

  • Exact on the sections. Each section is an iso-curve of the surface exactly, not within a tolerance. With rational input and given parameters the implementation is exact.
  • Linear in the sections. For fixed parameters, the net depends linearly on the control points of the sections.
  • Global in vv. Interpolation by splines is global, so changing one section changes the surface between all sections, mostly near the changed one.
  • Affine invariant. The construction uses affine combinations only, so it commutes with affine maps of space. The chord length parameters are also invariant under rigid motions and uniform scaling.
  • Two sections give a ruled surface. With K=1K = 1 the degree in vv is 11 and the surface is the ruled surface (1−v)C0(u)+vC1(u)(1 - v) C_0(u) + v C_1(u).
  • Shape between sections depends on the parameters. The parameters vkv_k and the knots VV fix the shape across the sections. Neither is part of the data.

Variants and improvements

  • Rational sections. For NURBS sections the method runs on the homogeneous control points. The result is a NURBS surface, but the weights of the sections must agree in a way that keeps the interpolated weights positive.
  • Approximate skinning. Sections with many unrelated knots give a merged knot vector with many knots. Piegl and Tiller also give a method that approximates the sections within a tolerance on fewer knots.
  • Skinning with spine or guide curves. Woodward places planar sections along a spine curve and adds curves in the long direction to control the shape between sections. A network of curves in both directions leads to the Gordon surface.
  • Lofting with end conditions. Hermite conditions at the first and last section, such as given cross tangents, let the surface join other surfaces with tangent plane continuity.
  • Sweeps. A sweep surface moves one section along a path, and many sweeps are built by skinning copies of the section placed along the path.

When to use it

Use skinning when a shape is given by a row of cross sections, as for hulls, fuselages, wings, bottles, ducts and blades, and the surface must contain them exactly. If curves are also given in the other direction, use a Gordon surface. If only two sections are given, a ruled surface is the same thing. If the sections come from measured data, an interpolant follows the noise, and a fitted surface is better.

Pitfalls

  • Incompatible sections. The sections must have one degree, one parameter interval and the same direction. A section drawn in the reverse direction or with a different start point on a closed curve gives a twisted surface. The program must check this, since the mathematics accepts it.
  • Knot growth. The merged knot vector holds every knot of every section, so sections with unrelated knots give many control points.
  • Bad parameters. Equal spacing of the vkv_k when the sections are unequally spaced gives bulges. Chord length averages help, but sections with very different sizes can still give waves.
  • Overshoot. Like all interpolation, the surface can overshoot between sections. In the example the middle row of the net is at height 72\frac72 over a bump of height 22. Check the result with reflection lines.
  • Coincident sections. Two equal consecutive sections give equal chord length parameters, and the interpolation has no solution. The implementation rejects this.

Implementations

The Python file in this folder has surface_skinning(sections, q, vs), which returns the knot vectors, the degrees and the control net, and chord_parameters, which computes the default parameters of line L2. The shared helper si3spline.py holds the basis functions, the evaluation, Boehm knot insertion, the knot merge and global interpolation with an exact Gauss-Jordan solver. The default parameters use floating point square roots and are then turned into exact fractions, so the rest of the computation is exact. The tests check the worked example and the default parameter v1v_1 of the example. On random sections with different knot vectors, both with given and with default parameters, they check that the iso-curve of the result at each vkv_k has exactly the control points of the section refined to UU, and that the surface and the section agree at a random point. They also check that two sections give the ruled surface and that coincident sections, mixed degrees and a single section are rejected.

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.

si3spline.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the si3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small B-spline tools for the si3 pages.

A point is a tuple of numbers of any fixed length. A B-spline curve of degree
p is a knot vector (a list of n + p + 2 non-decreasing numbers, clamped, that
is with p + 1 equal knots at each end) and a list of n + 1 control points.
Entries may be int or Fraction, and then every result here is exact. No
function here is the algorithm of a page: the basis functions, de Boor
evaluation, knot insertion and global interpolation are the standard tools of
the pages b-spline, de-boor-algorithm, boehm-knot-insertion and
curve-interpolation.
"""

from fractions import Fraction


# ---- points ----------------------------------------------------------------

def add(a, b):
    return tuple(x + y for x, y in zip(a, b))


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


def scale(s, a):
    return tuple(s * x for x in a)


def lincomb(ws, ps):
    """Return the sum of ws[i] * ps[i]; ps is not empty."""
    out = [0] * len(ps[0])
    for w, p in zip(ws, ps):
        if w:
            for d in range(len(out)):
                out[d] += w * p[d]
    return tuple(out)


# ---- basis and evaluation --------------------------------------------------

def check_curve(knots, p, ctrl):
    if p < 0 or len(knots) != len(ctrl) + p + 1:
        raise ValueError("a curve of degree p with n + 1 control points needs n + p + 2 knots")
    if any(knots[i] > knots[i + 1] for i in range(len(knots) - 1)):
        raise ValueError("knots must not decrease")
    if knots[p] >= knots[len(ctrl)]:
        raise ValueError("the parameter interval is empty")


def find_span(knots, p, t):
    """The index k with knots[k] <= t < knots[k + 1], in p..n, and n at the right end."""
    n = len(knots) - p - 2
    if t >= knots[n + 1]:
        return n
    if t <= knots[p]:
        return p
    k = p
    while knots[k + 1] <= t:
        k += 1
    return k


def basis_funs(knots, p, k, t):
    """The values N_{k-p,p}(t), ..., N_{k,p}(t), by the Cox-de Boor recursion."""
    N = [Fraction(1)] + [Fraction(0)] * p
    left = [0] * (p + 1)
    right = [0] * (p + 1)
    for j in range(1, p + 1):
        left[j] = t - knots[k + 1 - j]
        right[j] = knots[k + j] - t
        saved = Fraction(0)
        for r in range(j):
            tmp = N[r] / (right[r + 1] + left[j - r])
            N[r] = saved + right[r + 1] * tmp
            saved = left[j - r] * tmp
        N[j] = saved
    return N


def basis_row(knots, p, t):
    """All n + 1 basis values at t, as one list."""
    n = len(knots) - p - 2
    k = find_span(knots, p, t)
    row = [Fraction(0)] * (n + 1)
    for r, val in enumerate(basis_funs(knots, p, k, t)):
        row[k - p + r] = val
    return row


def curve_point(knots, p, ctrl, t):
    """The point of the curve at t, as the basis combination of the control points."""
    k = find_span(knots, p, t)
    N = basis_funs(knots, p, k, t)
    return lincomb(N, ctrl[k - p:k + 1])


def derivative_curve(knots, p, ctrl):
    """The derivative as a B-spline of degree p - 1 on the knots without their ends."""
    if p == 0:
        raise ValueError("the degree must be positive")
    Q = []
    for i in range(len(ctrl) - 1):
        h = knots[i + p + 1] - knots[i + 1]
        Q.append(scale(Fraction(p) / h, sub(ctrl[i + 1], ctrl[i])) if h else
                 tuple(0 for _ in ctrl[0]))
    return knots[1:-1], p - 1, Q


# ---- knot insertion --------------------------------------------------------

def insert_knot(knots, p, ctrl, t):
    """Insert the inner knot t once (Boehm). The curve does not change."""
    if not knots[p] < t < knots[len(ctrl)]:
        raise ValueError("only inner knots can be inserted")
    if knots.count(t) + 1 > p:
        raise ValueError("an inner knot can have multiplicity at most p")
    k = find_span(knots, p, t)
    new = []
    for i in range(len(ctrl) + 1):
        if i <= k - p:
            new.append(ctrl[i])
        elif i > k:
            new.append(ctrl[i - 1])
        else:
            a = (t - knots[i]) / Fraction(knots[i + p] - knots[i])
            new.append(add(scale(1 - a, ctrl[i - 1]), scale(a, ctrl[i])))
    return knots[:k + 1] + [t] + knots[k + 1:], new


def missing_knots(knots, target):
    """The multiset target minus the multiset knots; raises if knots is not a part of target."""
    out = []
    for t in sorted(set(target)):
        d = target.count(t) - knots.count(t)
        if d < 0:
            raise ValueError("the target knot vector must contain the old one")
        out += [t] * d
    return out


def refine(knots, p, ctrl, target):
    """Insert knots until the knot vector equals target. The curve does not change."""
    for t in missing_knots(knots, target):
        knots, ctrl = insert_knot(knots, p, ctrl, t)
    return knots, ctrl


def merge_knots(vectors):
    """The least knot vector that contains each vector, as multisets."""
    vals = sorted(set(t for v in vectors for t in v))
    out = []
    for t in vals:
        out += [t] * max(v.count(t) for v in vectors)
    return out


# ---- tensor product surfaces -----------------------------------------------
# A surface is (U, V, p, q, P): degree p on the knots U in u, degree q on the
# knots V in v, and the control net P[k][l], k along u and l along v.

def surface_point(U, V, p, q, P, u, v):
    k = find_span(U, p, u)
    N = basis_funs(U, p, k, u)
    return lincomb(N, [curve_point(V, q, P[k - p + r], v) for r in range(p + 1)])


def iso_curve_u(U, p, P, u):
    """Control points over V of the curve v -> S(u, v) for a fixed u."""
    k = find_span(U, p, u)
    N = basis_funs(U, p, k, u)
    return [lincomb(N, [P[k - p + r][l] for r in range(p + 1)]) for l in range(len(P[0]))]


def iso_curve_v(V, q, P, v):
    """Control points over U of the curve u -> S(u, v) for a fixed v."""
    return [curve_point(V, q, row, v) for row in P]


def refine_surface(U, V, p, q, P, U2, V2):
    """The same surface on the finer knot vectors U2 and V2."""
    cols = [refine(U, p, [row[l] for row in P], U2)[1] for l in range(len(P[0]))]
    P = [[cols[l][k] for l in range(len(cols))] for k in range(len(cols[0]))]
    return [refine(V, q, row, V2)[1] for row in P]


# ---- interpolation ---------------------------------------------------------

def solve(A, B):
    """Solve A X = B by Gauss-Jordan elimination with exact pivots. B is a list of points."""
    n = len(A)
    M = [[Fraction(x) for x in A[i]] + [Fraction(x) for x in B[i]] for i in range(n)]
    w = len(M[0])
    for c in range(n):
        r = next((r for r in range(c, n) if M[r][c] != 0), None)
        if r is None:
            raise ValueError("singular system")
        M[c], M[r] = M[r], M[c]
        piv = M[c][c]
        M[c] = [x / piv for x in M[c]]
        for r in range(n):
            if r != c and M[r][c] != 0:
                f = M[r][c]
                M[r] = [x - f * y for x, y in zip(M[r], M[c])]
    return [tuple(M[i][n:w]) for i in range(n)]


def averaging_knots(params, p):
    """Clamped knots whose inner knots are means of p consecutive parameters."""
    n = len(params) - 1
    inner = [sum(params[j:j + p], Fraction(0)) / p for j in range(1, n - p + 1)]
    return [params[0]] * (p + 1) + inner + [params[-1]] * (p + 1)


def interpolate(params, points, p):
    """The B-spline of degree p through points[k] at params[k], with averaging knots."""
    if len(params) != len(points) or len(points) < p + 1:
        raise ValueError("need at least p + 1 points, one parameter each")
    if any(params[k] >= params[k + 1] for k in range(len(params) - 1)):
        raise ValueError("the parameters must increase")
    knots = averaging_knots(params, p)
    A = [basis_row(knots, p, t) for t in params]
    return knots, solve(A, points)
surface_skinning.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/surface-skinning/. The authors are listed in prov/5J15FM.jsonl.

"""Skinning (lofting) a B-spline surface through section curves.

The sections C_0(u), ..., C_K(u) are B-spline curves of one degree p. The
method of Piegl and Tiller, Section 10.3, makes them compatible by merging
their knot vectors and inserting the missing knots into each, so that all
sections have control points on one basis. It chooses a parameter v_k for
each section, by averaging the chord length parameters of the columns of
control points, and averaged knots in v. Then it interpolates each column of
control points across the sections with degree q. The surface S has
S(u, v_k) = C_k(u) for every k, exactly.

With int or Fraction control points and given parameters every step is
exact. The default parameters use square roots in floating point; they are
then turned into exact fractions, so the rest stays exact. The caller raises
the sections to one degree first.
"""

from fractions import Fraction
from math import dist

from si3spline import check_curve, interpolate, merge_knots, refine


def chord_parameters(rows):
    """Average over the columns of the chord length parameters, from 0 to 1.

    rows[k] is the list of control points of section k. A column whose points
    all coincide carries no information and is skipped.
    """
    K = len(rows) - 1
    total = [0.0] * (K + 1)
    used = 0
    for i in range(len(rows[0])):
        d = [dist(map(float, rows[k][i]), map(float, rows[k + 1][i])) for k in range(K)]
        s = sum(d)
        if s == 0:
            continue
        used += 1
        acc = 0.0
        for k in range(1, K):
            acc += d[k - 1]
            total[k] += acc / s
    if used == 0:
        raise ValueError("all sections are the same curve")
    vs = [Fraction(0)] + [Fraction(total[k] / used) for k in range(1, K)] + [Fraction(1)]
    return vs


def surface_skinning(sections, q=3, vs=None):
    """Skin the sections; return (U, V, p, q, P) with P[i][l], i along u.

    sections is a list of (knots, control points). q is the degree in v; it is
    lowered to the number of sections minus one if needed. vs, if given, are
    the parameters of the sections; otherwise they are chord length averages.
    """
    if len(sections) < 2:
        raise ValueError("need at least two sections")
    degs = set()
    for knots, ctrl in sections:
        p = len(knots) - len(ctrl) - 1
        check_curve(knots, p, ctrl)
        degs.add(p)
    if len(degs) != 1:
        raise ValueError("the sections must have one degree")
    p = degs.pop()
    U = merge_knots([kn for kn, _ in sections])  # @line L1
    rows = [refine(kn, p, ctrl, U)[1] for kn, ctrl in sections]  # @line L1
    if vs is None:
        vs = chord_parameters(rows)  # @line L2
    if len(vs) != len(sections):
        raise ValueError("one parameter per section")
    q = min(q, len(sections) - 1)
    d = len(rows[0][0])
    flat = [tuple(x for pt in r for x in pt) for r in rows]
    V, sol = interpolate(vs, flat, q)  # @line L3
    # sol[l] holds the l-th control point of every column; P[i][l] is column i, row l
    P = [[tuple(sol[l][i * d:(i + 1) * d]) for l in range(len(sol))]  # @line L4
         for i in range(len(rows[0]))]
    return U, V, p, q, P  # @line L5
test_surface_skinning.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/surface-skinning/. The authors are listed in prov/5J15FM.jsonl.

import random
import unittest
from fractions import Fraction as Fr

from si3spline import curve_point, iso_curve_v, refine, surface_point
from surface_skinning import chord_parameters, surface_skinning

H = [0, 0, 0, Fr(1, 2), 1, 1, 1]
B = [0, 0, 0, 1, 1, 1]
C0 = (B, [(0, 0, 0), (1, 0, 0), (2, 0, 0)])
C1 = (H, [(0, 1, 0), (Fr(1, 2), 1, 2), (Fr(3, 2), 1, 0), (2, 1, 0)])
C2 = (B, [(0, 2, 1), (1, 2, 1), (2, 2, 1)])


def random_section(rng, p, y):
    """A random B-spline section of degree p near the plane y = const."""
    n = p + rng.randint(0, 4)
    inner = sorted(Fr(rng.randint(1, 19), 20) for _ in range(n - p))
    while any(inner.count(t) > p for t in inner):
        inner = sorted(Fr(rng.randint(1, 19), 20) for _ in range(n - p))
    knots = [Fr(0)] * (p + 1) + inner + [Fr(1)] * (p + 1)
    ctrl = [(Fr(rng.randint(-20, 20), 4), Fr(y) + Fr(rng.randint(-2, 2), 8), Fr(rng.randint(-20, 20), 4))
            for _ in range(n + 1)]
    return knots, ctrl


class TestSurfaceSkinning(unittest.TestCase):
    def assert_interpolates(self, sections, S, rng):
        U, V, p, q, P = S
        k = len(sections) - 1
        vs = self.params
        for (kn, ctrl), v in zip(sections, vs):
            # the iso-curve at v_k and the section on the same knots: equal nets
            self.assertEqual(iso_curve_v(V, q, P, v), refine(kn, p, ctrl, U)[1])
            t = Fr(rng.randint(0, 1000), 1000)
            self.assertEqual(surface_point(U, V, p, q, P, t, v), curve_point(kn, p, ctrl, t))
        self.assertEqual(len(vs), k + 1)

    def skin(self, sections, q=3, vs=None):
        S = surface_skinning(sections, q, vs)
        if vs is None:
            U, _, p, _, _ = S
            vs = chord_parameters([refine(kn, p, c, U)[1] for kn, c in sections])
        self.params = vs
        return S

    def test_example(self):
        S = self.skin([C0, C1, C2], q=2, vs=[Fr(0), Fr(1, 2), Fr(1)])
        U, V, p, q, P = S
        self.assertEqual((U, V, p, q), (H, B, 2, 2))
        middle = [row[1] for row in P]
        self.assertEqual(middle, [(0, 1, Fr(-1, 2)), (Fr(1, 2), 1, Fr(7, 2)),
                                  (Fr(3, 2), 1, Fr(-1, 2)), (2, 1, Fr(-1, 2))])
        self.assertEqual(surface_point(*S, Fr(1, 4), Fr(1, 2)), (Fr(1, 2), 1, Fr(5, 4)))
        self.assertEqual(surface_point(*S, Fr(1, 4), Fr(1, 4)), (Fr(1, 2), Fr(1, 2), Fr(13, 16)))
        self.assert_interpolates([C0, C1, C2], S, random.Random(1))

    def test_example_chord_parameters(self):
        S = self.skin([C0, C1, C2], q=2)
        v1 = float(self.params[1])
        expected = (3 / (1 + 2 ** 0.5) + 5 ** 0.5 / (5 ** 0.5 + 2 ** 0.5)) / 4
        self.assertAlmostEqual(v1, expected, places=12)
        self.assert_interpolates([C0, C1, C2], S, random.Random(2))

    def test_random_sections_are_interpolated(self):
        rng = random.Random(11)
        for trial in range(15):
            p = rng.randint(1, 3)
            K = rng.randint(1, 5)
            sections = [random_section(rng, p, 3 * k) for k in range(K + 1)]
            q = rng.randint(1, 3)
            if trial % 2:
                vs = sorted(rng.sample([Fr(j, 30) for j in range(1, 30)], K - 1)) if K > 1 else []
                vs = [Fr(0)] + vs + [Fr(1)]
                S = self.skin(sections, q, vs)
            else:
                S = self.skin(sections, q)
            self.assertEqual(S[3], min(q, K))
            self.assert_interpolates(sections, S, rng)

    def test_two_sections_give_a_ruled_surface(self):
        S = self.skin([C0, C2], q=3, vs=[Fr(0), Fr(1)])
        self.assertEqual(S[3], 1)
        u, v = Fr(1, 3), Fr(2, 5)
        a = curve_point(C0[0], 2, C0[1], u)
        b = curve_point(C2[0], 2, C2[1], u)
        self.assertEqual(surface_point(*S, u, v), tuple((1 - v) * x + v * y for x, y in zip(a, b)))

    def test_rejections(self):
        with self.assertRaises(ValueError):
            surface_skinning([C0, C0, C2], 2)            # equal sections: parameters do not increase
        with self.assertRaises(ValueError):
            surface_skinning([C0, ([0, 0, 1, 1], [(0, 0, 0), (1, 1, 1)])], 1)   # two degrees
        with self.assertRaises(ValueError):
            surface_skinning([C0], 1)


if __name__ == "__main__":
    unittest.main()

History

Lofting is older than computers. In shipyards and aircraft plants, full size sections were drawn on the floor of the mould loft and faired by hand with long flexible battens, the original splines. In CAD, skinning through drawn sections became a common tool for surface design in the 1980s. Woodward described B-spline skinning in 1988, with spine and projection curves for shape control. Piegl and Tiller give the form used here, with the merged knot vector and parameters averaged over the columns.

References

  1. Les Piegl and Wayne Tiller, The NURBS Book, second edition, Springer, 1997, Section 10.3, Skinned Surfaces (p. 457), and Section 9.2.1 (global curve interpolation with averaged knots)
  2. Charles D. Woodward, Skinning techniques for interactive B-spline surface interpolation, Computer-Aided Design 20(8), 441 to 451, 1988, skinning of B-spline sections, and projection curves for shape control in the long direction
  3. Gerald Farin, Curves and Surfaces for CAGD, A Practical Guide, fifth edition, Morgan Kaufmann, 2002, the chapters on tensor product B-spline surfaces and on surface interpolation

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.worst
  • 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
  • a scene preset for the example