Algorithm Search⌘K

Algorithmresearch

Polycube-based hex meshing

Also called polycube map, PolyCut.

Deforms a solid into a polycube, an axis-aligned union of cubes, by a volumetric map, meshes the polycube with a grid and maps the hexes back.

Time
O(C s^3) worst
Space
O(C s^3) extra
Where
C = the number of voxels of the polycube; s = the number of grid cells per voxel edge
Properties
deterministicexactiterative
Origin
James Gregson, Alla Sheffer, Eugene Zhang, 2011

A polycube method makes a hex mesh of a solid in three steps. First it finds a polycube, a solid made of axis-aligned unit cubes, with the same shape in a rough sense. Then it computes a volumetric map between the solid and the polycube. Last it meshes the polycube with a regular grid and maps the grid back into the solid. This page is one method for hexahedral mesh generation, and it gets a full hex mesh from a map to a polycube, while that page states the general problem and its limits. The code on this page implements one exact core step: the grid of a given polycube under a given map, with a test that proves every hex valid.

In plain words

Imagine the solid is made of soft clay. You press the clay until every face of it is flat and points along one of the three axes, so the clay looks like a stack of toy blocks. Blocks are easy to cut into small equal cubes.

Now draw these small cubes on the clay and let the clay spring back to its first shape. The small cubes bend with the clay, and they become the hexes of the mesh.

The hard parts are to choose a good stack of blocks for the shape, and to press the clay so that no part of it folds over another part. If the clay folds, some hexes turn inside out.

The problem

The input is a polycube PP, a finite set CC of unit voxels with integer corners, and a map gg from PP into space, given by the images of the integer voxel corners and trilinear on each voxel. In a full method, gg is the inverse of the map from the solid to the polycube. The output is the hex mesh of resolution ss: the images under gg of the cells of the grid of spacing 1/s1/s in PP. A hex is valid if det⁡J>0\det J > 0 at every point of it, as on the scaled Jacobian page.

The algorithm

The core step first proves that gg has a positive Jacobian on every voxel, then builds the grid. The test uses the 27 Bernstein coefficients of det⁡Dg\det Dg on each voxel, which is a polynomial of degree 2 in each variable.

  1. POLYCUBE-GRID(C, G, s)
  2. 1for each voxel c of C do
  3. 2if some Bernstein coefficient of det Dg on c is at most 0 then return failure
  4. 3K ← the grid points k / s, with k integer, that lie in some voxel of C
  5. 4for each grid point p of K do
  6. 5x_p ← g(p), by the trilinear map of a voxel that contains p
  7. 6H ← empty list
  8. 7for each voxel c of C and each cell q of side 1/s in c do
  9. 8append the hex of the 8 points x_p at the corners of q to H
  10. 9return H

Lines L1 and L2 are the certificate. Lines L3 to L5 map the grid, and lines L6 to L8 make one hex per grid cell. The code names a grid point by its integer key kk, so two cells that share a face use the same four points.

The full method. A polycube pipeline wraps this step, in words:

  1. Tetrahedralize the solid.
  2. Label each boundary triangle with one of the six directions ±x\pm x, ±y\pm y, ±z\pm z, often the one closest to its normal, and then fix the labels so that they describe a real polycube.
  3. Deform the tetrahedral mesh so that each boundary patch becomes flat and normal to its label. This gives a map ff from the solid to a polycube.
  4. Scale the polycube, sample it with an integer grid, and place each grid point in the solid by f−1f^{-1}, found by point location in the deformed tetrahedra.
  5. Add a padding layer of hexes on the boundary, and improve the mesh by untangling and smoothing.

Example

Take the L-shaped polycube with the voxels (0,0,0)(0, 0, 0), (1,0,0)(1, 0, 0) and (0,1,0)(0, 1, 0). Let gg be the identity, except at the two corners (1,1,0)(1, 1, 0) and (1,1,1)(1, 1, 1) on the inner edge of the L, which move to (54,54,0)(\frac54, \frac54, 0) and (54,54,1)(\frac54, \frac54, 1). This rounds the inner corner a little.

