Algorithm Search⌘K

Algorithmcore

Paving

Also called Blacker-Stephenson paving.

Blacker and Stephenson's all-quadrilateral mesher that lays rows of quads inward from the boundary and closes the front where rows meet, with good boundary elements.

Time
O(n^2) worst
Space
O(n) extra
Where
n = the number of front nodes
Properties
deterministicexactiterative
Origin
Ted D. Blacker, Michael B. Stephenson, 1991

Paving is a method that fills a planar region with quadrilaterals only. It starts at the boundary and lays a row of quads along it, then a row along the new inner boundary, and so on, so the mesh grows inward like the rows of stones on a path. Each row follows the shape of the boundary, so the quads near the boundary are well shaped and aligned with it, which is where a finite element solution often needs the most accuracy. Where rows from different sides meet, paving joins the fronts by seaming and closes small remaining holes with fixed patterns, then smooths the mesh. Ted Blacker and Michael Stephenson published it in 1991. There is no proof that paving always succeeds, and no bound on the quality of its quads. This page implements and proves one core step: laying one row.

In plain words

Picture laying tiles on the floor of an odd shaped room. Lay a row of tiles along every wall first, so the edge of the room looks neat. Then lay a second row along the inside edge of the first row, and so on, moving toward the middle.

At a corner of the room, one tile bends the row around the corner. Along a wall, each tile is about as tall as it is wide. In the middle, rows from opposite walls meet, and the last gaps need special care. Tiles with four sides can only fill a closed loop that has an even number of sides, so the method counts the sides first. The middle is where most bad tiles end up, so the method nudges the tile corners at the end to even them out.

The problem

The input is a planar region bounded by closed polygons, with nodes on the boundary that have an even total number of edges. The output is a conforming mesh of the region by convex quadrilaterals, using the given boundary nodes, with quads near the boundary that are close to squares and aligned with it. The core step solves a smaller problem: given a closed front, a simple counterclockwise polygon around the empty region, return one row of valid quads along it and the new, smaller front, or report that no row of this kind fits.

The algorithm

The full method repeats the core step and adds operations for the places where the step fails. The core step classifies each front node by its interior angle. A row end is a sharp corner, which turns the row around; it gets no new node, and one quad covers both of its edges. A row side is a node along a straight or gently curved part; it gets a new node inside the front. This code uses a row end below 135°135° and a row side up to 240°240°; these thresholds are parameters of the code, not values from the paper. Paving has more node types, row corners and row reversals, for reflex nodes.

  1. PAVE-ROW(front x_0..x_{n−1})
  2. 1classify each node as a row end or a row side by its interior angle; fail on other nodes
  3. 2for each row end c: q_c ← x_{c−1} + x_{c+1} − x_c, the new node of both neighbours
  4. 3for each other row side i: y_i ← the point inside at distance h_i from both edge lines at x_i, h_i ← mean length of the two edges
  5. 4make one quad (x_{c−1}, x_c, x_{c+1}, q_c) per row end and one quad (x_i, x_{i+1}, y_{i+1}, y_i) per other edge
  6. 5the new front ← the new nodes in front order, each q_c once
  7. 6if some quad is not strictly convex and counterclockwise then fail
  8. 7if the new front is not simple or not counterclockwise then fail
  9. 8return the quads and the new front

L6 and L7 use exact orientation tests on the float coordinates, converted to fractions without rounding. The full method runs PAVE-ROW until the front is small, and between rows it smooths the nodes, adds or removes nodes to keep the quads close to square (row adjustment), joins front nodes across sharp angles and narrow gaps (seaming), detects fronts that cross each other and splits them, and closes the last small fronts with fixed patterns.

Example

Take the square [0,4]2[0,4]^2 with 16 boundary nodes at unit spacing. The four corners have interior angle 90°90° and are row ends; the other 12 nodes are row sides, with h=1h = 1 and new nodes one unit inside. The corner (0,0)(0,0) gives the quad (0,1),(0,0),(1,0),(1,1)(0,1), (0,0), (1,0), (1,1) in front order. The row has 12 unit squares, exactly the outer ring of the 4×44 \times 4 grid, and the new front is the square [1,3]2[1,3]^2 with 8 nodes. A second row fails: on that small square, the row ends are only 2 nodes apart, so their quads would share an edge. A closure rule fills it with 4 squares.

