Algorithm Search⌘K

Algorithmcore

Isotropic remeshing

Also called incremental remeshing, Botsch-Kobbelt remeshing.

Makes a mesh with nearly equal edges and good angles by repeating edge splits, collapses, flips toward valence six and tangential smoothing.

Time
O(k n² log n) worst
Space
Θ(n) extra
Where
k = the number of rounds; n = the largest number of vertices during the run
Properties
deterministicnot exactiterative
Origin
Mario Botsch, Leif Kobbelt, 2004

Isotropic remeshing turns a triangle mesh with triangles of all sizes and shapes into one whose edges are all close to a target length LL and whose triangles are close to equilateral, while the surface stays the same up to a small error. It repeats a short loop of four local steps. It splits every edge longer than 43L\frac{4}{3}L and collapses every edge shorter than 45L\frac{4}{5}L. It flips edges so that the valences move toward 6. Then it moves each vertex toward the centroid of its neighbours, inside its tangent plane, and projects it back onto the input surface. Each step only changes a few triangles at a time, so the method is simple to write on a half-edge structure, and a few rounds are enough.

In plain words

A scanned or converted mesh often has long thin triangles next to tiny ones. Many later steps, such as smoothing, simulation or computing distances, work badly on such triangles. Remeshing replaces them by triangles of one size and a nice shape, on the same surface.

The method keeps a goal length in mind and repeats four simple fixes. If an edge is too long, cut it in the middle. If an edge is too short, shrink it to a point, which merges its two ends. If a corner has too many or too few edges around it, turn an edge in a four-sided patch the other way, so that the corners move toward six edges each. Finally, nudge every corner toward the middle of its neighbours, but only along the surface, and put it back on the surface. After a few rounds, all edges are about the goal length.

The problem

The input is a manifold triangle mesh, a target edge length L>0L > 0, a number of rounds kk, and optionally a projection onto a reference surface, usually the input mesh itself. The output is a manifold triangle mesh with the same topology, the same border curve, edge lengths mostly in [45L,43L][\frac{4}{5}L, \frac{4}{3}L], angles near 60°60° and valences near 6 (4 on the border). This is a quality goal, not an optimization with a unique answer. The page proves what each step keeps and measures the final quality.

The algorithm

The valence excess of a set of vertices is ∑v∣val⁡(v)−t(v)∣\sum_v |\operatorname{val}(v) - t(v)| with t(v)=6t(v) = 6 for an inner vertex and 44 for a border vertex.

  1. ISOTROPIC-REMESH(mesh, L, k, project)
  2. 1for r ← 1 to k do
  3. 2while the longest edge uv has |uv| > 4L/3 do split uv at its midpoint
  4. 3for each edge uv with |uv| < 4L/5 do collapse uv to its midpoint if it is safe
  5. 4while some inner edge uv has a legal flip that lowers the valence excess of its four vertices do flip uv
  6. 5for each inner vertex v do x_v ← project(x_v + (I − n_v n_vᵀ)(c_v − x_v))
  7. 6return the mesh

Split (line L2). The edge uvuv with faces (u,v,c)(u, v, c) and (v,u,d)(v, u, d) gets a new vertex mm at its midpoint, and the faces become (u,m,c)(u, m, c), (m,v,c)(m, v, c), (v,m,d)(v, m, d), (m,u,d)(m, u, d). A border edge has one face and gets two. The code always splits the longest edge, from a priority queue.

Collapse (line L3). Vertex vv is merged into uu at the midpoint, and the two faces of uvuv vanish. The code allows it only if the collapse is safe. Neither uu nor vv may be a border vertex. The link condition must hold: the common neighbours of uu and vv are exactly cc and dd. Both cc and dd must have valence at least 4. No edge at the new vertex may be longer than 43L\frac{4}{3}L. No remaining face may turn its normal by 90°90° or more.

Flip (line L4). The faces (u,v,c)(u, v, c) and (v,u,d)(v, u, d) become (u,d,c)(u, d, c) and (d,v,c)(d, v, c), as in an edge flip. A flip is legal if uvuv is not a border edge, cdcd is not already an edge, uu and vv have valence at least 4, and neither new face folds over the old pair. It is made only if it lowers the valence excess of u,v,c,du, v, c, d, where u,vu, v lose one edge and c,dc, d gain one.

Relaxation (line L5). cvc_v is the centroid of the neighbours of vv and nvn_v the unit normal, the normalized sum of the face normals. The move is the tangential part of the Laplacian smoothing step with factor 1, so the vertices spread evenly without shrinking the shape, and the projection puts them back on the surface.

Example

The split phase on a square. Take the unit square as two triangles, cut by the diagonal from (0,0)(0, 0) to (1,1)(1, 1), with L=12L = \frac{1}{2}, so the split threshold is 23\frac{2}{3}. The longest edge is the diagonal, 2\sqrt{2}. Splitting it at (12,12)(\frac{1}{2}, \frac{1}{2}) gives four triangles, with four sides of length 1 and four half-diagonals of length 22≈0.707\frac{\sqrt{2}}{2} \approx 0.707. The sides are now the longest. Each is split at its midpoint, which adds a spoke of length 12\frac{1}{2} to the center. Then the half-diagonals, 0.707>230.707 > \frac{2}{3}, are the longest, and each is split, for example at (14,14)(\frac{1}{4}, \frac{1}{4}), with new edges of length 24≈0.354\frac{\sqrt{2}}{4} \approx 0.354. After these 9 splits the mesh has 13 vertices and 16 faces, and every edge has length 12\frac{1}{2} or 24\frac{\sqrt{2}}{4}. The tests check these counts.

