Algorithm Search⌘K

Algorithmadvanced

Plastering

Also called plastering hex meshing.

The 3D analogue of paving that advances layers of hexahedra inward from a quadrilateral boundary mesh, hard to close where the fronts meet.

Time
O(V + Q) worst
Space
O(V + Q) extra
Where
Q = the number of front quads; V = the number of front vertices
Properties
deterministicexactiterative
Origin
Ted D. Blacker, R. J. Meyers, 1993

Plastering is the 3D form of paving. It starts from a closed quad mesh of the boundary, called the front, and builds hexahedra inward one layer at a time. Each new hex stands on a front quad, and its inner face becomes part of the new front. Where two parts of the front come close or meet at a sharp angle, plastering joins them with seams and wedges. The method ends when the front closes up, but this last step is the hard part: the void that remains often cannot be filled with good hexes, and sometimes not with hexes at all. This page is one method for hexahedral mesh generation, and it is a front method with no guarantee to close, while that page states the general problem and its limits. The code on this page implements one exact core step, one layer on a convex box.

In plain words

Think of a plasterer who covers the inside walls of a room with a layer of plaster of even thickness. Each tile on a wall gets a brick of plaster behind it. In a corner, the bricks of two walls must meet along a slanted joint, so they fit without a gap.

When the first layer is done, the room is a bit smaller, and its new walls are the inner faces of the bricks. The plasterer can do the same again and again.

For a plain box room this works well. For a room with odd shapes, the layers from different walls run into each other at strange angles, and at the end a small hole is left in the middle. Often there is no good way to fill that hole with bricks, and the method fails.

The problem

The input of plastering is a solid and a closed quad mesh of its boundary. The output is an all-hex mesh of the solid whose boundary quads are the given ones. A hex is valid if its trilinear map has det⁡J>0\det J > 0 everywhere, as on the scaled Jacobian page.

The code solves the core step for a convex axis-aligned box B=∏t[lt,ut]\mathcal{B} = \prod_t [l_t, u_t] with a grid of breakpoints on each axis. The front is the boundary grid, with each quad counterclockwise seen from outside, and the step adds one layer of thickness hh. The safe thickness is

g=min⁡tmin⁡(first spacing on axis t, last spacing on axis t, 12(ut−lt)).g = \min_t \min\Big(\text{first spacing on axis } t,\ \text{last spacing on axis } t,\ \tfrac12 (u_t - l_t)\Big).

The algorithm

Each front vertex vv moves inward by hh along each box face that contains it: nvn_v is the sum of the outward unit normals of those faces. A vertex inside a face moves along one normal, a vertex on a box edge along two, and a box corner along three, which makes the slanted joints at the edges and corners.

  1. PLASTER-LAYER(P, Q, n, h)
  2. 1for each front vertex v do
  3. 2n_v ← the sum of the outward unit normals of the box faces that contain v
  4. 3v' ← v − h n_v
  5. 4H ← empty list
  6. 5for each front quad (a, b, c, d), counterclockwise seen from outside do
  7. 6append the hex (a', b', c', d', a, b, c, d) to H
  8. 7ok ← every hex of H has 8 positive corner Jacobians
  9. 8return H, the new front (the quads (a', b', c', d')), ok

Lines L1 to L3 place the new front. Lines L4 to L6 make one hex per front quad. The bottom of the hex is the offset quad and its top is the front quad, so the hex grows inward and its top face is counterclockwise seen from above, as the standard vertex order needs. Line L7 is the usual check of the corner Jacobians.

The full method. For a general solid, plastering repeats a loop of this kind, in words:

  1. Choose front quads to advance, usually a whole row or layer at once, and compute inward directions at their vertices from the angles of the front.
  2. Make new hexes on them, and project the new nodes so that the hexes have good shape.
  3. Where the front makes a sharp angle, close it with a seam, which joins two front faces into one inner face of a hex. Where it makes a wide angle, add a wedge.
  4. Find places where fronts come too close or cross, and join or trim them. A mixed mesh of the unmeshed region helps to find such contacts.
  5. When the void that remains is small, fill it with a known pattern of a few hexes. If no pattern fits, back up and try again, or give up.

Example

Take the box [0,4]3[0, 4]^3 with the breakpoints 0,1,3,40, 1, 3, 4 on each axis, so each face has 3×33 \times 3 quads. The front has 5656 vertices and 5454 quads, and g=1g = 1. Take h=1/2h = 1/2. The corner (0,0,0)(0, 0, 0) moves to (1/2,1/2,1/2)(1/2, 1/2, 1/2), the edge vertex (1,0,0)(1, 0, 0) to (1,1/2,1/2)(1, 1/2, 1/2), and the face vertex (1,1,0)(1, 1, 0) to (1,1,1/2)(1, 1, 1/2).