voxel least Bernstein coefficient largest volume of its image
(0,0,0)(0, 0, 0) 11 32\frac32 54\frac54
(1,0,0)(1, 0, 0) 34\frac34 54\frac54 11
(0,1,0)(0, 1, 0) 34\frac34 54\frac54 11

All coefficients are positive, so L2 accepts. With s=2s = 2 the grid has 6363 points and 2424 hexes, and 5656 boundary quads, 44 for each of the 1414 unit faces of the L. The grid point (12,12,0)(\frac12, \frac12, 0) goes to (916,916,0)(\frac{9}{16}, \frac{9}{16}, 0). The least corner Jacobian of a hex is 332=34⋅2−3\frac{3}{32} = \frac34 \cdot 2^{-3}, and the hex volumes add up to 134\frac{13}{4}, the sum of the voxel volumes.

Correctness

The full proof is below. A trilinear map restricted to a grid cell is again trilinear, so each hex is gg on its cell, and det⁡J\det J of the hex is s−3s^{-3} times det⁡Dg\det Dg. The Bernstein basis is at least 00 and adds up to 11, so positive coefficients give det⁡Dg>0\det Dg > 0 on the whole voxel. Thus, when L2 accepts, every hex at every resolution ss is valid at every point, not only at its corners. The hexes are conforming because the maps of two voxels agree on their shared face. If gg is also one to one on PP, the hexes tile the image g(P)g(P).

The conditions are exactly these: gg is trilinear on each voxel and given by its corner images, every voxel passes the Bernstein test, and, for a mesh of the solid, gg is one to one. The proof does not cover the steps that make gg. The survey of Pietroni and others notes that no current method guarantees a valid polycube labeling, nor a volumetric map without flipped tetrahedra. What is measured is the quality that published methods report on their test models. The tests compare the step with brute force on 500 random polycubes and maps: the set of grid points, face counts for conformity, positive corner Jacobians when the map is accepted, the volume sum, and the Bernstein form against direct values of det⁡J\det J.

Proof: The grid of a certified polycube map gives valid conforming hexes at every resolutionfull

Setting. A polycube PP is the union of a finite set CC of unit voxels c+[0,1]3c + [0, 1]^3 with c∈Z3c \in \mathbb{Z}^3. Each integer corner kk of a voxel has an image G(k)∈R3G(k) \in \mathbb{R}^3. On the voxel cc the map gc(c+x)=∑rBr(x) G(c+r)g_c(c + x) = \sum_{r} B_r(x)\, G(c + r), with x∈[0,1]3x \in [0, 1]^3, the sum over the 8 corners r∈{0,1}3r \in \{0, 1\}^3 and Br(x)=∏txtrt(1−xt)1−rtB_r(x) = \prod_t x_t^{r_t} (1 - x_t)^{1 - r_t}, is the trilinear map of the hex (G(c+r))r(G(c + r))_r. POLYCUBE-GRID(CC, GG, ss) rejects the input if, for some voxel, one of the 27 Bernstein coefficients of det⁡Dgc\det Dg_c is at most 00 (L1 and L2). Otherwise it maps every point k/sk / s of the grid 1sZ3∩P\frac{1}{s}\mathbb{Z}^3 \cap P by gg (L3 to L5) and returns, for every voxel cc and every cell q∈{0,…,s−1}3q \in \{0, \dots, s - 1\}^3, the hex whose corners are the images of the 8 corners c+(q+r)/sc + (q + r)/s of the cell (L6 to L9).