A noisy sphere. Take the icosphere with 162 vertices, move each vertex by up to 0.0250.025 in each coordinate and put it back on the unit sphere. Then remesh with L=0.15L = 0.15, half the input edge length, for 5 rounds, with projection onto the sphere. The measured result has 619 vertices, a mean edge length of 1.021L1.021L, 99.599.5 percent of the edges in [45L,43L][\frac{4}{5}L, \frac{4}{3}L], 563 of the 619 vertices of valence 6, and a smallest angle of 41°41°, against 44°44° in the noisy input at twice the edge length. The Euler characteristic stays 2.

A rectangle of thin triangles. An 8×48 \times 4 rectangle cut into 32 triangles of size 4×124 \times \frac{1}{2} has a smallest angle of 7.1°7.1°. Five rounds with L=12L = \frac{1}{2} give 164 vertices, 102 of the 116 inner vertices of valence 6, and a measured smallest angle of 27.4°27.4°. The area stays exactly 3232, the corners stay, and every border edge lies on a side of the rectangle.

Correctness

These are proved in the correctness file:

  • The split loop stops, and then every edge is at most 43L\frac{4}{3}L. The loop splits the longest edge, which is the longest edge of both its faces, so every split is a longest-side bisection. By the theorem of Rosenberg and Stenger, every triangle made in this way has all its angles at least half the smallest angle of the input. So a triangle with an edge longer than 43L\frac{4}{3}L has area at least a fixed amount, and a counting argument bounds the number of splits.
  • Splits keep the surface. A midpoint lies on the old edge, so the new faces cover exactly the old ones, with the same area.
  • The collapse loop stops and keeps the bound. Each collapse removes a vertex. The guard keeps every edge at most 43L\frac{4}{3}L.
  • The flip loop stops at a local optimum. Each flip lowers the integer valence excess of the whole mesh by at least 1. When it stops, no legal flip lowers the excess, which the tests check by a scan of all edges.
  • The mesh stays a manifold with the same topology. Splits and flips keep a manifold with the same Euler characteristic. A collapse under the link condition, away from the border, also keeps the manifold and the Euler characteristic. The tests recompute the topology from scratch after random operations.
  • The border stays. No border vertex moves, no border edge is collapsed or flipped, and a split of a border edge puts the new vertex on that edge.

The upper bound 43L\frac{4}{3}L holds after line L3, but flips and relaxation can create longer edges. Edges shorter than 45L\frac{4}{5}L can remain where a collapse is not safe. So the final length distribution, the angles and the valences are only measured, as in the examples.

Proof: Each phase of isotropic remeshing stops, the split phase leaves every edge at most 4L/3, the collapse guard keeps this bound, the flip phase ends at a local optimum of the valence excess, and the mesh keeps its topology and borderfull

Setup. The input is an oriented manifold triangle mesh, possibly with border, in which every face has positive area. L>0L > 0 is the target length, high=43L\mathrm{high} = \frac{4}{3}L and low=45L\mathrm{low} = \frac{4}{5}L. A vertex is a border vertex if it lies on a border edge, an edge with only one face. The valence val⁡(v)\operatorname{val}(v) is the number of neighbours of vv, and the valence excess is E=∑v∣val⁡(v)−t(v)∣E = \sum_v |\operatorname{val}(v) - t(v)| with t(v)=4t(v) = 4 on the border and 66 inside. The claims are about the combinatorics of the operators and the exact geometry of the midpoints. The floating-point length tests only decide which operator runs, and do not change the arguments.

Lemma 1 (a split keeps the surface and the topology). Splitting the edge uvuv at its midpoint mm gives a manifold mesh with the same oriented surface, the same border curve and the same Euler characteristic.

Proof. Each face (a,b,w)(a, b, w) that contains the directed edge a→ba \to b, with {a,b}={u,v}\{a, b\} = \{u, v\}, is replaced by (a,m,w)(a, m, w) and (m,b,w)(m, b, w). Since mm lies on the segment abab, these two triangles lie in the plane of the old one, keep its orientation, and cover it with no overlap, so the surface and the area do not change. Every other face is untouched. The star of mm is a disk (two faces from each old face, joined along mwmw), or a half-disk if uvuv was a border edge, and the stars of uu, vv and the opposite vertices only replace one edge by another. For an inner edge, VV grows by 1, EE by 3 (the halves umum, mvmv and two spokes) and FF by 2. For a border edge, VV grows by 1, EE by 2 and FF by 1. In both cases V−E+FV - E + F is the same. The border curve is the same point set, because a border edge uvuv becomes the border edges umum and mvmv. □\square

Lemma 2 (longest-first splits are longest-side bisections). In line L2, every split cuts each of its one or two faces through a longest side of that face.

Proof. The heap holds every edge longer than high\mathrm{high}, with stale entries skipped, and a split pushes every new edge longer than high\mathrm{high}. So the popped edge is a longest edge of the whole mesh, and so a longest side of each face that contains it. □\square

Theorem 1 (the split phase stops and bounds the edges). Line L2 makes finitely many splits, and when it stops every edge has length at most 43L\frac{4}{3}L.