For the rectangle [0,6]×[0,3][0,6] \times [0,3], the row has 14 quads and leaves the strip [1,5]×[1,2][1,5] \times [1,2] with 10 nodes, which is one row of 4 quads that closure must fill. For a round front of 16 nodes on a circle of radius 3, every node is a row side, since the interior angle is 157.5°157.5°. The edges have length 1.17051.1705, the new nodes lie on a circle of radius 1.80651.8065, the area inside the front falls from 27.55327.553 to 9.9919.991, and a second row succeeds as well.

front quads in the row nodes of the new front next row
square [0,4]2[0,4]^2 12 8 fails: row ends too close
rectangle 6×36 \times 3 14 10 fails: row ends too close
square [0,7]2[0,7]^2 24 20 succeeds, 16 quads
circle, 16 nodes 16 16 succeeds

Correctness

The proof file has two results. The first is the parity rule: in any quad mesh, each quad has 4 edge sides, interior edges have two and boundary edges one, so 4Q=2Eint+Ebnd4Q = 2E_\text{int} + E_\text{bnd} and the boundary has an even number of edges. Paving therefore makes the boundary count even before it starts. The row step keeps the parity: each row end removes its own node and merges two new nodes, so the new front has n−2en - 2e nodes for ee row ends.

The second result is that an accepted row is a valid mesh of the band between the two fronts. The boundaries of the quads add up to the old front minus the new front, because each radial edge appears in two neighbouring quads with opposite directions. So the winding numbers add up the same way. If every quad is strictly convex and both fronts are simple and counterclockwise, each point of the band lies in exactly one quad, and the areas add up exactly. The code tests every hypothesis exactly, so it never returns an invalid row.

What is not proved: that a row exists, that paving as a whole closes every front, and any bound on the quality of the quads. These are measured, case by case.

Proof: A quad mesh has an even number of boundary edges, and an accepted paving row is a valid quad mesh of the band between two frontsfull

What is proved and what is not. Two results are proved: the parity rule, which every all-quad mesher must respect, and the correctness of one accepted row, the core step of paving as it is implemented here. Nothing is proved about the whole paving method. Blacker and Stephenson give no quality guarantee and no proof that the fronts always close; paving relies on smoothing, seaming, row adjustment and closure rules that are tuned by experiment. The step here can fail, and it says so.

Theorem 1 (parity). In a mesh of a planar region by QQ quads, in which every edge lies in one quad (a boundary edge) or two quads (an interior edge), the number EbE_b of boundary edges is even.

Proof. Count pairs (quad, edge of that quad), the edge sides. Each quad has 4 edges, so there are 4Q4Q pairs. Each interior edge is in two pairs and each boundary edge in one, so 4Q=2Ei+Eb4Q = 2E_i + E_b. Then Eb=4Q−2EiE_b = 4Q - 2E_i is even. □\square

So a paving front, which becomes the boundary of the quads inside it, must have an even number of edges. Paving makes the boundary discretisation even before it starts, and the step below keeps the parity.

Setting. The old front FF is a simple polygon x0,…,xn−1x_0, \dots, x_{n-1} in counterclockwise order around the empty region. A row end cc has no new node, and the point qc=xc−1+xc+1−xcq_c = x_{c-1} + x_{c+1} - x_c is the new node of both of its neighbours. Row ends are at least 3 apart along the front. Every other node ii has the new node yiy_i. The quads are (xi,xi+1,yi+1,yi)(x_i, x_{i+1}, y_{i+1}, y_i) for an edge whose ends are both row sides, and (xc−1,xc,xc+1,qc)(x_{c-1}, x_c, x_{c+1}, q_c) for a row end cc, which covers its two edges. The new front F′F' lists the new nodes in the order of the old nodes, with each qcq_c once.