Claim.

  1. The algorithm stops after O(∣C∣)O(|C|) Bernstein tests and O(∣C∣s3)O(|C| s^3) further steps, and returns ∣C∣s3|C| s^3 hexes.
  2. The maps gcg_c agree on shared faces, edges and corners of voxels, so they define one continuous map g:P→R3g : P \to \mathbb{R}^3, and the image of a grid point does not depend on the voxel used in L5.
  3. The trilinear map of the hex of the cell qq of cc is H(u)=gc(c+(q+u)/s)H(u) = g_c(c + (q + u)/s) for u∈[0,1]3u \in [0, 1]^3, and det⁡DH(u)=s−3det⁡Dgc(c+(q+u)/s)\det DH(u) = s^{-3} \det Dg_c\big(c + (q + u)/s\big).
  4. If the input is accepted, det⁡Dgc>0\det Dg_c > 0 on every closed voxel. So every hex has det⁡J>0\det J > 0 on the whole closed unit cube, for every s≥1s \ge 1, and in particular its 8 corner Jacobians are positive.
  5. The hexes are conforming: a face of a grid cell that lies in two voxels of PP is a face of exactly two hexes, with the same four corner points, and the other faces are on the boundary of PP. The number of boundary quads is s2s^2 times the number of unit faces on the boundary of PP.
  6. The signed volumes of the hexes add up to ∑c∫det⁡Dgc\sum_c \int \det Dg_c, which does not depend on ss.
  7. If, in addition, gg is one to one on PP, the hexes are the images of the grid cells under gg and tile g(P)g(P) with disjoint interiors. So the output is a valid conforming hex mesh of g(P)g(P).

Proof of part 1. L1 and L2 do a constant amount of work per voxel. A voxel has (s+1)3(s + 1)^3 grid points and s3s^3 cells, so L3 to L8 take O(∣C∣s3)O(|C| s^3) steps.

Proof of part 2. Let two voxels share the face xt=1x_t = 1 of the first and xt=0x_t = 0 of the second. On it, BrB_r is 00 for the corners with rt≠1r_t \ne 1 in the first voxel, and the remaining four terms are the bilinear interpolation of the four shared corner images. The second voxel gives the same four corners with the same bilinear weights. The same argument with fewer free variables covers shared edges and corners. So the formulas agree wherever two voxels meet.

Proof of part 3. The map u↦c+(q+u)/su \mapsto c + (q + u)/s is affine in each coordinate on its own. A trilinear map composed with it is again of degree at most 11 in each utu_t, so HH is trilinear. A trilinear map is fixed by its values at the 8 corners of the cube, and HH takes at the corner rr the value g(c+(q+r)/s)g(c + (q + r)/s), which by part 2 is the point that L5 stores for the key sc+q+rs c + q + r. So HH is the trilinear map of the hex built in L8. The chain rule gives DH(u)=1sDgc(⋅)DH(u) = \frac{1}{s} Dg_c(\cdot), and the determinant of a 3×33 \times 3 matrix scales by s−3s^{-3}.

Proof of part 4. The column ∂xtgc\partial_{x_t} g_c has degree 00 in xtx_t and at most 11 in the other two variables. The determinant is a sum of products of one entry from each column, so it has degree at most 22 in each variable. It is therefore a unique combination det⁡Dgc(x)=∑i,j,lbijl βi(x0)βj(x1)βl(x2)\det Dg_c(x) = \sum_{i,j,l} b_{ijl}\, \beta_i(x_0) \beta_j(x_1) \beta_l(x_2) of the tensor Bernstein basis of degree 22, with β0(t)=(1−t)2\beta_0(t) = (1 - t)^2, β1(t)=2t(1−t)\beta_1(t) = 2t(1 - t) and β2(t)=t2\beta_2(t) = t^2. On [0,1][0, 1] these are at least 00 and add up to ((1−t)+t)2=1((1 - t) + t)^2 = 1, so the 27 products are at least 00 and add up to 11. Hence det⁡Dgc(x)≥min⁡bijl>0\det Dg_c(x) \ge \min b_{ijl} > 0 on the closed voxel. The code finds the bijlb_{ijl} from the values at {0,12,1}3\{0, \frac12, 1\}^3 by the exact one-dimensional rule b0=f(0)b_0 = f(0), b1=2f(12)−12(f(0)+f(1))b_1 = 2 f(\frac12) - \frac12 (f(0) + f(1)), b2=f(1)b_2 = f(1), applied in each direction. Part 3 then gives det⁡DH>0\det DH > 0 on the closed unit cube for every cell. The corner Jacobian at a corner of a trilinear hex equals det⁡DH\det DH at that corner, so it is positive too.