Proof. Let α>0\alpha > 0 be the smallest angle of the mesh when line L2 starts, and β=α/2\beta = \alpha/2. Every face made in line L2 comes from a face TT of the starting mesh by repeated bisection through a longest side (Lemma 2). By the theorem of Rosenberg and Stenger, every triangle made in this way from TT has all its angles at least half the smallest angle of TT, so at least β\beta. Their argument allows either side when two sides are equally long.

Take a face that is split. Its longest side has length ℓ>43L\ell > \frac{4}{3}L. Let A,BA, B be the angles at the ends of that side and hh the height of the opposite vertex above it. Both AA and BB are at most the third angle, so they are acute, and the foot of the height splits the side into parts xx and ℓ−x\ell - x with h=xtan⁡A=(ℓ−x)tan⁡Bh = x\tan A = (\ell - x)\tan B. So h=ℓ tan⁡Atan⁡Btan⁡A+tan⁡Bh = \ell\,\frac{\tan A \tan B}{\tan A + \tan B}. The function aba+b\frac{ab}{a + b} grows in each of a,b>0a, b > 0, and tan⁡A,tan⁡B≥tan⁡β\tan A, \tan B \ge \tan\beta, so h≥ℓ2tan⁡βh \ge \frac{\ell}{2}\tan\beta and the area is at least a0=14ℓ2tan⁡β>49L2tan⁡βa_0 = \frac{1}{4}\ell^2\tan\beta > \frac{4}{9}L^2\tan\beta.

A bisection halves the area. So a face made by jj bisections from TT has area area⁡(T)/2j\operatorname{area}(T)/2^j, and it can be split only if area⁡(T)/2j≥a0\operatorname{area}(T)/2^j \ge a_0, that is, j≤log⁡2(area⁡(T)/a0)j \le \log_2(\operatorname{area}(T)/a_0). Each split bisects one or two faces, and each face is bisected at most once, because the face disappears. So the number of splits is at most the number of faces ever made at a depth jj that can be split, which is finite. When the heap is empty, no edge is longer than high\mathrm{high}. □\square

Lemma 3 (a safe collapse keeps the manifold and the topology). If uvuv is an inner edge with faces (u,v,c)(u, v, c) and (v,u,d)(v, u, d), neither uu nor vv is a border vertex, and the link condition N(u)∩N(v)={c,d}N(u) \cap N(v) = \{c, d\} holds, then merging vv into uu gives an oriented manifold mesh with the same Euler characteristic and the same border.

Proof. The two faces of uvuv vanish, and every other face of vv gets uu in place of vv. Since uu and vv are inner vertices, their stars are disks, with link cycles c,v,d,…c, v, d, \ldots around uu and d,u,c,…d, u, c, \ldots around vv. The new link of uu is the first cycle with vv removed, joined at cc and dd to the second cycle with uu removed. The link condition says that these two paths share only cc and dd, so the join is a single simple cycle, and the new star of uu is a disk. A vertex w∉{u,v,c,d}w \notin \{u, v, c, d\} in the link of vv is not a neighbour of uu, so its link changes only by the name v→uv \to u and stays a cycle. The vertices cc and dd each lose one neighbour (vv merges into uu) and keep a link cycle of length val⁡−1≥3\operatorname{val} - 1 \ge 3, because the guard asks val⁡(c),val⁡(d)≥4\operatorname{val}(c), \operatorname{val}(d) \ge 4. No directed edge is used twice: a repeated directed edge would need a common neighbour of uu and vv other than cc and dd. The faces keep their vertex order, so the orientation stays. The counts change by V−1V - 1, E−3E - 3 (the edge uvuv, and vcvc, vdvd merge into ucuc, udud) and F−2F - 2, so V−E+FV - E + F is the same. No border vertex is involved, so the border does not change. This is the inner case of the result of Dey, Edelsbrunner, Guha and Nekhayev on topology-preserving edge contraction. □\square

Theorem 2 (the collapse phase stops and keeps the bound). Line L3 makes fewer than VV collapses, where VV is the vertex count at its start. If every edge is at most high\mathrm{high} at the start, this still holds at the end.

Proof. Each collapse removes one vertex and adds none, and a mesh with faces keeps at least 3 vertices, so there are fewer than VV collapses. Each sweep over the edges either collapses one or ends the loop. The new edges of a collapse are the edges from the midpoint pp to the old neighbours of uu and vv, and the guard refuses the collapse if one of them is longer than high\mathrm{high}. All other edges keep their length. □\square

Lemma 4 (a flip keeps the topology and changes four valences). Flipping a legal inner edge uvuv with faces (u,v,c)(u, v, c) and (v,u,d)(v, u, d) into (u,d,c)(u, d, c) and (d,v,c)(d, v, c) gives an oriented manifold mesh with the same VV, EE and FF, the same border, and new valences val⁡(u)−1\operatorname{val}(u) - 1, val⁡(v)−1\operatorname{val}(v) - 1, val⁡(c)+1\operatorname{val}(c) + 1, val⁡(d)+1\operatorname{val}(d) + 1, all others unchanged.

Proof. The legality test asks c≠dc \ne d and that cdcd is not an edge, so the new edge cdcd is new and no directed edge is used twice. The four outer edges ucuc, cvcv, vdvd, dudu keep one face each on the same side. The edge uvuv leaves and cdcd comes in, so the counts stay. uu and vv keep valence at least 3, because the test asks at least 4 before the flip. Border status depends only on border edges, which flips do not touch, so the targets tt do not change. □\square