Lemma 2 (boundary chain). As 1-chains, ∑Q∂Q=∂F−∂F′\sum_Q \partial Q = \partial F - \partial F'.

Proof. Each old front edge is in exactly one quad, forward: the side quad on that edge, or the corner quad of the row end at one of its ends. No edge is in two quads, because row ends are at least 3 apart, so an edge has at most one row end at its ends. Each row side node ii has one radial edge between xix_i and its new node. The quad on the edge to the left of xix_i uses it as xi→yix_i \to y_i, and the quad on the edge to its right uses it as yi→xiy_i \to x_i; this holds also when one of these quads is a corner quad, since its edges xc+1→qcx_{c+1} \to q_c and qc→xc−1q_c \to x_{c-1} are the radial edges of the two neighbours of the row end. So the radial edges cancel. The remaining edges are the top edges yi+1→yiy_{i+1} \to y_i of the side quads, which are the edges of F′F' reversed; between two neighbours of a row end the top edge would join qcq_c to itself and is absent from both sides. □\square

Theorem 3 (one row). If every quad is strictly convex and counterclockwise and F′F' is a simple polygon with positive signed area, then the quads have pairwise disjoint interiors, their union is the closure of the region between FF and F′F', the region inside F′F' lies inside FF, and the sum of the quad areas equals the area inside FF minus the area inside F′F'. The new front has n−2en - 2e nodes, where ee is the number of row ends, so its length has the parity of nn.

Proof. By Lemma 2, for every point xx not on an edge, the winding numbers satisfy ∑Qw(∂Q,x)=w(F,x)−w(F′,x)\sum_Q w(\partial Q, x) = w(F, x) - w(F', x). Both fronts are simple and counterclockwise, so w(F,⋅)w(F, \cdot) and w(F′,⋅)w(F', \cdot) are 1 inside and 0 outside. Each strictly convex counterclockwise quad has winding number 1 inside and 0 outside. So the left side is a sum of terms in {0,1}\{0, 1\}, and the right side is in {−1,0,1}\{-1, 0, 1\}, hence in {0,1}\{0, 1\}. A point inside F′F' therefore lies inside FF. A point inside FF and outside F′F' is in exactly one quad, and every other point is in none. Edges have measure zero, which gives the claims on the interiors and the union. The shoelace sums are additive like the chains, which gives the area identity. For the count, each row end removes itself and merges the two new nodes of its neighbours into one, so the new front has n−e−e=n−2en - e - e = n - 2e nodes. □\square

The code checks every hypothesis of Theorem 3 exactly (L6 and L7), so an accepted row is always a valid conforming quad mesh of its band. The tests check the area identity in exact arithmetic, the boundary of the row, the parity count 4Q=2Ei+Eb4Q = 2E_i + E_b, and, for 4000 random points, that no point lies in two quads. On the square [0,4]2[0,4]^2 with unit spacing, the row is exactly the outer ring of 12 unit squares of the structured grid.

Termination. One step does O(n2)O(n^2) work and stops. Repeating the step on the new front makes a sequence of fronts with strictly decreasing area, by Theorem 3, as long as the steps succeed; with a fixed node spacing the fronts also lose nodes at row ends. But a step can fail, as on the inner 2×22 \times 2 square, whose row ends are only 2 apart, or on a thin strip, where the rows from the two sides cross. There, paving needs its other operations: seams, which join front nodes across a narrow gap, row adjustments, and closure rules for small fronts. Those operations are not proved to always succeed.

What is not proved. No bound on the angles or the aspect ratio of the quads is proved, for the step or for paving. The step's angle thresholds are parameters of this code, not values from the paper. When rows from different parts of the front meet, the quads near the meeting line can be poor, and paving smooths them; the result of that smoothing is measured, not proved.

Complexity

The row step costs O(n)O(n) for the classification, the new nodes and the quads, and O(n2)O(n^2) for the exact test that the new front is simple. A sweep line or a grid of buckets brings the test down for typical fronts. Paving as a whole meshes a region with NN quads in a number of rows that is about the ratio of the region width to the element size. The intersection tests between fronts dominate in practice, and implementations use spatial search structures for them.