Proof of part 5. Grid points are named by integer keys, and L8 names the corners of the cell qq of cc by the keys sc+q+rs c + q + r. Two cells that share a face of the cubical grid use the same four keys on it, and by part 2 the same four points. A face of the cubical grid of spacing 1/s1/s lies in at most two cells of the grid, and it lies in two cells of PP exactly when it is inside PP or between two voxels of PP. A boundary face of a cell lies in a unit boundary face of PP, and each unit face holds s2s^2 such faces.

Proof of part 6. The signed volume of a hex is ∫[0,1]3det⁡DH\int_{[0,1]^3} \det DH. By part 3 and the change of variables x=(q+u)/sx = (q + u)/s, this is ∫det⁡Dgc\int \det Dg_c over the cell c+(q+[0,1]3)/sc + (q + [0, 1]^3)/s. The s3s^3 cells of a voxel cover it and meet only on their faces, so the sum over the cells is ∫det⁡Dgc\int \det Dg_c over the voxel.

Proof of part 7. By part 3 each hex is the set g(Q)g(Q) for its grid cell QQ. The grid cells tile PP, so the images g(Q)g(Q) cover g(P)g(P). The polycube PP is compact and gg is continuous and one to one, so gg is a homeomorphism from PP onto g(P)g(P). By the invariance of domain, the interior of g(Q)g(Q) is g(int⁡Q)g(\operatorname{int} Q). The interiors of two cells are disjoint, and gg is one to one, so their images are disjoint. ■\blacksquare

Remarks. The test of L2 is sufficient, not necessary: a positive determinant can have a Bernstein coefficient at most 00, and then the input is rejected, although subdivision of the voxel would certify it. Positive corner Jacobians of the voxel hexes are not enough. The test file has a voxel with corner Jacobians 44 and 1212 whose determinant is 4(1−2w)(1−4w)4(1 - 2w)(1 - 4w), which is negative for 14<w<12\frac14 < w < \frac12. Without the test, the grid of resolution 33 has hexes with the corner Jacobian −4243-\frac{4}{243}. Part 7 needs gg to be one to one. Local positivity alone does not give this when the image folds over itself across many voxels, so a full method must also check the boundary of g(P)g(P) for self-intersections.

Complexity

The test of L1 and L2 costs a constant per voxel. The grid has O(∣C∣s3)O(|C| s^3) points and exactly ∣C∣s3|C| s^3 hexes, so the step takes O(∣C∣s3)O(|C| s^3) time and space. In a full method the deformation of the tetrahedral mesh dominates. It is an iterative nonlinear optimization with no general bound on its number of steps.

Properties

  • Regular inside. Every inner vertex of the grid has 6 edges, except along the edges and corners of the polycube, where the irregular vertices sit.
  • Coarse structure. The polycube is a coarse block structure of the mesh. Its blocks can be meshed with different numbers of cells along each axis, as long as the counts match across blocks.
  • Sensitive to the polycube. Too few cubes give bad hexes near features. Too many give a complex structure with many irregular vertices.
  • No closure problem. Unlike plastering, there is no void to close, since the whole polycube is a grid.