hexes how many front quad offset quad corner Jacobians volume
on a face center 6 2×22 \times 2 2×22 \times 2 all 22 22
along a box edge 24 1×21 \times 2 1/2×21/2 \times 2 1/21/2 and 11 3/43/4
at a box corner 24 1×11 \times 1 1/2×1/21/2 \times 1/2 1/81/8 and 1/21/2 7/247/24

The volumes add up to 12+18+7=37=43−3312 + 18 + 7 = 37 = 4^3 - 3^3, the volume of the shell between the box and the inner box [1/2,7/2]3[1/2, 7/2]^3. The new front is the boundary grid of the inner box with the breakpoints 1/2,1,3,7/21/2, 1, 3, 7/2. A second layer with h=1/2h = 1/2 leaves the box [1,3]3[1, 3]^3 with the breakpoints 1,31, 3, which is one cell.

A layer that passes the corner check but folds. Take the one-cell box [0,4]×[0,2]×[0,6][0, 4] \times [0, 2] \times [0, 6], where g=1g = 1, and h=7/2h = 7/2. Every offset width is negative: 4−74 - 7, 2−72 - 7 and 6−76 - 7. The corner Jacobians are hh times a product of two widths, so all of them are positive and L7 returns true. But the inner box is turned inside out in all three directions, and the hexes overlap. With h=3/2h = 3/2 only the width in yy is negative, and L7 returns false.

Correctness

The proof below covers the core step. The offset of a vertex is a map μ\mu that acts on each coordinate on its own. For a hex on a face with normal axis aa and in-plane axes bb and cc, the trilinear map splits by coordinate, and

det⁡J(u,v,w)=h ((1−w)Δb′+w Δb)((1−w)Δc′+w Δc),\det J(u, v, w) = h\,\big((1 - w)\Delta'_b + w\,\Delta_b\big)\big((1 - w)\Delta'_c + w\,\Delta_c\big),

where Δ\Delta are the side lengths of the front quad and Δ′\Delta' those of the offset quad. So if 0<h<g0 < h < g, every hex is valid at every point, and the layer is a conforming mesh of the shell. If h≥gh \ge g, some offset width is at most zero and the layer is not a valid mesh of a shell, even when, as in the example, every corner Jacobian is positive.

What is proved and what is measured are different here. The proof covers only the box. For a general solid, plastering has no guarantee to close the last void, and the survey of Pietroni and others states that a void with an odd number of quads cannot be filled at all and needs backtracking. Plastering often fails to close the last void, and practical codes fall back to tetrahedra or pyramids there. The tests compare the corner check with a direct formula on 500 random boxes and thicknesses, and check conformity by face counts. On a sample of these boxes they also check that all Bernstein coefficients of det⁡J\det J are positive and that the volumes add up to the volume of the shell.

Proof: One plastering layer on a grid box is a valid conforming hex mesh of the shell exactly when 0 < h < gfull

Setting. The box is B=∏t=02[lt,ut]\mathcal{B} = \prod_{t=0}^{2} [l_t, u_t]. Each axis tt has strictly increasing breakpoints lt=xt,0<xt,1<⋯<xt,nt=utl_t = x_{t,0} < x_{t,1} < \cdots < x_{t,n_t} = u_t with nt≥1n_t \ge 1. The front is the boundary quad mesh of this grid, and each quad is listed counterclockwise seen from outside, so for its first three corners p0,p1,p3p_0, p_1, p_3 the vector (p1−p0)×(p3−p0)(p_1 - p_0) \times (p_3 - p_0) points out of the box. For a front vertex pp, npn_p is the sum of the outward unit normals of the box faces that contain pp. PLASTER-LAYER sets p′=p−h npp' = p - h\,n_p (L1 to L3) and makes, for each quad (a,b,c,d)(a, b, c, d), the hex (a′,b′,c′,d′,a,b,c,d)(a', b', c', d', a, b, c, d) (L5 and L6). Let

g=min⁡tmin⁡(xt,1−xt,0, xt,nt−xt,nt−1, 12(ut−lt)).g = \min_t \min\Big(x_{t,1} - x_{t,0},\ x_{t,n_t} - x_{t,n_t - 1},\ \tfrac12 (u_t - l_t)\Big).

Claim.

  1. PLASTER-LAYER stops after O(V+Q)O(V + Q) steps for VV front vertices and QQ front quads, and makes Q=2(n0n1+n1n2+n2n0)Q = 2(n_0 n_1 + n_1 n_2 + n_2 n_0) hexes.
  2. Let μt(x)=x+h\mu_t(x) = x + h for x=ltx = l_t, μt(x)=x−h\mu_t(x) = x - h for x=utx = u_t, and μt(x)=x\mu_t(x) = x otherwise. Then pt′=μt(pt)p'_t = \mu_t(p_t) for every front vertex and every axis.
  3. Take a hex on a face with normal axis aa, and let bb and cc be the other two axes. Let Δb\Delta_b and Δc\Delta_c be the side lengths of its front quad, and Δb′\Delta'_b, Δc′\Delta'_c the side lengths of the offset quad. Then at every point of the unit cube