Theorem 3 (the flip phase stops at a local optimum). Line L4 makes at most E0E_0 flips, where E0E_0 is the valence excess at its start. When it stops, no legal flip lowers the excess.

Proof. A flip is made only if it lowers ∑w∈{u,v,c,d}∣val⁡(w)−t(w)∣\sum_{w \in \{u, v, c, d\}} |\operatorname{val}(w) - t(w)|. By Lemma 4 no other term of EE changes, so EE drops by this positive integer, at least 1. Since E≥0E \ge 0, there are at most E0E_0 flips. The loop ends after a sweep with no flip, and in that sweep every edge was tested, so no legal flip lowers EE. □\square

Theorem 4 (topology and border are kept). The output is an oriented manifold mesh with the Euler characteristic and the border curve of the input, and every vertex of the input border that was there at the start is still in place.

Proof. Lines L2, L3 and L4 keep both by Lemmas 1, 3 and 4. Line L5 moves only inner vertices, and does not change the faces. Border vertices are never moved, never collapsed, and border edges are only split at their midpoints, so the border curve is the same point set in every round. □\square

Termination. Each round stops by Theorems 1, 2 and 3, and line L5 is one pass over the vertices, so the kk rounds stop.

What is not proved here. The upper bound of Theorem 1 holds after line L3, but flips and the relaxation of line L5 can make edges longer than 43L\frac{4}{3}L again, and edges shorter than 45L\frac{4}{5}L remain where no collapse is safe. Line L5 can also, in principle, move a vertex so far that a face turns over. That the final edge lengths, angles and valences are close to the targets, and that the faces stay oriented, is measured in the tests and the examples, not proved. Theorem 1 uses exact midpoints, and the Rosenberg and Stenger bound gives no useful count of the splits beyond finiteness.

Complexity

With a half-edge structure, or the edge and face maps of the code, each local operator costs O(d)O(d) time for the valences dd involved, which is O(1)O(1) on a mesh of bounded valence. Assume bounded valence. In one round, line L2 makes at most nn splits, each with a priority queue operation of O(log⁡n)O(\log n), and line L5 takes O(n)O(n) time plus the cost of the projection. Lines L3 and L4 sweep the sorted edge list, O(nlog⁡n)O(n \log n) per sweep, until a sweep changes nothing. Every sweep but the last makes a collapse or a flip, and the proofs bound these by nn collapses and by the valence excess, which is O(n)O(n), flips. This gives the worst case O(kn2log⁡n)O(k n^2 \log n). In the measured runs the loops end after a few sweeps, so a round costs about O(nlog⁡n)O(n \log n) in practice. Projection onto the input mesh needs a spatial search structure, about O(log⁡n)O(\log n) per query. In practice k=5k = 5 to 1010 rounds are used. The extra space is Θ(n)\Theta(n).

Properties

  • Local and simple. Four operators and two thresholds.
  • The thresholds fit together. 43L\frac{4}{3}L and 45L\frac{4}{5}L are chosen so that splitting an edge just above 43L\frac{4}{3}L gives halves above 23L\frac{2}{3}L, and collapsing the shortest edges does not make edges longer than the split threshold, so the steps do not undo each other.
  • Uniform, not adaptive. All edges aim at one length. Fine details smaller than LL are lost, and flat regions get as many triangles as curved ones.
  • Topology is kept. The Euler characteristic, the number of border loops and the orientation stay.
  • Not exact. The midpoints, normals and projections use floating point.

Variants and improvements

  • Adaptive remeshing. Make LL depend on the position, smaller where the curvature is high, so that the error stays the same with fewer triangles.
  • Feature edges. Mark sharp edges and corners, and never collapse or flip across them. Relax feature vertices only along the feature curve.
  • Area-weighted relaxation. Use the centroid of the neighbours weighted by the areas of their faces, which spreads the vertices according to the area.
  • Delaunay flips. Flip toward the intrinsic Delaunay condition, the angles opposite each edge summing to at most π\pi, as in the Lawson flip algorithm, instead of toward valence 6.
  • Quadric collapses. For coarsening only, collapse by the quadric error metric of mesh simplification, which keeps the shape better than midpoint collapses.
  • Global methods. Centroidal Voronoi tessellations and parameterization-based remeshers optimize the vertex positions as a whole, at a higher cost.

When to use it

Use it to clean a mesh before simulation, smoothing, parameterization or geodesic computations, all of which need well-shaped triangles, and to bring a scanned or converted mesh to a known resolution. Several mesh libraries include it. For planar domains with guaranteed angle bounds, use Delaunay refinement, such as Ruppert's algorithm. To reduce the triangle count while keeping the shape, use mesh simplification. To measure how far the result is from the input, use Metro.

Pitfalls

  • No projection. Without line L5's projection, the tangential moves still drift off a curved surface, and the shape slowly changes.
  • Unsafe collapses. A collapse without the link condition can glue two sheets together, or make a vertex whose star is not a disk.
  • Collapsing into long edges. Without the 43L\frac{4}{3}L guard, a collapse can make edges that the next round splits again, and the loop does not settle.
  • Moving the border. Relaxing border vertices like inner ones pulls the border inward.
  • Features. Sharp edges are rounded unless they are marked and kept.
  • A target too large. If LL is larger than the size of a thin part, collapses close it up or the link condition blocks them, and the mesh stays poor there.

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.