Variants and improvements

  • Labeling first. Gregson and others label the boundary by the nearest axis and then fix it. Livesu and others search the labelings for one that meets the conditions for a valid polycube, based on the work of Eppstein and Mumford.
  • Deformation first. Some methods deform the solid freely until a polycube appears, and then read off the labels.
  • Flip-free energies. Fu, Bai and Liu use an energy that grows without bound when a tetrahedron flips, so the map stays locally one to one.
  • Generalized polycubes. Some methods allow a polycube that is not embedded in space, which allows fewer cubes for some shapes.
  • Spline output. The polycube map also gives a volumetric spline parameterization of the solid, for isogeometric analysis.

When to use it

Use a polycube method for a solid that looks roughly like a union of boxes, such as a part with flat faces at right angles, or a smooth organic shape where a few hundred irregular vertices are fine. For a solid with a sweep direction, sweeping is simpler. When the shape has features at many angles, frame field methods align hexes better, at the cost of less robust singularity structures.

Pitfalls

  • Positive corners are not enough. A voxel can have corner Jacobians 44 and 1212 while det⁡Dg=4(1−2w)(1−4w)\det Dg = 4(1 - 2w)(1 - 4w) is negative for 14<w<12\frac14 < w < \frac12. Without the Bernstein test, its grid of resolution 3 has hexes with corner Jacobian −4243-\frac{4}{243}.
  • The test is conservative. A positive det⁡Dg\det Dg can still have a coefficient at most 00. Then the code rejects the map, although subdividing the voxel might prove it valid.
  • Invalid labelings. A labeling that does not describe a polycube makes the deformation fail. Check it before the deformation.
  • Flipped tetrahedra. A deformation with flips gives a map that is not one to one, and then grid points land in the wrong place. Use a flip-free energy, or untangle the hex mesh afterwards.
  • Boundary hexes. At a polycube edge the hexes of two faces meet at a right angle in the polycube but may meet at a flat angle on the solid. Add a padding layer.

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)]
polycube_hex_meshing.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/polycube-hex-meshing/. The authors are listed in prov/ZACEGX.jsonl.

"""The integer grid step of polycube hex meshing.

A polycube is a finite set C of unit voxels, each named by the integer point
(i, j, k) of its lowest corner. The map g from the polycube to the solid is
given by the images of the integer voxel corners and is trilinear on each
voxel, so it is continuous across shared faces. The step meshes the
polycube with the grid of spacing 1/s and maps every grid point by g. The
hexes are the images of the grid cells. Before that, it checks on each voxel
that all 27 Bernstein coefficients of det Dg are positive, which proves that
g has a positive Jacobian on the whole polycube, so every hex is valid at
every resolution s.

Grid points are keys (a, b, c) of integers that stand for (a/s, b/s, c/s).
With int or Fraction input every value and sign is exact.
"""

from fractions import Fraction
from itertools import product
from typing import Dict, Iterable, List, Sequence, Tuple

from mg4geom import REF, bernstein_certified, trilinear

Key = Tuple[int, int, int]


def voxel_hex(corner_image: Dict[Key, Sequence], c: Key) -> List:
    """The trilinear hex of g on voxel c, in the standard corner order."""
    return [corner_image[(c[0] + a, c[1] + b, c[2] + d)] for a, b, d in REF]


def polycube_grid(voxels: Iterable[Key], corner_image: Dict[Key, Sequence], s: int):
    """Mesh the polycube at resolution s and map the grid by g.

    Returns None if some voxel fails the Bernstein test. Otherwise returns
    (points, hexes): points maps each grid key to its image, and each hex is a
    list of 8 keys in the standard order. Cost: O(|C| s^3) after the O(|C|) test.
    """
    cells = sorted(set(voxels))
    for c in cells:  # @line L1
        if not bernstein_certified(voxel_hex(corner_image, c)):  # @line L2
            return None
    owner: Dict[Key, Key] = {}
    for c in cells:  # @line L3
        for a, b, d in product(range(s + 1), repeat=3):
            owner.setdefault((s * c[0] + a, s * c[1] + b, s * c[2] + d), c)
    points: Dict[Key, Tuple] = {}
    for key, c in owner.items():  # @line L4
        local = [Fraction(key[t] - s * c[t], s) for t in range(3)]
        points[key] = trilinear(voxel_hex(corner_image, c), *local)  # @line L5
    hexes: List[List[Key]] = []  # @line L6
    for c in cells:  # @line L7
        for q in product(range(s), repeat=3):
            hexes.append([(s * c[0] + q[0] + a, s * c[1] + q[1] + b, s * c[2] + q[2] + d) for a, b, d in REF])  # @line L8
    return points, hexes  # @line L9