det⁡J(u,v,w)=h βb(w) βc(w),βt(w)=(1−w) Δt′+w Δt.\det J(u, v, w) = h\,\beta_b(w)\,\beta_c(w), \qquad \beta_t(w) = (1 - w)\,\Delta'_t + w\,\Delta_t.
  1. If 0<h<g0 < h < g, every hex has det⁡J>0\det J > 0 on the whole closed cube. The hexes form a conforming mesh of the shell B∖int⁡B′\mathcal{B} \setminus \operatorname{int} \mathcal{B}' with B′=∏t[lt+h,ut−h]\mathcal{B}' = \prod_t [l_t + h, u_t - h], and the new front is the boundary grid of B′\mathcal{B}' with the breakpoints μt(xt,i)\mu_t(x_{t,i}).
  2. If h≤0h \le 0 or h≥gh \ge g, the layer is not a valid mesh of a shell: some offset width Δt′\Delta'_t is at most 00. The corner test of L7 is true exactly when h>0h > 0 and Δb′Δc′>0\Delta'_b \Delta'_c > 0 for every pair of offset widths on two different axes. This can hold when every offset width is negative, so the corner test alone does not prove validity.

Proof of part 1. L1 to L3 visit each vertex once and L5 and L6 visit each quad once. The two faces normal to axis aa each carry nbncn_b n_c quads, which gives the count.

Proof of part 2. The outward normal of the face xt=ltx_t = l_t is −et-e_t, and of the face xt=utx_t = u_t it is +et+e_t. A vertex is on the face xt=ltx_t = l_t exactly when pt=ltp_t = l_t, and it is not on both faces of an axis because lt<utl_t < u_t. So the tt component of −h np-h\,n_p is +h+h, −h-h or 00 in the three cases of μt\mu_t.

Proof of part 3. Let the front quad be on the face xa=lax_a = l_a. The case xa=uax_a = u_a is the same with the signs changed. The quad is the rectangle [xb,i,xb,i+1]×[xc,j,xc,j+1][x_{b,i}, x_{b,i+1}] \times [x_{c,j}, x_{c,j+1}] in the plane xa=lax_a = l_a. By part 2 the offset quad is the rectangle [μb(xb,i),μb(xb,i+1)]×[μc(xc,j),μc(xc,j+1)][\mu_b(x_{b,i}), \mu_b(x_{b,i+1})] \times [\mu_c(x_{c,j}), \mu_c(x_{c,j+1})] in the plane xa=la+hx_a = l_a + h. Both are listed in the same corner order. Up to the choice of which of uu and vv runs along bb, the trilinear map is