isotropic_remeshing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isotropic-remeshing/. The authors are listed in prov/0E9HMJ.jsonl.

"""Isotropic remeshing in the style of Botsch and Kobbelt (SGP 2004).

Each round, for a target edge length L:
1. split the longest edge while it is longer than 4/3 L,
2. collapse edges shorter than 4/5 L into their midpoint, when the collapse is
   safe (link condition, no border vertex, no new edge longer than 4/3 L, no
   flipped face),
3. flip edges while a flip lowers the valence excess (target 6 inside,
   4 on the border),
4. move each inner vertex toward the centroid of its neighbours, inside its
   tangent plane, and
5. optionally project the vertices onto a reference surface.

Border vertices never move and border edges are never collapsed or flipped, so
the border keeps its shape (border edges may still be split at their midpoints).
The mesh is a small half-edge-like structure: directed edge -> face, and
vertex -> faces.
"""

import heapq
from math import sqrt
from typing import Callable, Optional, Sequence

Vec = tuple


def sub(a, b):
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def dot(a, b):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def length(a):
    return sqrt(dot(a, a))


def mid(a, b):
    return ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2)


class Mesh:
    def __init__(self, points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]]):
        self.P: list[Vec] = [tuple(p) for p in points]
        self.F: dict[int, tuple[int, int, int]] = {}
        self.he: dict[tuple[int, int], int] = {}
        self.vf: list[set[int]] = [set() for _ in self.P]
        self.next_id = 0
        for f in faces:
            self.add_face(*f)

    # ---- basic operations ----

    def add_face(self, a, b, c) -> int:
        fid = self.next_id
        self.next_id += 1
        self.F[fid] = (a, b, c)
        for u, v in ((a, b), (b, c), (c, a)):
            if (u, v) in self.he:
                raise ValueError("non-manifold or badly oriented: directed edge used twice")
            self.he[(u, v)] = fid
        for v in (a, b, c):
            self.vf[v].add(fid)
        return fid

    def remove_face(self, fid):
        a, b, c = self.F.pop(fid)
        for u, v in ((a, b), (b, c), (c, a)):
            del self.he[(u, v)]
        for v in (a, b, c):
            self.vf[v].discard(fid)

    def opposite(self, u, v):
        """The third vertex of the face with the directed edge u -> v, or None."""
        fid = self.he.get((u, v))
        if fid is None:
            return None
        f = self.F[fid]
        return next(w for w in f if w != u and w != v)

    def neighbours(self, v) -> set[int]:
        return {w for fid in self.vf[v] for w in self.F[fid] if w != v}

    def is_border_edge(self, u, v) -> bool:
        return ((u, v) in self.he) != ((v, u) in self.he)

    def is_border_vertex(self, v) -> bool:
        return any(self.is_border_edge(v, w) for w in self.neighbours(v))

    def edges(self) -> list[tuple[int, int]]:
        return sorted({(min(u, v), max(u, v)) for u, v in self.he})

    def elen(self, u, v) -> float:
        return length(sub(self.P[u], self.P[v]))

    def face_normal(self, f, P=None):
        P = P or self.P
        a, b, c = f
        return cross(sub(P[b], P[a]), sub(P[c], P[a]))

    def valence_target(self, v) -> int:
        return 4 if self.is_border_vertex(v) else 6

    # ---- the three local operators ----

    def split(self, u, v) -> int:
        """Split the edge u-v at its midpoint m; each face (u, v, w) becomes (u, m, w) and (m, v, w)."""
        m = len(self.P)
        self.P.append(mid(self.P[u], self.P[v]))
        self.vf.append(set())
        for a, b in ((u, v), (v, u)):
            fid = self.he.get((a, b))
            if fid is not None:
                w = self.opposite(a, b)
                self.remove_face(fid)
                self.add_face(a, m, w)
                self.add_face(m, b, w)
        return m

    def can_collapse(self, u, v, high) -> bool:
        if self.is_border_edge(u, v) or self.is_border_vertex(u) or self.is_border_vertex(v):
            return False
        c, d = self.opposite(u, v), self.opposite(v, u)
        if self.neighbours(u) & self.neighbours(v) != {c, d}:             # the link condition
            return False
        if len(self.neighbours(c)) <= 3 or len(self.neighbours(d)) <= 3:
            return False
        p = mid(self.P[u], self.P[v])
        if any(length(sub(p, self.P[w])) > high for w in (self.neighbours(u) | self.neighbours(v)) - {u, v}):
            return False
        P = list(self.P)
        P[u] = P[v] = p
        for fid in self.vf[u] | self.vf[v]:
            f = self.F[fid]
            if u in f and v in f:
                continue
            if dot(self.face_normal(f), self.face_normal(f, P)) <= 0:      # the face would flip or degenerate
                return False
        return True

    def collapse(self, u, v):
        """Merge v into u at the midpoint. The two faces of the edge disappear."""
        p = mid(self.P[u], self.P[v])
        old = [self.F[fid] for fid in self.vf[v]]
        for fid in list(self.vf[v]):
            self.remove_face(fid)
        for f in old:
            if u not in f:
                self.add_face(*(u if w == v else w for w in f))
        self.P[u] = p

    def flip_gain(self, u, v) -> int:
        """How much a flip of u-v lowers the valence excess at its four vertices (0 if not allowed)."""
        if self.is_border_edge(u, v):
            return 0
        c, d = self.opposite(u, v), self.opposite(v, u)
        if c == d or d in self.neighbours(c):
            return 0
        val = {w: len(self.neighbours(w)) for w in (u, v, c, d)}
        if val[u] <= 3 or val[v] <= 3:
            return 0
        tgt = {w: self.valence_target(w) for w in (u, v, c, d)}
        before = sum(abs(val[w] - tgt[w]) for w in (u, v, c, d))
        after = (abs(val[u] - 1 - tgt[u]) + abs(val[v] - 1 - tgt[v]) +
                 abs(val[c] + 1 - tgt[c]) + abs(val[d] + 1 - tgt[d]))
        if after >= before:
            return 0
        n_old = tuple(x + y for x, y in zip(self.face_normal((u, v, c)), self.face_normal((v, u, d))))
        for f in ((u, d, c), (d, v, c)):
            if dot(self.face_normal(f), n_old) <= 0:                         # the new face would fold over
                return 0
        return before - after

    def flip(self, u, v):
        """Faces (u, v, c) and (v, u, d) become (u, d, c) and (d, v, c)."""
        c, d = self.opposite(u, v), self.opposite(v, u)
        self.remove_face(self.he[(u, v)])
        self.remove_face(self.he[(v, u)])
        self.add_face(u, d, c)
        self.add_face(d, v, c)

    # ---- output ----

    def compact(self) -> tuple[list[Vec], list[tuple[int, int, int]]]:
        used = sorted({w for f in self.F.values() for w in f})
        new = {v: i for i, v in enumerate(used)}
        return [self.P[v] for v in used], [tuple(new[w] for w in self.F[fid]) for fid in sorted(self.F)]