def hex_points(points: Dict[Key, Tuple], hexes: Sequence[Sequence[Key]]) -> List[List[Tuple]]:
    """The hexes with their corner coordinates in place of their keys."""
    return [[points[k] for k in hx] for hx in hexes]


def identity_images(voxels: Iterable[Key]) -> Dict[Key, Tuple]:
    """The corner images of the identity map, as Fractions."""
    out: Dict[Key, Tuple] = {}
    for c in voxels:
        for a, b, d in REF:
            k = (c[0] + a, c[1] + b, c[2] + d)
            out[k] = tuple(Fraction(x) for x in k)
    return out


def boundary_faces(voxels: Iterable[Key]) -> int:
    """The number of unit faces of the polycube that belong to one voxel only."""
    cells = set(voxels)
    n = 0
    for c in cells:
        for t in range(3):
            for step in (-1, 1):
                nb = list(c)
                nb[t] += step
                if tuple(nb) not in cells:
                    n += 1
    return n


def all_voxels_certified(voxels: Iterable[Key], corner_image: Dict[Key, Sequence]) -> bool:
    """True when every voxel passes the Bernstein test of L1 and L2."""
    return all(bernstein_certified(voxel_hex(corner_image, c)) for c in set(voxels))
test_polycube_hex_meshing.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/polycube-hex-meshing/. The authors are listed in prov/ZACEGX.jsonl.

import random
from fractions import Fraction as F
from itertools import product

from mg4geom import FACES, REF, corner_jacobians, hex_volume, jacobian_bernstein, jacobian_det, trilinear
from polycube_hex_meshing import (
    all_voxels_certified,
    boundary_faces,
    hex_points,
    identity_images,
    polycube_grid,
    voxel_hex,
)


def unchecked_grid(voxels, corner_image, s):
    """The grid hexes of the map without the Bernstein test, for the brute force checks."""
    out = []
    for c in sorted(set(voxels)):
        h = voxel_hex(corner_image, c)
        for q in product(range(s), repeat=3):
            out.append([trilinear(h, *(F(q[t] + r[t], s) for t in range(3))) for r in REF])
    return out


def bernstein_value(coeffs, u, v, w):
    basis = [lambda t: (1 - t) ** 2, lambda t: 2 * t * (1 - t), lambda t: t * t]
    total = 0
    for i, j, k in product(range(3), repeat=3):
        total += coeffs[9 * i + 3 * j + k] * basis[i](u) * basis[j](v) * basis[k](w)
    return total