Properties

  • All quads. The output has no triangles, when closure succeeds.
  • Boundary aligned. The rows follow the boundary, so the quads near it are close to squares and aligned with it.
  • Parity. Every front must have an even number of edges, a hard rule for any all-quad mesh.
  • No guarantee. No bound on angles or on success is proved; the irregular nodes collect where the fronts meet.
  • Row step proved. An accepted row is a valid mesh of its band, with exact checks.

Variants and improvements

  • Plastering. Blacker and Meyers extended the idea to 3D, filling a volume with hexahedra layer by layer. Closing the fronts is much harder in 3D, and plastering is not robust in general.
  • Q-Morph. Owen and coauthors run the same kind of advancing front of quads over an existing triangle mesh, which makes the closure and the intersection tests easier; see Q-Morph.
  • Blossom-Quad. An indirect method that pairs the triangles of a triangle mesh into quads by a perfect matching; see Blossom-Quad.
  • Surface paving. Paving on a CAD face runs in the parameter plane with the surface metric; see surface meshing in parametric space.
  • Size fields. The row height can follow a size field instead of the local edge length, for graded meshes.

When to use it

Use paving when an all-quad mesh is needed on a planar region or a CAD face, with good elements along the boundary, for example for structural analysis with the finite element method, where boundary stresses matter. For a simple region that maps to a rectangle, a structured grid is better. For large meshes or complex regions, an indirect method such as Q-Morph or Blossom-Quad is often more robust, because the triangle mesh already solves the hard global problem.

Pitfalls

  • Odd boundary count. A front with an odd number of edges cannot be meshed by quads at all. Fix the count before meshing.
  • Colliding rows. Rows from opposite sides of a narrow region cross. Test the new front for self intersection, as in L7, and seam or split the front.
  • Sharp corners. Without row ends at sharp corners, the row quads there fold. Classify the nodes.
  • Poor interior. The irregular nodes all end up where the fronts meet, often with poor quads. Smooth the mesh, and accept that the interior is worse than the boundary.
  • Float tests. Front intersection with float tests can miss a touch and leave overlapping quads. Use exact tests.

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.

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

"""Small exact tools for triangle and tetrahedral meshes, used by the mg3 pages.

Points are tuples of int, fractions.Fraction or float. Every predicate here is
exact when the coordinates are int or Fraction. A float converts to a Fraction
without rounding, so exact() followed by a predicate gives the exact sign for
the float points as they are stored. Nothing here builds a mesh; each page
builds its own.
"""

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

Point = Tuple


def exact(p: Point) -> Tuple[Fraction, ...]:
    """The point p with each coordinate converted to Fraction, without rounding."""
    return tuple(Fraction(c) for c in p)


def to_grid(x: float, bits: int = 20) -> Fraction:
    """The nearest multiple of 2**-bits to x, as a Fraction."""
    return Fraction(round(x * (1 << bits)), 1 << bits)


def orient2d(a: Point, b: Point, c: Point):
    """Twice the signed area of the triangle a, b, c; positive if counterclockwise."""
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def incircle(a: Point, b: Point, c: Point, d: Point):
    """Positive if d is inside the circle through a, b, c (a, b, c counterclockwise),
    zero if on it, negative if outside."""
    rows = []
    for p in (a, b, c):
        dx, dy = p[0] - d[0], p[1] - d[1]
        rows.append((dx, dy, dx * dx + dy * dy))
    (a0, a1, a2), (b0, b1, b2), (c0, c1, c2) = rows
    return a0 * (b1 * c2 - b2 * c1) - a1 * (b0 * c2 - b2 * c0) + a2 * (b0 * c1 - b1 * c0)


def orient3d(a: Point, b: Point, c: Point, d: Point):
    """Six times the signed volume of the tetrahedron a, b, c, d.

    Positive if d lies on the side of the plane abc toward which (b - a) x (c - a)
    points, that is, if a, b, c look clockwise from d."""
    u = (b[0] - a[0], b[1] - a[1], b[2] - a[2])
    v = (c[0] - a[0], c[1] - a[1], c[2] - a[2])
    w = (d[0] - a[0], d[1] - a[1], d[2] - a[2])
    return (u[0] * (v[1] * w[2] - v[2] * w[1])
            - u[1] * (v[0] * w[2] - v[2] * w[0])
            + u[2] * (v[0] * w[1] - v[1] * w[0]))