def split_long_edges(mesh: Mesh, high: float) -> int:
    """Split the longest edge while it is longer than high. Returns the number of splits."""
    heap = [(-mesh.elen(u, v), u, v) for u, v in mesh.edges() if mesh.elen(u, v) > high]
    heapq.heapify(heap)
    count = 0
    while heap:
        neg, u, v = heapq.heappop(heap)
        if ((u, v) not in mesh.he and (v, u) not in mesh.he) or mesh.elen(u, v) != -neg:
            continue
        m = mesh.split(u, v)
        count += 1
        for w in mesh.neighbours(m):
            if mesh.elen(m, w) > high:
                heapq.heappush(heap, (-mesh.elen(m, w), min(m, w), max(m, w)))
    return count


def collapse_short_edges(mesh: Mesh, low: float, high: float) -> int:
    count = 0
    changed = True
    while changed:
        changed = False
        for u, v in mesh.edges():
            if (u, v) not in mesh.he and (v, u) not in mesh.he:
                continue
            if mesh.elen(u, v) < low and mesh.can_collapse(u, v, high):
                mesh.collapse(u, v)
                count += 1
                changed = True
    return count


def equalize_valences(mesh: Mesh) -> int:
    count = 0
    changed = True
    while changed:
        changed = False
        for u, v in mesh.edges():
            if (u, v) not in mesh.he:
                u, v = v, u
            if (u, v) in mesh.he and mesh.flip_gain(u, v) > 0:
                mesh.flip(u, v)
                count += 1
                changed = True
    return count


def tangential_relaxation(mesh: Mesh, project: Optional[Callable] = None):
    live = sorted({w for f in mesh.F.values() for w in f})
    new = {}
    for v in live:
        if mesh.is_border_vertex(v):
            continue
        nb = mesh.neighbours(v)
        q = tuple(sum(mesh.P[w][k] for w in nb) / len(nb) for k in range(3))
        n = (0.0, 0.0, 0.0)
        for fid in mesh.vf[v]:
            n = tuple(x + y for x, y in zip(n, mesh.face_normal(mesh.F[fid])))
        ln = length(n)
        d = sub(q, mesh.P[v])
        if ln > 0:
            n = tuple(x / ln for x in n)
            d = tuple(d[k] - dot(d, n) * n[k] for k in range(3))
        p = tuple(mesh.P[v][k] + d[k] for k in range(3))
        new[v] = project(p) if project else p
    for v, p in new.items():
        mesh.P[v] = p


def isotropic_remeshing(points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]], target: float,
                        iterations: int = 5, project: Optional[Callable] = None):
    """Remesh toward edges of length `target`. Returns (points, faces) of the new mesh."""
    mesh = Mesh(points, faces)
    low, high = 4 * target / 5, 4 * target / 3
    for _ in range(iterations):                                     # @line L1
        split_long_edges(mesh, high)                                # @line L2
        collapse_short_edges(mesh, low, high)                       # @line L3
        equalize_valences(mesh)                                     # @line L4
        tangential_relaxation(mesh, project)                        # @line L5
    return mesh.compact()                                           # @line L6
test_isotropic_remeshing.py 219 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isotropic-remeshing/. The authors are listed in prov/0E9HMJ.jsonl.

import random
from math import acos, degrees, sqrt

from isotropic_remeshing import (Mesh, collapse_short_edges, cross, dot, equalize_valences, isotropic_remeshing,
                                 length, split_long_edges, sub)


def sphere(p):
    n = sqrt(dot(p, p))
    return tuple(c / n for c in p)