def check_mesh(voxels, img, s, full=False):
    cells = set(voxels)
    result = polycube_grid(voxels, img, s)
    if full:
        assert (result is not None) == all_voxels_certified(voxels, img)
    if result is None:
        return False
    points, hexes = result
    assert len(hexes) == len(cells) * s**3
    # brute force: the grid points are the keys that lie in some voxel
    lo = [s * min(c[t] for c in cells) for t in range(3)]
    hi = [s * max(c[t] for c in cells) + s for t in range(3)]
    expect = set()
    for k in product(*(range(lo[t], hi[t] + 1) for t in range(3))):
        if any(all(s * c[t] <= k[t] <= s * c[t] + s for t in range(3)) for c in cells):
            expect.add(k)
    assert set(points) == expect
    # conformity: every face of the grid is in one hex on the boundary and two inside
    count = {}
    for hx in hexes:
        for f in FACES:
            key = frozenset(hx[i] for i in f)
            count[key] = count.get(key, 0) + 1
    assert set(count.values()) <= {1, 2}
    assert sum(1 for c in count.values() if c == 1) == s * s * boundary_faces(cells)
    # validity: every hex has positive corner Jacobians, equal to det Dg / s^3 at the grid points
    hp = hex_points(points, hexes)
    for hx, keys in zip(hp, hexes):
        assert all(d > 0 for d in corner_jacobians(hx))
    if full:
        # continuity: a shared grid point has the same image in every voxel that contains it
        for k, p in points.items():
            for c in cells:
                if all(s * c[t] <= k[t] <= s * c[t] + s for t in range(3)):
                    assert trilinear(voxel_hex(img, c), *(F(k[t] - s * c[t], s) for t in range(3))) == p
        # the sub-hex Jacobian is the voxel Jacobian scaled by s^-3
        c = min(cells)
        h = voxel_hex(img, c)
        assert corner_jacobians(hp[0])[0] == jacobian_det(h, 0, 0, 0) / s**3
        # volume: the hexes add up to the volume of the image, for every s
        assert sum(hex_volume(hx) for hx in hp) == sum(hex_volume(voxel_hex(img, c)) for c in cells)
    return True


def test_page_example():
    voxels = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
    img = identity_images(voxels)
    for z in (0, 1):
        img[(1, 1, z)] = (F(5, 4), F(5, 4), F(z))
    assert [min(jacobian_bernstein(voxel_hex(img, c))) for c in voxels] == [1, F(3, 4), F(3, 4)]
    assert check_mesh(voxels, img, 2, full=True)
    points, hexes = polycube_grid(voxels, img, 2)
    assert len(points) == 63 and len(hexes) == 24 and boundary_faces(voxels) == 14
    assert points[(2, 2, 0)] == (F(5, 4), F(5, 4), 0)
    assert points[(1, 1, 0)] == (F(9, 16), F(9, 16), 0)
    hp = hex_points(points, hexes)
    assert sum(hex_volume(hx) for hx in hp) == F(13, 4)
    assert min(min(corner_jacobians(hx)) for hx in hp) == F(3, 32)


def twisted_voxel():
    img = {}
    for a, b in product((0, 1), repeat=2):
        img[(a, b, 0)] = (F(2 * a - 1), F(2 * b - 1), F(0))
        img[(a, b, 1)] = (F(1 - 2 * a), F(3 - 6 * b), F(1))
    return img


def test_twisted_voxel_is_rejected_although_its_corners_are_positive():
    img = twisted_voxel()
    h = voxel_hex(img, (0, 0, 0))
    assert sorted(set(corner_jacobians(h))) == [4, 12]
    assert min(jacobian_bernstein(h)) == -8
    # det Dg = 4 (1 - 2 w)(1 - 4 w), negative for 1/4 < w < 1/2
    for w in (0, F(1, 4), F(1, 3), F(1, 2), 1):
        assert jacobian_det(h, F(1, 2), F(1, 2), w) == 4 * (1 - 2 * w) * (1 - 4 * w)
    for s in (1, 2, 3, 4):
        assert polycube_grid([(0, 0, 0)], img, s) is None
    # without the test the grid of resolution 3 has inverted hexes
    mins = {s: min(min(corner_jacobians(hx)) for hx in unchecked_grid([(0, 0, 0)], img, s)) for s in (1, 2, 3)}
    assert mins == {1: 4, 2: 0, 3: F(-4, 243)}