xa=la+(1−w)h,xb=(1−w)(μb(xb,i)+s Δb′)+w (xb,i+s Δb),x_a = l_a + (1 - w) h, \qquad x_b = (1 - w)(\mu_b(x_{b,i}) + s\,\Delta'_b) + w\,(x_{b,i} + s\,\Delta_b),

and the same for xcx_c with the other parameter rr, where ss and rr are uu and vv or 1−u1 - u and 1−v1 - v. So xax_a depends only on ww, xbx_b only on (s,w)(s, w) and xcx_c only on (r,w)(r, w). The Jacobian matrix has, up to a permutation of rows and columns, a triangular form with the diagonal −h-h, ±βb(w)\pm\beta_b(w), ±βc(w)\pm\beta_c(w). So det⁡J=σ h βb(w) βc(w)\det J = \sigma\, h\, \beta_b(w)\, \beta_c(w) with a sign σ=±1\sigma = \pm 1 that is the same at every point. To find σ\sigma, take w=1w = 1, where βt=Δt>0\beta_t = \Delta_t > 0. There the first two columns are the edge vectors of the front quad, and the third column ∂wH\partial_w H is the front point minus the offset point. Its aa component is −h-h, which is hh times the outward normal −ea-e_a, and its other components are in the plane of the quad. So det⁡J=h (∂uH×∂vH)⋅(−ea)\det J = h\,(\partial_u H \times \partial_v H) \cdot (-e_a), which is positive because the quad is counterclockwise seen from outside. So σ=1\sigma = 1.

Proof of part 4. Let 0<h<g0 < h < g. On each axis the offset widths are xt,1−xt,0−hx_{t,1} - x_{t,0} - h and xt,nt−xt,nt−1−hx_{t,n_t} - x_{t,n_t-1} - h at the ends and the unchanged widths inside, or ut−lt−2hu_t - l_t - 2h if nt=1n_t = 1. All are positive by the choice of gg. So μt\mu_t is strictly increasing on the breakpoints, and βt(w)>0\beta_t(w) > 0 for all w∈[0,1]w \in [0, 1]. Part 3 gives det⁡J>0\det J > 0 on the closed cube.

The new points are μ(p)\mu(p), with μt(lt)=lt+h\mu_t(l_t) = l_t + h and μt(ut)=ut−h\mu_t(u_t) = u_t - h, and μt\mu_t keeps the inner breakpoints, which lie in (lt+h,ut−h)(l_t + h, u_t - h). So the new front is the boundary grid of B′\mathcal{B}' with the breakpoints μt(xt,i)\mu_t(x_{t,i}).

Conformity. The offset of a vertex depends only on the vertex. Two front quads that share the edge pqpq give two hexes that share the face (p,q,q′,p′)(p, q, q', p'). The front quads and the offset quads each belong to one hex.

Covering. For a face FF of B\mathcal{B} with the parallel face F′F' of B′\mathcal{B}', let PFP_F be the convex hull of F∪F′F \cup F', a frustum. For a point xx of the shell, let d(x)d(x) be the least of the six distances xt−ltx_t - l_t and ut−xtu_t - x_t. A point of the shell is not in int⁡B′\operatorname{int} \mathcal{B}', so d(x)≤hd(x) \le h. Because B′\mathcal{B}' is B\mathcal{B} moved in by the same hh on every side, xx is in PFP_F exactly when the distance to FF is the least of the six, and xx is in the interior of PFP_F only when that distance is strictly the least. So the six frusta cover the shell and have disjoint interiors. Inside PFP_F with FF on xa=lax_a = l_a, the hexes of FF are the images of the front quads of FF under Φ(y,w)=(1−w)μ(y)+w y\Phi(y, w) = (1 - w)\mu(y) + w\,y. The aa coordinate fixes ww, and for a fixed ww the in-plane coordinates are (1−w)μt(yt)+w yt(1 - w)\mu_t(y_t) + w\,y_t, which are continuous, piecewise affine and strictly increasing in yty_t. So Φ\Phi is one to one from F×[0,1]F \times [0, 1] onto PFP_F, and the hexes of FF tile PFP_F with disjoint interiors.

Proof of part 5. If h≤0h \le 0, the offset quads are not inside the box, and part 3 gives det⁡J=0\det J = 0 for h=0h = 0 and a negative value at w=1w = 1 for h<0h < 0. If h≥gh \ge g, one of the three cases in the definition of gg gives an offset width at most 00, so B′\mathcal{B}' does not have positive side lengths and the new front is not the boundary of a box inside B\mathcal{B}. The corner Jacobians are the values of part 3 at w∈{0,1}w \in \{0, 1\}. At w=1w = 1 they are hΔbΔch \Delta_b \Delta_c. At w=0w = 0 they are hΔb′Δc′h \Delta'_b \Delta'_c for every pair of offset widths of the face, and every pair of offset widths of two different axes occurs on some face, because the faces normal to the third axis carry all pairs. This gives the condition for L7. If all offset widths are negative, which needs nt≤2n_t \le 2 on every axis, every product is positive and L7 returns true, but B′\mathcal{B}' is reflected and the hexes overlap. ■\blacksquare

Complexity

One layer visits each front vertex and each front quad once, so it takes O(V+Q)O(V + Q) time and space. For the grid box, Q=2(n0n1+n1n2+n2n0)Q = 2(n_0 n_1 + n_1 n_2 + n_2 n_0). Each new layer of a box has the same quad count, and kk layers of thickness hh are valid exactly when kh<gk h < g, because each layer lowers gg by hh. For a general solid, the cost of front contact tests and of backtracking dominates, and there is no useful bound on the number of tries.

Properties

  • Good boundary hexes. The first layers follow the boundary closely, with faces parallel to it. This is the main reason for plastering, as for boundary layers in flow problems.
  • Fixed boundary mesh. The given boundary quads are kept, so a plastered volume can meet a neighbour volume with a matching mesh.
  • Same front size. On a convex box, each layer leaves a front with the same number of quads, so the front does not shrink in count, only in size.
  • No closure guarantee. The front may meet itself in a way that no hex pattern can close. The last void is often impossible to fill well.
  • Parity. A void with an odd number of quads has no hex mesh at all, by the parity of the hexahedral mesh existence theorem.

Variants and improvements

  • Seams and wedges. Blacker and Meyers close sharp front angles by seams and fill wide angles by wedges.
  • Unconstrained plastering. Staten and others start from the geometry, not from a boundary quad mesh. They advance whole layers until they meet, and only then fix the boundary mesh. The remaining voids are easier to fill, but the process can still fail.
  • Hybrid meshes. Owen and Saigal keep a tetrahedral mesh of the unmeshed region during the advance, so front contacts are easy to find. The last void can stay as tetrahedra and pyramids, which gives a hex-dominant mesh.
  • Receding front. Ruiz-Gironés, Roca and Sarrate grow a seed mesh outward and the boundary front inward, guided by distance fields, so the meeting surface is known in advance.

When to use it

Use plastering, or one of its unconstrained or hybrid forms, when good hexes near the boundary matter most and a few non-hex elements in the middle are acceptable. For a solid with a sweep direction, sweeping is simpler and safer. For a strict all-hex mesh of a general solid, polycube and frame field methods are the research choices, and none of them is guaranteed either.

Pitfalls

  • Closing the last void. This is the main failure. Check the parity of the void first, and plan a fallback, such as a few tetrahedra or a pillow layer.
  • Corner checks are not enough. The example shows a layer with all corner Jacobians positive that overlaps itself. Check the new front against the old one, not only each hex.
  • Front collisions. Two parts of the front that grow toward each other can cross. Test for contacts after each layer.
  • Thickness too large. On a box, a layer thicker than the safe value gg folds. On a general solid, the safe thickness changes along the front and must be found locally.

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.

mg4geom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the mg4 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Exact geometry of trilinear hexahedra, shared by the mg4 pages.

A hex is a list of 8 points in the standard order: the bottom face
0, 1, 2, 3 counterclockwise seen from above, then the top face 4, 5, 6, 7
above 0, 1, 2, 3. Vertex k is the image of the reference corner
REF[k] of the unit cube, and the hex is the trilinear map of the cube with
these corner images. With int or Fraction coordinates every value here is
exact, so every sign is decided exactly.
"""

from fractions import Fraction
from typing import List, Sequence, Tuple

Point = Tuple
Hex = Sequence[Point]

REF = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1)]

# For corner k, three neighbours whose edge vectors form a right-handed frame on the unit cube.
CORNER_NEIGHBOURS = [(1, 3, 4), (2, 0, 5), (3, 1, 6), (0, 2, 7), (7, 5, 0), (4, 6, 1), (5, 7, 2), (6, 4, 3)]

# The six faces, each listed counterclockwise seen from outside the hex.
FACES = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]

# The twelve edges in three classes of four parallel edges (directions u, v, w).
EDGE_CLASSES = [
    [(0, 1), (3, 2), (4, 5), (7, 6)],
    [(0, 3), (1, 2), (4, 7), (5, 6)],
    [(0, 4), (1, 5), (2, 6), (3, 7)],
]


def sub(p: Point, q: Point) -> Point:
    """p - q, componentwise."""
    return tuple(a - b for a, b in zip(p, q))


def det3(a: Point, b: Point, c: Point):
    """The determinant of the 3 x 3 matrix with columns a, b, c."""
    return (
        a[0] * (b[1] * c[2] - b[2] * c[1])
        - b[0] * (a[1] * c[2] - a[2] * c[1])
        + c[0] * (a[1] * b[2] - a[2] * b[1])
    )


def corner_jacobians(h: Hex) -> List:
    """The 8 corner Jacobian determinants det(e1, e2, e3) of a hex. Cost: O(1)."""
    out = []
    for k, (i, j, l) in enumerate(CORNER_NEIGHBOURS):
        out.append(det3(sub(h[i], h[k]), sub(h[j], h[k]), sub(h[l], h[k])))
    return out


def corners_positive(h: Hex) -> bool:
    """True when all 8 corner Jacobians are positive (necessary for validity, not sufficient)."""
    return all(d > 0 for d in corner_jacobians(h))


def trilinear(h: Hex, u, v, w) -> Point:
    """The point of the trilinear hex at the reference point (u, v, w)."""
    out = [0, 0, 0]
    for k, (a, b, c) in enumerate(REF):
        wt = (u if a else 1 - u) * (v if b else 1 - v) * (w if c else 1 - w)
        for t in range(3):
            out[t] += wt * h[k][t]
    return tuple(out)


def jacobian_det(h: Hex, u, v, w):
    """det of the Jacobian matrix of the trilinear hex at (u, v, w), exact for exact input."""
    du, dv, dw = [0, 0, 0], [0, 0, 0], [0, 0, 0]
    for k, (a, b, c) in enumerate(REF):
        fu, fv, fw = (u if a else 1 - u), (v if b else 1 - v), (w if c else 1 - w)
        su, sv, sw = (1 if a else -1), (1 if b else -1), (1 if c else -1)
        for t in range(3):
            du[t] += su * fv * fw * h[k][t]
            dv[t] += fu * sv * fw * h[k][t]
            dw[t] += fu * fv * sw * h[k][t]
    return det3(du, dv, dw)


def _to_bernstein2(f0, fh, f1):
    """Bernstein coefficients of the quadratic with values f0, fh, f1 at 0, 1/2, 1."""
    return (f0, 2 * fh - (f0 + f1) / Fraction(2), f1)


def jacobian_bernstein(h: Hex) -> List:
    """The 27 Bernstein coefficients of det J, which has degree 2 in each of u, v, w.

    The determinant is sampled at {0, 1/2, 1}^3 and converted direction by direction.
    Index order: coefficient (i, j, k) is at position 9 i + 3 j + k. Cost: O(1).
    """
    half = Fraction(1, 2)
    ts = (0, half, 1)
    vals = [[[jacobian_det(h, ts[i], ts[j], ts[k]) for k in range(3)] for j in range(3)] for i in range(3)]
    for i in range(3):
        for j in range(3):
            vals[i][j] = list(_to_bernstein2(*vals[i][j]))
    for i in range(3):
        for k in range(3):
            col = _to_bernstein2(vals[i][0][k], vals[i][1][k], vals[i][2][k])
            for j in range(3):
                vals[i][j][k] = col[j]
    for j in range(3):
        for k in range(3):
            col = _to_bernstein2(vals[0][j][k], vals[1][j][k], vals[2][j][k])
            for i in range(3):
                vals[i][j][k] = col[i]
    return [vals[i][j][k] for i in range(3) for j in range(3) for k in range(3)]


def bernstein_certified(h: Hex) -> bool:
    """True when every Bernstein coefficient of det J is positive, which proves det J > 0 on the whole hex."""
    return all(c > 0 for c in jacobian_bernstein(h))


def hex_volume(h: Hex):
    """The signed volume of the trilinear hex, the integral of det J over the unit cube.

    Each quadratic Bernstein polynomial integrates to 1/3 on [0, 1], so the integral is
    the mean of the 27 coefficients. Exact for exact input.
    """
    return sum(jacobian_bernstein(h)) / Fraction(27)


def solve(a: List[List], b: List) -> List:
    """Solve a x = b by Gaussian elimination with Fraction. Raises ValueError if singular."""
    n = len(a)
    m = [[Fraction(x) for x in row] + [Fraction(y)] for row, y in zip(a, b)]
    for c in range(n):
        p = next((r for r in range(c, n) if m[r][c] != 0), None)
        if p is None:
            raise ValueError("singular system")
        m[c], m[p] = m[p], m[c]
        for r in range(n):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                m[r] = [x - f * y for x, y in zip(m[r], m[c])]
    return [m[r][n] / m[r][r] for r in range(n)]
plastering.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plastering/. The authors are listed in prov/ZETKKR.jsonl.

"""One layer of plastering on a convex axis-aligned box.

The front is a closed quad mesh, each quad listed counterclockwise seen from
outside the solid. Each front vertex v gets an inward offset: v' = v - h n_v,
where n_v is the sum of the outward unit normals of the box faces that contain
v. One hex joins each front quad (a, b, c, d) to its offset quad
(a', b', c', d'), and the offset quads are the new front. This is the core step
of plastering, without seams, wedges or the closure of the last void.
With int or Fraction input every value and sign is exact.
"""

from fractions import Fraction
from typing import Dict, List, Sequence, Tuple

from mg4geom import corners_positive, det3, sub

Point = Tuple


def box_front(xs: Sequence, ys: Sequence, zs: Sequence):
    """The boundary quad mesh of the grid box with the given strictly increasing breakpoints.

    Returns (points, quads). Every quad is counterclockwise seen from outside.
    """
    grids = (list(xs), list(ys), list(zs))
    ids: Dict[Point, int] = {}
    quads = []
    for axis in range(3):
        a1, a2 = [t for t in range(3) if t != axis]
        for side, sign in ((0, -1), (-1, 1)):
            normal = tuple(sign if t == axis else 0 for t in range(3))
            g1, g2 = grids[a1], grids[a2]
            for i in range(len(g1) - 1):
                for j in range(len(g2) - 1):
                    q = []
                    for di, dj in ((0, 0), (1, 0), (1, 1), (0, 1)):
                        p = [0, 0, 0]
                        p[axis] = grids[axis][side]
                        p[a1], p[a2] = g1[i + di], g2[j + dj]
                        q.append(tuple(Fraction(c) for c in p))
                    if det3(sub(q[1], q[0]), sub(q[3], q[0]), normal) < 0:
                        q = [q[0], q[3], q[2], q[1]]
                    quads.append(tuple(ids.setdefault(p, len(ids)) for p in q))
    points = sorted(ids, key=ids.get)
    return points, quads


def box_normals(points: Sequence[Point], low: Sequence, high: Sequence) -> List[Point]:
    """For each point, the sum of the outward unit normals of the box faces that contain it."""
    out = []
    for p in points:
        out.append(tuple((1 if p[t] == high[t] else 0) - (1 if p[t] == low[t] else 0) for t in range(3)))
    return out


def plaster_layer(points: Sequence[Point], quads: Sequence[Tuple[int, int, int, int]], normals: Sequence[Point], h):
    """Advance the front by one layer of hexes of thickness h.

    Returns (new_points, hexes, ok): new_points[v] is the offset of points[v], the new
    front has the same quads with the new points, hexes[i] joins the offset of
    quads[i] (bottom) to quads[i] (top), and ok tells whether every hex has 8
    positive corner Jacobians. Cost: O(V + Q) for V vertices and Q quads.
    """
    new_points = []
    for v, p in enumerate(points):  # @line L1
        n = normals[v]  # @line L2
        new_points.append(tuple(p[t] - h * n[t] for t in range(3)))  # @line L3
    hexes = []  # @line L4
    for a, b, c, d in quads:  # @line L5
        hexes.append([new_points[a], new_points[b], new_points[c], new_points[d], points[a], points[b], points[c], points[d]])  # @line L6
    ok = all(corners_positive(hx) for hx in hexes)  # @line L7
    return new_points, hexes, ok  # @line L8


def safe_thickness(xs: Sequence, ys: Sequence, zs: Sequence):
    """g = the least of the first spacing, the last spacing and half the length, over the three axes."""
    g = None
    for grid in (xs, ys, zs):
        cands = [Fraction(grid[1] - grid[0]), Fraction(grid[-1] - grid[-2]), Fraction(grid[-1] - grid[0], 2)]
        m = min(cands)
        g = m if g is None else min(g, m)
    return g
test_plastering.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plastering/. The authors are listed in prov/ZETKKR.jsonl.

import random
from fractions import Fraction as F

from mg4geom import FACES, bernstein_certified, corner_jacobians, hex_volume, jacobian_det
from plastering import box_front, box_normals, plaster_layer, safe_thickness


def layer(xs, ys, zs, h):
    points, quads = box_front(xs, ys, zs)
    normals = box_normals(points, (xs[0], ys[0], zs[0]), (xs[-1], ys[-1], zs[-1]))
    new_points, hexes, ok = plaster_layer(points, quads, normals, h)
    return points, quads, new_points, hexes, ok


def faces_by_coordinates(hexes):
    count = {}
    for hx in hexes:
        for f in FACES:
            key = frozenset(hx[i] for i in f)
            count[key] = count.get(key, 0) + 1
    return count


def check_layer(xs, ys, zs, h, full=False):
    points, quads, new_points, hexes, ok = layer(xs, ys, zs, h)
    nx, ny, nz = len(xs) - 1, len(ys) - 1, len(zs) - 1
    assert len(quads) == len(hexes) == 2 * (nx * ny + ny * nz + nz * nx)
    g = safe_thickness(xs, ys, zs)
    # brute force: corner Jacobians of every hex
    assert ok == all(d > 0 for hx in hexes for d in corner_jacobians(hx))
    # oracle: a corner Jacobian is h times the product of two in-plane widths, outer or inner
    ws = [inner_widths(grid, h) for grid in (xs, ys, zs)]
    expect = h > 0 and all(p * q > 0 for b in range(3) for c in range(b + 1, 3) for p in ws[b] for q in ws[c])
    assert ok == expect
    # the layer is a valid mesh of the shell exactly when 0 < h < g
    assert (0 < h < g) == (h > 0 and all(w > 0 for wl in ws for w in wl))
    if 0 < h < g:
        assert ok
        lo = [xs[0] + h, ys[0] + h, zs[0] + h]
        hi = [xs[-1] - h, ys[-1] - h, zs[-1] - h]
        # the new front is the boundary of the inner box
        for p in new_points:
            assert all(lo[t] <= p[t] <= hi[t] for t in range(3))
            assert any(p[t] in (lo[t], hi[t]) for t in range(3))
        # conformity: outer and inner quads are free, every other face is shared by two hexes
        count = faces_by_coordinates(hexes)
        outer = {frozenset(points[v] for v in q) for q in quads}
        inner = {frozenset(new_points[v] for v in q) for q in quads}
        for key, c in count.items():
            assert c == (1 if key in outer or key in inner else 2)
        if full:
            vol = sum(hex_volume(hx) for hx in hexes)
            big = (xs[-1] - xs[0]) * (ys[-1] - ys[0]) * (zs[-1] - zs[0])
            small = (hi[0] - lo[0]) * (hi[1] - lo[1]) * (hi[2] - lo[2])
            assert vol == big - small
            assert all(bernstein_certified(hx) for hx in hexes)
    return points, quads, new_points, hexes, ok


def test_page_example():
    xs = ys = zs = [0, 1, 3, 4]
    points, quads, new_points, hexes, ok = check_layer(xs, ys, zs, F(1, 2), full=True)
    assert len(points) == 56 and len(quads) == 54 and ok
    assert safe_thickness(xs, ys, zs) == 1
    corner = points.index((0, 0, 0))
    assert new_points[corner] == (F(1, 2), F(1, 2), F(1, 2))
    edge_pt = points.index((1, 0, 0))
    assert new_points[edge_pt] == (1, F(1, 2), F(1, 2))
    face_pt = points.index((1, 1, 0))
    assert new_points[face_pt] == (1, 1, F(1, 2))
    assert sum(hex_volume(hx) for hx in hexes) == 64 - 27
    kinds = {}
    for hx in hexes:
        key = (tuple(sorted(set(corner_jacobians(hx)))), hex_volume(hx))
        kinds[key] = kinds.get(key, 0) + 1
    assert kinds == {((F(1, 8), F(1, 2)), F(7, 24)): 24, ((F(1, 2), 1), F(3, 4)): 24, ((2,), 2): 6}


def test_thickness_at_the_limit_fails():
    xs = ys = zs = [0, 1, 3, 4]
    for h in (F(0), F(1), F(3, 2), F(-1, 2)):
        assert not layer(xs, ys, zs, h)[4]


def test_one_cell_box_and_half_length():
    xs, ys, zs = [0, 4], [0, 2], [0, 6]
    assert safe_thickness(xs, ys, zs) == 1
    assert check_layer(xs, ys, zs, F(99, 100), full=True)[4]
    _, _, _, hexes, ok = layer(xs, ys, zs, F(3, 2))
    assert not ok
    # past half the length in y the inner box is turned over in y only, and hexes invert near it
    assert any(jacobian_det(hx, F(1, 2), F(1, 2), F(1, 4)) < 0 for hx in hexes)


def test_box_turned_inside_out_passes_the_corner_check():
    # h is past half of every length, so the inner box is reflected in all three axes:
    # every hex keeps positive corner Jacobians, but the layer folds over itself
    xs, ys, zs = [0, 4], [0, 2], [0, 6]
    points, quads, new_points, hexes, ok = layer(xs, ys, zs, F(7, 2))
    assert ok and safe_thickness(xs, ys, zs) == 1
    # the signed volumes add up to the box minus the signed volume of the reflected inner box
    assert sum(hex_volume(hx) for hx in hexes) == 48 - (4 - 7) * (2 - 7) * (6 - 7)
    corner = points.index((0, 0, 0))
    assert new_points[corner] == (F(7, 2), F(7, 2), F(7, 2))  # outside the box in y


def inner_widths(grid, h):
    widths = [b - a for a, b in zip(grid, grid[1:])]
    if len(widths) == 1:
        return [widths[0] - 2 * h]
    return [widths[0] - h] + widths[1:-1] + [widths[-1] - h]


def test_second_layer_on_the_new_front():
    xs = ys = zs = [0, 2, 4, 6]
    points, quads, p1, hexes1, ok1 = check_layer(xs, ys, zs, F(1, 2))
    normals = box_normals(p1, (F(1, 2),) * 3, (F(11, 2),) * 3)
    p2, hexes2, ok2 = plaster_layer(p1, quads, normals, F(1, 2))
    assert ok1 and ok2
    assert all(hx[4:] == hy[:4] for hx, hy in zip(hexes2, hexes1))
    # the void that remains is the box [1, 5]^3 with the breakpoints 1, 2, 4, 5
    assert {c for p in p2 for c in p} == {1, 2, 4, 5}


def test_random_boxes():
    rng = random.Random(1993)
    passed = 0
    for trial in range(500):
        grids = []
        for _ in range(3):
            n = rng.randint(1, 3)
            grids.append(sorted(rng.sample(range(0, 10), n + 1)))
        g = safe_thickness(*grids)
        h = rng.choice([g * F(rng.randint(1, 15), 10), F(rng.randint(-2, 12), 4)])
        ok = check_layer(*grids, h, full=(trial % 50 == 0))[4]
        passed += ok
    assert 100 < passed < 450

History

Paving, the 2D method of Blacker and Stephenson, appeared in 1991. Plastering, its 3D form, was described by Blacker and Meyers in 1993, with seams and wedges to close the front. It showed that the 3D closure problem is much harder than in 2D, and Mitchell's work on the existence theorem explained part of the reason: a void can be closed by hexes only if its quad count is even, and even then the hexes may have to be bad. From 2005 to 2010 Staten, Owen, Blacker and others gave unconstrained plastering, which defers the boundary mesh until the layers meet.

References

  1. T. D. Blacker and R. J. Meyers, Seams and wedges in plastering, a 3D hexahedral mesh generation algorithm, Engineering with Computers 9(2), 1993, 83 to 93, the advancing front of quads, the projection of hexes inward, and the seam and wedge operations where fronts meet (general locator)
  2. Matthew L. Staten, Steven J. Owen and Ted D. Blacker, Unconstrained paving and plastering, a new idea for all hexahedral mesh generation, Proceedings of the 14th International Meshing Roundtable, 2005, 399 to 416, layers that start from the geometry and leave the boundary mesh unconstrained (general locator)
  3. Matthew L. Staten, Robert A. Kerr, Steven J. Owen, Ted D. Blacker, Marco Stupazzini and Kenji Shimada, Unconstrained plastering, hexahedral mesh generation via advancing-front geometry decomposition, International Journal for Numerical Methods in Engineering 81, 2010, 135 to 171, the full unconstrained plastering method and the meshing of the remaining voids (general locator)
  4. Nico Pietroni, Marcel Campen, Alla Sheffer, Gianmarco Cherchi, David Bommes, Xifeng Gao, Riccardo Scateni, Franck Ledoux, Jean-François Remacle and Marco Livesu, Hex-mesh generation and processing, a survey, arXiv 2202.12670, 2022, the section on advancing front methods, which states that there is no guarantee of a full hex mesh and that a void with an odd quad count needs backtracking

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