def twice_area(poly: Sequence[Point]):
    """Twice the signed area of a polygon by the shoelace formula."""
    n = len(poly)
    return sum(poly[i][0] * poly[(i + 1) % n][1] - poly[(i + 1) % n][0] * poly[i][1] for i in range(n))


def segments_cross(a: Point, b: Point, c: Point, d: Point) -> bool:
    """True if the open segments ab and cd cross at one point inside both."""
    return (orient2d(a, b, c) * orient2d(a, b, d) < 0
            and orient2d(c, d, a) * orient2d(c, d, b) < 0)


def edge_map(cells: Iterable[Sequence[int]]) -> Dict[Tuple[int, int], int]:
    """Map each directed edge (i, j) of a list of counterclockwise polygons
    (triangles or quads, given by vertex indices) to the index of its cell.
    Raises ValueError if a directed edge is used twice."""
    m: Dict[Tuple[int, int], int] = {}
    for k, cell in enumerate(cells):
        n = len(cell)
        for s in range(n):
            e = (cell[s], cell[(s + 1) % n])
            if e in m:
                raise ValueError("directed edge %r used twice" % (e,))
            m[e] = k
    return m


def boundary_edges(cells: Iterable[Sequence[int]]) -> List[Tuple[int, int]]:
    """The directed edges whose reverse is not an edge of any cell."""
    m = edge_map(cells)
    return [e for e in m if (e[1], e[0]) not in m]


def is_valid_planar_mesh(points: Sequence[Point], cells: Sequence[Sequence[int]]) -> bool:
    """Exact check that every cell is a strictly convex counterclockwise polygon
    and that no directed edge is used twice. With the area sum of the caller,
    this shows a conforming mesh of a simply covered region."""
    try:
        edge_map(cells)
    except ValueError:
        return False
    for cell in cells:
        n = len(cell)
        for s in range(n):
            a, b, c = points[cell[s]], points[cell[(s + 1) % n]], points[cell[(s + 2) % n]]
            if orient2d(a, b, c) <= 0:
                return False
    return True