def test_affine_maps():
    rng = random.Random(11)
    for _ in range(12):
        while True:
            a = [[F(rng.randint(-3, 3), 2) for _ in range(3)] for _ in range(3)]
            d = (
                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])
            )
            if d > 0:
                break
        voxels = random_polycube(rng, 3)
        img = {}
        for c in voxels:
            for r in REF:
                k = tuple(c[t] + r[t] for t in range(3))
                img[k] = tuple(sum(a[i][j] * k[j] for j in range(3)) + i for i in range(3))
        s = rng.randint(1, 2)
        points, hexes = polycube_grid(voxels, img, s)
        for hx in hex_points(points, hexes):
            assert set(corner_jacobians(hx)) == {d / s**3}
        assert check_mesh(voxels, img, s)


def random_polycube(rng, size):
    cells = {(rng.randint(0, 2), rng.randint(0, 2), rng.randint(0, 1))}
    while len(cells) < size:
        c = list(rng.choice(sorted(cells)))
        t = rng.randrange(3)
        c[t] += rng.choice((-1, 1))
        cells.add(tuple(c))
    return sorted(cells)


def test_random_polycubes():
    rng = random.Random(2016)
    meshed = 0
    for trial in range(500):
        voxels = random_polycube(rng, rng.choice((1, 1, 1, 2, 2, 3)))
        # integer images: the identity scaled by 8 plus a random move, which keeps the arithmetic fast
        img = identity_images(voxels)
        spread = rng.choice((1, 2, 3))
        for k in img:
            img[k] = tuple(8 * k[t] + rng.randint(-spread, spread) for t in range(3))
        s = rng.choice((1, 1, 2, 2, 3))
        ok = check_mesh(voxels, img, s, full=(trial % 100 == 0))
        meshed += ok
        if trial % 20 == 0:
            # the 27 coefficients reproduce det J at a random point (checks the Bernstein form)
            h = voxel_hex(img, voxels[0])
            u, v, w = (F(rng.randint(0, 12), 12) for _ in range(3))
            coeffs = jacobian_bernstein(h)
            assert bernstein_value(coeffs, u, v, w) == jacobian_det(h, u, v, w)
            if ok:
                assert jacobian_det(h, u, v, w) >= min(coeffs) > 0
    assert 100 < meshed < 500

History

Tarini, Hormann, Cignoni and Montani defined polycube maps in 2004 to store textures on surfaces without seams. Gregson, Sheffer and Zhang used a volumetric polycube deformation for all-hex meshing in 2011, with a padding layer to fix the boundary hexes. In 2013 Livesu, Vining, Sheffer, Gregson and Scateni turned the choice of the labeling into a search under the graph conditions of Eppstein and Mumford. Later methods added flip-free energies and generalized polycubes.

References

  1. Marco Tarini, Kai Hormann, Paolo Cignoni and Claudio Montani, PolyCube-Maps, ACM Transactions on Graphics 23(3), 2004, the definition of a polycube and of a polycube map (general locator)
  2. James Gregson, Alla Sheffer and Eugene Zhang, All-hex mesh generation via volumetric PolyCube deformation, Computer Graphics Forum 30(5), 2011, 1407 to 1416, the deformation that turns surface normals to the axes, the grid of the polycube, the inverse map and the padding layer (general locator)
  3. Marco Livesu, Nicholas Vining, Alla Sheffer, James Gregson and Riccardo Scateni, PolyCut, monotone graph-cuts for PolyCube base-complex construction, ACM Transactions on Graphics 32(6), 2013, article 171, the labeling of the boundary by axes under topological conditions for a valid polycube (general locator)
  4. Xiao-Ming Fu, Chong-Yang Bai and Yang Liu, Efficient volumetric PolyCube-map construction, Computer Graphics Forum 35(7), 2016, 97 to 106, a deformation energy that grows without bound for inverted tetrahedra (general locator)
  5. David Eppstein and Elena Mumford, Steinitz theorems for orthogonal polyhedra, Proceedings of the Symposium on Computational Geometry, 2010, 429 to 438, the graph conditions for an orthogonal polyhedron (general locator)
  6. 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 polycube maps, which states that neither the labeling nor the flip-free map is guaranteed

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