def icosphere(level):
    t = (1 + sqrt(5)) / 2
    raw = [(-1, t, 0), (1, t, 0), (-1, -t, 0), (1, -t, 0), (0, -1, t), (0, 1, t),
           (0, -1, -t), (0, 1, -t), (t, 0, -1), (t, 0, 1), (-t, 0, -1), (-t, 0, 1)]
    pts = [sphere(p) for p in raw]
    faces = [(0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4),
             (11, 10, 2), (10, 7, 6), (7, 1, 8), (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8),
             (3, 8, 9), (4, 9, 5), (2, 4, 11), (6, 2, 10), (8, 6, 7), (9, 8, 1)]
    for _ in range(level):
        memo = {}

        def m(i, j):
            k = (min(i, j), max(i, j))
            if k not in memo:
                pts.append(sphere(tuple((a + b) / 2 for a, b in zip(pts[i], pts[j]))))
                memo[k] = len(pts) - 1
            return memo[k]

        faces = [g for a, b, c in faces for g in
                 ((a, m(a, b), m(c, a)), (b, m(b, c), m(a, b)), (c, m(c, a), m(b, c)), (m(a, b), m(b, c), m(c, a)))]
    return pts, faces


def rectangle():
    """An 8 x 4 rectangle cut into 32 long thin triangles (cells 4 x 0.5)."""
    pts = [(4.0 * i, 0.5 * j, 0.0) for j in range(9) for i in range(3)]
    faces = []
    for j in range(8):
        for i in range(2):
            a, b, c, d = 3 * j + i, 3 * j + i + 1, 3 * (j + 1) + i + 1, 3 * (j + 1) + i
            faces += [(a, b, c), (a, c, d)]
    return pts, faces


# ---- brute force: the topology recomputed from the face list ----


def check_manifold(points, faces, closed):
    directed = {}
    for f in faces:
        assert len(set(f)) == 3
        for k in range(3):
            e = (f[k], f[(k + 1) % 3])
            assert e not in directed                          # consistent orientation, no edge used twice
            directed[e] = f
    if closed:
        assert all((v, u) in directed for u, v in directed)
    for v in {w for f in faces for w in f}:                  # the link of each vertex is one cycle or one path
        nxt = {}
        for f in faces:
            if v in f:
                k = f.index(v)
                nxt[f[(k + 1) % 3]] = f[(k + 2) % 3]
        starts = set(nxt) - set(nxt.values())
        assert len(starts) <= 1
        start = next(iter(starts)) if starts else next(iter(nxt))
        seen, w = 0, start
        while w in nxt and seen <= len(nxt):
            w = nxt[w]
            seen += 1
            if w == start:
                break
        assert seen == len(nxt)


def euler(points, faces):
    es = {(min(f[k], f[(k + 1) % 3]), max(f[k], f[(k + 1) % 3])) for f in faces for k in range(3)}
    return len({w for f in faces for w in f}) - len(es) + len(faces)


def area(points, faces):
    return sum(length(cross(sub(points[b], points[a]), sub(points[c], points[a]))) / 2 for a, b, c in faces)


def edge_lengths(points, faces):
    es = {(min(f[k], f[(k + 1) % 3]), max(f[k], f[(k + 1) % 3])) for f in faces for k in range(3)}
    return [length(sub(points[i], points[j])) for i, j in es]


def test_square_example() -> None:
    p = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)]
    mesh = Mesh(p, [(0, 1, 2), (0, 2, 3)])
    assert split_long_edges(mesh, 4 * 0.5 / 3) == 9          # the diagonal, the 4 sides, the 4 half-diagonals
    P, F = mesh.compact()
    assert (len(P), len(F)) == (13, 16)
    assert sorted(set(round(x, 12) for x in edge_lengths(P, F))) == [round(sqrt(2) / 4, 12), 0.5]
    assert (0.5, 0.5, 0.0) in P and (0.25, 0.25, 0.0) in P


def test_split_bounds_every_edge_and_keeps_the_surface() -> None:
    for (p, f), L in ((icosphere(0), 0.3), (rectangle(), 0.5)):
        mesh = Mesh(p, f)
        a0 = area(p, f)
        k = split_long_edges(mesh, 4 * L / 3)
        P, F = mesh.compact()
        assert max(edge_lengths(P, F)) <= 4 * L / 3
        assert abs(area(P, F) - a0) < 1e-9 * a0              # midpoints stay in the planes of the faces
        assert euler(P, F) == euler(p, f)
        assert len(F) >= len(f) + k                          # each split adds one or two faces
        check_manifold(P, F, closed=(len(p) == 12))


def test_collapse_respects_the_upper_bound() -> None:
    p, f = icosphere(2)
    L = 0.5                                                  # the edges of the input are about 0.3
    mesh = Mesh(p, f)
    split_long_edges(mesh, 4 * L / 3)
    n0 = len({w for g in mesh.F.values() for w in g})
    k = collapse_short_edges(mesh, 4 * L / 5, 4 * L / 3)
    P, F = mesh.compact()
    assert k > 0 and len(P) == n0 - k                        # each collapse removes one vertex
    assert max(edge_lengths(P, F)) <= 4 * L / 3
    assert euler(P, F) == 2
    check_manifold(P, F, closed=True)