def mean_ratio(a: Point, b: Point, c: Point) -> float:
    """The mean ratio 4 sqrt(3) A / (sum of squared edge lengths) of a triangle,
    in floats; 1 for the equilateral triangle, 0 for a flat one, negative if the
    triangle is clockwise."""
    s = sum(float((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2) for p, q in ((a, b), (b, c), (c, a)))
    return 2.0 * math.sqrt(3.0) * float(orient2d(a, b, c)) / s
paving.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/paving/. The authors are listed in prov/AS3MCY.jsonl.

"""The core step of paving: lay one row of quads inside a closed front.

This is one step of Blacker and Stephenson's paving, not the whole mesher.
The front is a closed polygon in counterclockwise order around the region that
is still empty. Each front node is classified by its interior angle:

* a row end, if the angle is below END_ANGLE: the node gets no new node, and
  one quad (prev, node, next, q) covers both of its edges, with
  q = prev + next - node, the fourth corner of a parallelogram;
* a row side, otherwise: the node gets a new node at the distance h from the
  lines of both of its edges, inside, where h is the mean length of the two
  edges.

The new nodes of the two neighbours of a row end are merged into q. The row is
accepted only if every quad is strictly convex and counterclockwise and the
new front is a simple polygon, tested exactly on the float coordinates (each
float converts to a Fraction without rounding). Otherwise the step reports
failure. The angle thresholds are parameters of this code; paving as published
uses its own classification with more node types (row corners and reversals),
smoothing, seaming and closure, which are not here.
"""

import math
from typing import List, Optional, Sequence, Tuple

from mg3geom import exact, is_valid_planar_mesh, orient2d, twice_area

Vec = Tuple[float, float]
END_ANGLE = 3 * math.pi / 4
MAX_SIDE_ANGLE = 4 * math.pi / 3


def interior_angle(p: Vec, q: Vec, r: Vec) -> float:
    """The interior angle at q of a counterclockwise polygon with edges pq, qr."""
    u = (p[0] - q[0], p[1] - q[1])
    v = (r[0] - q[0], r[1] - q[1])
    a = math.atan2(u[0] * v[1] - u[1] * v[0], u[0] * v[0] + u[1] * v[1])
    # angle from v to u counterclockwise is the interior angle for a CCW polygon
    return (-a) % (2 * math.pi)


def classify(front: Sequence[Vec]) -> List[str]:
    n = len(front)
    out = []
    for i in range(n):
        a = interior_angle(front[i - 1], front[i], front[(i + 1) % n])
        out.append("end" if a < END_ANGLE else "side" if a < MAX_SIDE_ANGLE else "other")
    return out


def inward_offset(p: Vec, q: Vec, r: Vec, h: float) -> Vec:
    """The point inside a counterclockwise polygon at the distance h from the
    lines pq and qr, on the bisector at q."""
    def unit_in(a, b):
        dx, dy = b[0] - a[0], b[1] - a[1]
        L = math.hypot(dx, dy)
        return (-dy / L, dx / L)   # left normal, inward for a CCW polygon
    na, nb = unit_in(p, q), unit_in(q, r)
    s = 1.0 + na[0] * nb[0] + na[1] * nb[1]
    return (q[0] + h * (na[0] + nb[0]) / s, q[1] + h * (na[1] + nb[1]) / s)


def is_simple_polygon(poly: Sequence) -> bool:
    """Exact test: non-adjacent closed edges do not meet, adjacent edges do not fold back."""
    def on(p, q, x):
        return min(p[0], q[0]) <= x[0] <= max(p[0], q[0]) and min(p[1], q[1]) <= x[1] <= max(p[1], q[1])

    def meet(a, b, c, d):
        o1, o2, o3, o4 = orient2d(a, b, c), orient2d(a, b, d), orient2d(c, d, a), orient2d(c, d, b)
        if o1 * o2 < 0 and o3 * o4 < 0:
            return True
        return ((o1 == 0 and on(a, b, c)) or (o2 == 0 and on(a, b, d))
                or (o3 == 0 and on(c, d, a)) or (o4 == 0 and on(c, d, b)))
    n = len(poly)
    if n < 3:
        return False
    for i in range(n):
        a, b, c = poly[i], poly[(i + 1) % n], poly[(i + 2) % n]
        if orient2d(a, b, c) == 0 and (a[0] - b[0]) * (c[0] - b[0]) + (a[1] - b[1]) * (c[1] - b[1]) > 0:
            return False
        for j in range(i + 2, n):
            if not (i == 0 and j == n - 1) and meet(poly[i], poly[(i + 1) % n], poly[j], poly[(j + 1) % n]):
                return False
    return True


def pave_row(front: Sequence[Vec]):
    """One row of paving. Returns (points, quads, new_front, None) on success,
    where points = front + new nodes, quads are counterclockwise index 4-tuples
    and new_front is a list of indices into points; or (None, None, None, reason)."""
    n = len(front)
    kind = classify(front)  # @line L1
    if "other" in kind:
        return None, None, None, "a reflex node needs a row corner or reversal, not handled here"
    ends = [i for i in range(n) if kind[i] == "end"]
    for a in ends:
        for b in ends:
            if a != b and min((a - b) % n, (b - a) % n) < 3:
                return None, None, None, "two row ends are too close"
    points: List[Vec] = list(front)
    new_index = [None] * n
    for c in ends:  # @line L2
        p, q, r = front[c - 1], front[c], front[(c + 1) % n]
        points.append((p[0] + r[0] - q[0], p[1] + r[1] - q[1]))
        new_index[c - 1] = new_index[(c + 1) % n] = len(points) - 1
    for i in range(n):  # @line L3
        if kind[i] == "side" and new_index[i] is None:
            p, q, r = front[i - 1], front[i], front[(i + 1) % n]
            h = (math.dist(p, q) + math.dist(q, r)) / 2
            points.append(inward_offset(p, q, r, h))
            new_index[i] = len(points) - 1
    quads: List[Tuple[int, int, int, int]] = []
    for i in range(n):  # @line L4
        j = (i + 1) % n
        if kind[j] == "end":
            quads.append((i, j, (j + 1) % n, new_index[i]))
        elif kind[i] != "end":
            quads.append((i, j, new_index[j], new_index[i]))
    new_front: List[int] = []
    for i in range(n - 1, -1, -1):  # @line L5
        if kind[i] == "end":
            continue
        k = new_index[i]
        if not new_front or new_front[-1] != k:
            new_front.append(k)
    if len(new_front) > 1 and new_front[0] == new_front[-1]:
        new_front.pop()
    new_front.reverse()
    E = [exact(p) for p in points]
    if not is_valid_planar_mesh(E, quads):  # @line L6
        return None, None, None, "a quad of the row is not strictly convex"
    inner = [E[k] for k in new_front]
    if not is_simple_polygon(inner) or twice_area(inner) <= 0:  # @line L7
        return None, None, None, "the new front is not simple"
    return points, quads, new_front, None  # @line L8


def quad_count_parity(quads: Sequence[Sequence[int]]) -> Tuple[int, int, int]:
    """(4 Q, interior edges, boundary edges) of a quad mesh, by counting edge sides."""
    sides = {}
    for q in quads:
        for s in range(4):
            e = frozenset((q[s], q[(s + 1) % 4]))
            sides[e] = sides.get(e, 0) + 1
    return 4 * len(quads), sum(1 for v in sides.values() if v == 2), sum(1 for v in sides.values() if v == 1)
test_paving.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/paving/. The authors are listed in prov/AS3MCY.jsonl.

import math
import random
from fractions import Fraction as F

from mg3geom import boundary_edges, exact, is_valid_planar_mesh, orient2d, twice_area
from paving import classify, is_simple_polygon, pave_row, quad_count_parity


def rect_front(W, H):
    """The counterclockwise boundary of [0, W] x [0, H] with unit spacing."""
    return ([(float(i), 0.0) for i in range(W)] + [(float(W), float(j)) for j in range(H)]
            + [(float(W - i), float(H)) for i in range(W)] + [(0.0, float(H - j)) for j in range(H)])


def round_front(rng, n, radius):
    angles = [2 * math.pi * (i + rng.uniform(-0.2, 0.2)) / n for i in range(n)]
    return [(radius * math.cos(t) * rng.uniform(0.97, 1.03), radius * math.sin(t) * rng.uniform(0.97, 1.03))
            for t in angles]


def inside_quad(q, x):
    return all(orient2d(q[s], q[(s + 1) % 4], x) > 0 for s in range(4))


def check_row(front, points, quads, new_front):
    E = [exact(p) for p in points]
    n = len(front)
    assert is_valid_planar_mesh(E, quads)                        # strictly convex, no inverted quad
    inner = [E[k] for k in new_front]
    assert is_simple_polygon(inner)                               # the new front is simple
    # area identity, exact: the row fills the region between the two fronts
    assert sum(orient2d(E[q[0]], E[q[1]], E[q[2]]) + orient2d(E[q[0]], E[q[2]], E[q[3]]) for q in quads) \
        == twice_area(E[:n]) - twice_area(inner)
    assert twice_area(inner) > 0
    # the boundary of the row is the old front plus the new front reversed
    m = len(new_front)
    expected = {(i, (i + 1) % n) for i in range(n)} | {(new_front[(j + 1) % m], new_front[j]) for j in range(m)}
    assert set(boundary_edges(quads)) == expected
    # parity: 4 Q = 2 E_int + E_bnd, so the fronts keep the parity of their length
    four_q, interior, bnd = quad_count_parity(quads)
    assert four_q == 2 * interior + bnd and bnd == n + m and (n - m) % 2 == 0


def test_square_row_is_the_outer_ring_of_the_grid():
    front = rect_front(4, 4)
    assert classify(front).count("end") == 4
    points, quads, new_front, why = pave_row(front)
    assert why is None and len(quads) == 12
    check_row(front, points, quads, new_front)
    got = {frozenset(points[i] for i in q) for q in quads}
    ring = {frozenset({(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)})
            for x in range(4) for y in range(4) if x in (0, 3) or y in (0, 3)}
    assert got == {frozenset((float(a), float(b)) for a, b in s) for s in ring}
    assert sorted(points[k] for k in new_front) == sorted(
        (float(x), float(y)) for x in (1, 2, 3) for y in (1, 2, 3) if (x, y) != (2, 2))


def test_rows_on_rectangles_and_round_fronts():
    for W, H in ((6, 3), (5, 4), (7, 7)):
        front = rect_front(W, H)
        points, quads, new_front, why = pave_row(front)
        assert why is None and len(quads) == 2 * (W + H) - 4
        check_row(front, points, quads, new_front)
    rng = random.Random(4)
    done = 0
    for _ in range(30):
        front = round_front(rng, rng.randint(12, 24), rng.uniform(3, 6))
        points, quads, new_front, why = pave_row(front)
        if why is None:
            check_row(front, points, quads, new_front)
            done += 1
    assert done >= 20


def test_no_point_is_in_two_quads():
    rng = random.Random(5)
    front = round_front(rng, 16, 4.0)
    points, quads, new_front, why = pave_row(front)
    assert why is None
    E = [exact(p) for p in points]
    for _ in range(4000):
        x = (F(rng.randint(-5000, 5000), 1000), F(rng.randint(-5000, 5000), 1000))
        assert sum(inside_quad([E[i] for i in q], x) for q in quads) <= 1


def test_failure_is_reported():
    # the inner 2 x 2 square: its row ends are neighbours of neighbours
    points, quads, new_front, why = pave_row(rect_front(2, 2))
    assert points is None and "too close" in why
    # a front with a reflex node
    L_shape = [(0.0, 0.0), (2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0), (2.0, 4.0), (0.0, 4.0), (0.0, 2.0)]
    points, quads, new_front, why = pave_row(L_shape)
    assert points is None and "reflex" in why
    # a strip of width 1 with nodes 2 apart on the long sides: the rows from both
    # sides are 2 high, they cross, and the new front is not simple
    strip = [(0.0, 0.0), (2.0, 0.0), (4.0, 0.0), (6.0, 0.0), (8.0, 0.0), (8.0, 1 / 3), (8.0, 2 / 3), (8.0, 1.0),
             (6.0, 1.0), (4.0, 1.0), (2.0, 1.0), (0.0, 1.0), (0.0, 2 / 3), (0.0, 1 / 3)]
    points, quads, new_front, why = pave_row(strip)
    assert points is None and "not simple" in why
    # the same strip, 4.5 wide, takes a row
    wide = [(x, y * 4.5) for x, y in strip]
    points, quads, new_front, why = pave_row(wide)
    assert why is None
    check_row(wide, points, quads, new_front)

History

Ted Blacker and Michael Stephenson published paving in the International Journal for Numerical Methods in Engineering in 1991, from work at Sandia National Laboratories, where it went into the CUBIT mesh generation toolkit. Before paving, all-quad meshes of general regions were mostly made by splitting the region into four-sided blocks by hand and meshing each block with a structured grid, or by splitting triangles into quads. Paving was among the first methods to produce well shaped all-quad meshes of arbitrary planar regions automatically. Plastering, its 3D extension to hexahedra, followed in the early 1990s, and Q-Morph moved the advancing front of quads onto a triangle mesh in 1999.

References

  1. Ted D. Blacker and Michael B. Stephenson, Paving, a new approach to automated quadrilateral mesh generation, International Journal for Numerical Methods in Engineering 32(4), 1991, 811 to 847, the row by row advance of the front, the classification of front nodes, seaming, row adjustment, intersection of fronts, closure, and smoothing (general locator)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.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
  • at least three sources
  • a scene preset for the example