def test_flips_reach_a_local_optimum() -> None:
    rng = random.Random(5)
    p, f = icosphere(2)
    p = [sphere(tuple(c + 0.04 * (rng.random() - 0.5) for c in v)) for v in p]
    mesh = Mesh(p, f)
    for u, v in rng.sample(sorted(mesh.he), 60):             # scramble the valences first
        if (u, v) in mesh.he and mesh.opposite(u, v) != mesh.opposite(v, u):
            c, d = mesh.opposite(u, v), mesh.opposite(v, u)
            if d not in mesh.neighbours(c) and len(mesh.neighbours(u)) > 3 and len(mesh.neighbours(v)) > 3:
                mesh.flip(u, v)

    def excess():
        live = {w for g in mesh.F.values() for w in g}
        return sum(abs(len(mesh.neighbours(w)) - 6) for w in live)

    e0 = excess()
    equalize_valences(mesh)
    assert excess() < e0
    for u, v in mesh.he:                                     # the brute-force scan: no improving flip is left
        assert mesh.flip_gain(u, v) == 0
    P, F = mesh.compact()
    check_manifold(P, F, closed=True)


def test_random_operations_keep_a_manifold() -> None:
    rng = random.Random(11)
    p, f = icosphere(1)
    mesh = Mesh(p, f)
    for _ in range(150):
        u, v = rng.choice(sorted(mesh.he))
        op = rng.randrange(3)
        if op == 0:
            mesh.split(u, v)
        elif op == 1 and mesh.can_collapse(u, v, float("inf")):
            mesh.collapse(u, v)
        elif op == 2 and mesh.flip_gain(u, v) > 0:
            mesh.flip(u, v)
        P, F = mesh.compact()
        check_manifold(P, F, closed=True)
        assert euler(P, F) == 2


def test_sphere_is_remeshed_to_the_target_length() -> None:
    rng = random.Random(3)
    p, f = icosphere(2)
    p = [sphere(tuple(c + 0.05 * (rng.random() - 0.5) for c in v)) for v in p]
    L = 0.15
    P, F = isotropic_remeshing(p, f, L, 5, project=sphere)
    check_manifold(P, F, closed=True)
    assert euler(P, F) == 2
    assert all(abs(length(q) - 1) < 1e-12 for q in P)
    vol = sum(dot(P[a], cross(P[b], P[c])) for a, b, c in F) / 6
    assert vol > 0                                           # the orientation is kept
    ls = edge_lengths(P, F)
    mean = sum(ls) / len(ls)
    assert abs(mean / L - 1) < 0.05                          # measured: 1.021
    assert sum(1 for x in ls if 4 * L / 5 <= x <= 4 * L / 3) / len(ls) > 0.98   # measured: 0.995
    angles = []
    for t in F:
        for k in range(3):
            a, b, c = P[t[k]], P[t[(k + 1) % 3]], P[t[(k + 2) % 3]]
            x, y = sub(b, a), sub(c, a)
            angles.append(degrees(acos(dot(x, y) / (length(x) * length(y)))))
    assert min(angles) > 35                                 # measured: 41 degrees, from 44 in the input


def test_border_is_kept() -> None:
    p, f = rectangle()
    P, F = isotropic_remeshing(p, f, 0.5, 5)
    check_manifold(P, F, closed=False)
    assert euler(P, F) == 1
    assert abs(area(P, F) - 32) < 1e-9
    assert all(q[2] == 0.0 for q in P)
    for q in p:
        if q[0] in (0.0, 8.0) and q[1] in (0.0, 4.0):
            assert q in P                                    # the corners stay
    directed = {(t[k], t[(k + 1) % 3]) for t in F for k in range(3)}
    for u, v in directed:
        if (v, u) not in directed:                           # a border edge lies on the rectangle
            a, b = P[u], P[v]
            assert (a[0] == b[0] and a[0] in (0.0, 8.0)) or (a[1] == b[1] and a[1] in (0.0, 4.0))
    angles = []
    for t in F:
        for k in range(3):
            a, b, c = P[t[k]], P[t[(k + 1) % 3]], P[t[(k + 2) % 3]]
            x, y = sub(b, a), sub(c, a)
            angles.append(degrees(acos(dot(x, y) / (length(x) * length(y)))))
    assert min(angles) > 20                                 # measured: 27 degrees, from 7 in the input

History

Remeshing by local operators grew out of the mesh optimization work of the 1990s, which used splits, collapses and swaps to fit a mesh to data. Surazhsky and Gotsman described explicit remeshing by local operators in 2003. In 2004 Botsch and Kobbelt, in a paper on multiresolution modeling, reduced the method to a loop of four steps with the thresholds 43L\frac{4}{3}L and 45L\frac{4}{5}L, and this simple form became the standard one in teaching and in libraries. The termination of the split step rests on the 1975 theorem of Rosenberg and Stenger on the angles of longest-side bisection.

References

  1. Mario Botsch and Leif Kobbelt, A remeshing approach to multiresolution modeling, Eurographics Symposium on Geometry Processing (SGP), 2004, 189 to 196, the remeshing loop of splits, collapses, flips and tangential relaxation, with the thresholds 4/3 and 4/5 of the target edge length
  2. Ivo G. Rosenberg and Frank Stenger, A lower bound on the angles of triangles constructed by bisecting the longest side, Mathematics of Computation 29(130), 1975, 390 to 395, the theorem that repeated longest-side bisection keeps every angle at least half the smallest angle of the first triangle
  3. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 6, Remeshing (incremental isotropic remeshing and the local operators)

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