./jerome{m}jack in

~/Notes/Dual Contouring.md · note · seedling · 12 min · updated

Dual Contouring

// status: seedling

If Marching Cubes is the "smooth blob" algorithm, Dual Contouring is the "keep the sharp edges" algorithm. Introduced by Ju, Losasso, Schaefer & Warren in 2002, it's the iso-surface extractor you want when you're carving with a flat brush and want the flat bits to stay flat.

The short version of why it works: Marching Cubes may only put a vertex on a grid edge, and a corner almost never sits on a grid edge. Dual Contouring puts its vertices inside the cells, which is where the corners are.

The dual trick

Marching Cubes is primal: it puts vertices on the edges of cells. Dual Contouring is dual: it puts one vertex inside each cell, then connects vertices of the four cells sharing a sign-crossing edge into a quad.

That flip gives DC two superpowers:

  1. Adaptive resolution is natural — since each cell has one vertex, you can have an octree with cells of different sizes and still connect them cleanly.
  2. Sharp features are recoverable — if you have normals at the sign-crossing points (not just positions), you can place the interior vertex at the location where those planes meet.

The paper describes itself as a hybrid of two earlier methods: it takes the vertex placement of Extended Marching Cubes and applies it to every cell, and it takes its connectivity from Surface Nets. Nothing has to be detected or classified first, which is most of its appeal.

Hermite data

DC doesn't work from just the scalar field. You need Hermite data: for each edge that crosses the iso-surface, both the crossing position and the normal of the surface there. For analytic SDFs you get both trivially. For sampled data (a CT scan, noise-based terrain) the gradient gives you the normal.

Where each half comes from matters more than it looks:

  • The position should be the real crossing, not a guess. Linear interpolation between two samples is exact on a flat face and wrong near a corner, where the two samples measure their distance to different faces. If the field can be evaluated, bisect along the edge until the sign flips; a dozen halvings is plenty.
  • The normal should be the surface normal at that crossing, evaluated there. An analytic gradient is best. Central differences work if the step is small against the cell size; Normals for Implicit Surfaces has the details. For CSG, take the normal of whichever operand is active at the crossing, not a blend.
  • Storage is per edge, not per sample: a crossing parameter and a normal for each edge that changes sign. That is the real cost of the algorithm. The field alone is no longer enough to rebuild the mesh.

The QEF

For each cell, collect all its edges that cross the surface. Each crossing gives you a point p_i and a normal n_i — implicitly a plane n_i · (x − p_i) = 0. Place the cell vertex at the point that minimises the sum of squared distances to all these planes:

E(x) = \sum_i (n_i \cdot (x - p_i))^2

This is a Quadratic Error Function (QEF). Expand it and it's a linear least squares problem in 3 unknowns. Solve with SVD — not a normal equation — because many cells are underdetermined (one plane, a flat feature) and SVD gives you the minimum-norm solution with graceful degradation.

c
// Pseudo: minimise || A x - b ||^2 with SVD, clamp x into the cell bounds.
Mat3 A;  // rows are n_i
Vec3 b;  // b_i = n_i . p_i
for (crossing in edges) {
    A.addRow(crossing.normal);
    b.addRow(dot(crossing.normal, crossing.pos));
}
Vec3 x = svdSolve(A, b, massPoint);    // mass point = average of p_i as a fallback
x = clampToCell(x);                     // keep the vertex inside the cell

The mass point is a regularisation trick: bias the solution toward the average of the crossing points so that underdetermined cells give sensible results.

Clamp the final vertex to the cell bounds. Without this, sharp features can place vertices arbitrarily far outside their cell, creating self-intersecting geometry.

What the rank tells you

With A holding one unit normal per row, the number of singular values that are not close to zero says what kind of cell it is:

RankThe normals…The minimiser is…The cell contains
3point three independent waysa single pointa corner
2all lie in one planea whole linea sharp edge
1all agreea whole planea flat face

For rank 2 and rank 1 there is no single answer, so pick the one nearest the mass point c. Solving for the offset from c does exactly that:

x = c + V\,\Sigma^{+}\,U^{T}(b - A\,c)

where Σ⁺, the pseudo-inverse of Σ, inverts the singular values that are large enough and zeroes the rest. The paper truncates singular values below 0.1, chosen by experiment, and the number is meaningful because the rows are unit normals. On a flat face the vertex stays at the mass point; on an edge it slides along the edge to the point nearest the mass point; on a corner it lands on the corner.

Truncation is also the paper's answer to runaway vertices. When noisy normals are nearly coplanar, A is nearly singular and the exact minimiser can sit far outside the cube. Zeroing the small singular value removes the direction the data says nothing about. Clamping to the cell, as above, is a second and blunter guard. The paper gets by on truncation alone; with normals from a sampled field you want both, at a small cost in accuracy that the demo below makes visible.

Why not the normal equations

The obvious way to store a QEF is A^T A, A^T b and b^T b: ten floats, and you can add two QEFs by adding the numbers. The paper rejects it for single precision. On a 256³ grid b^T b reaches the order of 10⁶, floats carry about six digits, and the error at a point that should score zero comes out near 1. Doubles fix the arithmetic and double the memory.

Its alternative keeps ten floats: append b to A as a fourth column, reduce that matrix to upper-triangular form with Givens rotations, and store the triangle. Two QEFs merge by stacking their triangles and reducing again. The SVD then runs on the 3×3 upper-left block.

Doubles are the paper's own first suggestion and they do fix the arithmetic, at twice the storage. In single precision the warning below stands.

Sharp features, worked through

Here is the whole idea in two dimensions. The shape is known exactly; each extractor only sees where it crosses the grid edges and which way it faces there (the white ticks). Hover a cell to see its tangent lines and the point where they agree best.

contour · liveOne shape, three extractors, the same Hermite data. Switch between marching, extended and dual; drag the shape; change the grid. The label reports how far the worst corner is from the outline.open ↗

Things to try, and what each shows:

  • Switch to marching. Every corner becomes a chord. The crossings are exact, so this is not an interpolation error: the extractor has nowhere to put a vertex except on a grid edge.
  • Back to dual. In a corner's cell the two tangents meet at the corner, and that is where the QEF puts the vertex. The corner miss drops to zero, or close to it.
  • Drag slowly until the miss is no longer zero. A corner can poke into a cell without its sides crossing two different edges of it. That cell sees nothing; the neighbour sees both sides and solves for a corner that lies outside itself. With clamp on, the vertex is held at the neighbour's wall, short of the corner by however far it pokes in. Turn clamp off and it reaches the corner, at the price of leaving its cell.
  • Pick the wedge. Its tip is narrower than a cell and no grid node falls inside it, so no edge changes sign there. For all three extractors the tip does not exist, and the miss is more than a cell. Hermite data sharpens what the grid sees; it cannot recover what the grid never sampled. Drag the wedge and you will also catch cells that both of its sides pass through, where one vertex has to serve two pieces of outline and welds them: the non-manifold case below.
  • Pick the disc. On a smooth shape all three nearly agree. At the default grid extended already adds a red vertex where the normal turns past its threshold within one cell: a tight curve and a corner look the same to a threshold. Refine the grid and it goes away.

In three dimensions the picture gains one case. A 2D corner is the only kind of feature; in 3D there are edges (two faces meet, rank 2) and corners (three or more, rank 3), and the QEF handles both without being told which is which.

Building the mesh

Once every cell has a vertex, the mesh is implicit in adjacency:

  • For every cell edge that crosses the surface, the four cells sharing that edge each have a vertex — connect them into a quad.
  • Orient consistently using the sign of the edge crossing.

In an octree with different cell sizes, the "four cells sharing an edge" become potentially 2× or 4× smaller cells on one side. The same adjacency logic still works, you just walk the tree to find the neighbours at each scale.

On a uniform grid this is one loop over edges and no lookup table. Skip edges on the outer boundary of the volume: they have fewer than four cells around them. The quads are generally not planar, so the choice of diagonal is visible when you split them into triangles; splitting along the diagonal whose two triangles agree best with the vertex normals keeps feature edges crisp.

Adaptive octrees

The second half of the paper is what makes DC more than a sharper Marching Cubes. Three pieces fit together:

  1. QEFs add. The QEF of a parent node is the sum of its children's, so the octree can be simplified bottom-up with no access to the original data. A parent whose summed QEF has a residual below a tolerance is collapsed into a leaf, and its minimiser becomes the vertex. Flat regions collapse quickly; features resist, because no single point satisfies all their planes.
  2. Minimal edges decide the polygons. In a mixed-size octree, a minimal edge is a leaf's edge that does not properly contain an edge of a smaller neighbour. For each minimal edge with a sign change, connect the vertices of the leaves that contain it: four leaves give a quad, three give a triangle. The paper enumerates them with three mutually recursive functions over cells, faces and edges.
  3. The result is closed. Every mesh edge ends up shared by an even number of polygons, for any simplified octree. There is no restriction on neighbouring levels and no crack patching.

Compare that with Marching Cubes, where neighbouring levels of detail disagree along their shared face and need a dedicated fix such as Transvoxel.

The catch is that collapsing can change the surface's topology: two sheets that pass through one coarse cell get a single vertex. The paper adds a topology safety test that refuses such collapses.

Dual contouring for terrain

DC earns its cost on terrain that has things to keep sharp: buildings, mined tunnels with flat walls, cliffs cut by CSG, anything sculpted with a flat brush. On rolling hills from noise it produces the same surface as Marching Cubes with more machinery.

What changes compared with a Marching Cubes terrain such as Raym:

  • Edits write Hermite data. A brush has to update crossings and normals on every edge it touches, not only sample values. For an analytic brush this is easy, since the brush knows its own normal. See From Brush Stroke to Mesh - Real-Time Voxel Terrain Editing in C for the edit loop this replaces.
  • Chunk borders need neighbours. A quad joins four cells, so quads along a chunk face use vertices owned by the next chunk. Either build each chunk with a one-cell overlap or mesh the seams as their own pass. The sample-ownership rules in Seamless Chunked Voxel Terrain apply unchanged.
  • Level of detail is the easy part, when the world is one octree. With independent chunks at different levels, the seam between them is a small octree problem of its own.
  • The field still has to be well behaved. Designing Scalar Fields for Procedural Terrain applies as written; DC adds a demand for trustworthy normals on top.

If the terrain is smooth and you only want fewer, better-shaped triangles than Marching Cubes gives, Surface Nets is the cheaper answer.

Variants and fixes

The classic DC paper has a few known problems that later work addressed:

  • Non-manifold output — a single cell can have multiple disjoint surface patches inside it. Vanilla DC places one vertex, which welds them together. Manifold Dual Contouring (Schaefer & Warren) detects this and splits the cell into multiple vertices.
  • Self-intersections — particularly on thin features. Clamping to the cell and constraining the QEF helps; more robust variants add explicit checks.
  • Intersection-free contouring (Ju et al., 2006) — extensions that guarantee no self-intersection.

And the neighbours it is most often confused with:

  • Surface Nets (Gibson, 1998) has the same connectivity and no normals. The original relaxes each cell's vertex toward its neighbours while keeping it inside the cell; the "naive" variant simply averages the cell's edge crossings. Smooth results, rounded corners, a fraction of the code.
  • Extended Marching Cubes (Kobbelt et al., 2001) keeps the Marching Cubes structure and adds one feature vertex to the cells that test as sharp. It is where DC's vertex rule comes from.
  • Dual Marching Cubes (Schaefer & Warren, 2004) is a different algorithm despite the name: it builds a dual grid from an octree and runs Marching Cubes over that.

DC vs Marching Cubes — when to reach for each

PropertyMarching CubesSurface NetsExtended MCDual Contouring
Sharp featuresNo — rounds edgesNoYes, in cells that pass a thresholdYes, with Hermite data
Adaptive LODAd hoc (Transvoxel)Needs stitchingAd hocNative via octree
Input neededScalar valuesScalar valuesValues + edge normalsValues + edge normals
Vertices sitOn grid edgesIn cellsOn edges, plus one per feature cellIn cells
Mesh regularityTriangles, higher countQuadsTriangles, highest countQuads, fewer elements
Topological robustnessAmbiguity casesNon-manifold casesAmbiguity casesNon-manifold cases
Implementation effortLowLowMedium (tables + SVD + edge flips)Medium–high (SVD, octree plumbing)

Rule of thumb: if you're building Minecraft-style sculpting with flat walls and 90° corners, DC. If you're rendering a medical scan or organic terrain, MC (or Surface Nets) is simpler and fine.

If you already have a working Marching Cubes pipeline and only some of your content has hard edges, Extended Marching Cubes is the smaller change. If you are starting fresh and want level of detail as well, DC gets you both from one data structure.

Things that tripped me up

  • SVD on the small matrix — rolling your own 3×3 SVD is fiddly. I've used the Givens-rotation variant from the DC reference code. Don't use the normal equations (A^T A), they square the condition number.
  • Cell clamping is not optional — without it, outputs look plausible but self-intersect under stress.
  • Hermite data quality — the whole algorithm stands on the accuracy of your normals. A finite-difference gradient at a lousy step size ruins sharp features.
  • Octree neighbour walks — the part that takes the longest to write. The DC mesh is only as clean as your adjacency logic.
  • Clamping costs a little accuracy — a corner that pokes into a cell without crossing two of its edges is solved by the neighbour and held at the wall. The demo above shows it as a corner miss that is small but not zero.
  • A feature thinner than a cell is lost or welded — if no sample falls inside it, no extractor sees it; if two sheets share a cell, one vertex cannot describe both. Refining the grid fixes either; the manifold variant fixes only the second.

References

  • Ju, T., Losasso, F., Schaefer, S., & Warren, J. — Dual Contouring of Hermite Data (SIGGRAPH 2002)
  • Schaefer, S., & Warren, J. — Dual Contouring: "The Secret Sauce"
  • Lin Reid's blog has an approachable implementation walk-through; Nick Gildea's "Dual Contouring the Easier Way" is the other one I reread often.
  • The 2002 paper itself: PDF from Rice · doi:10.1145/566570.566586. Section 2.3 has the QEF numerics, section 3 the octree.
  • Kobbelt, L., Botsch, M., Schwanecke, U., & Seidel, H.-P. — Feature Sensitive Surface Extraction from Volume Data (SIGGRAPH 2001) · doi:10.1145/383259.383265
  • Schaefer, S., Ju, T., & Warren, J. — Manifold Dual Contouring (IEEE TVCG, 2007) · doi:10.1109/TVCG.2007.1012
  • Schaefer, S., & Warren, J. — Dual Marching Cubes: Primal Contouring of Dual Grids (Pacific Graphics 2004) · doi:10.1109/PCCGA.2004.1348336
  • Gibson, S. — Constrained Elastic Surface Nets: Generating Smooth Surfaces from Binary Segmented Data (MICCAI 1998) · doi:10.1007/BFb0056277

Back to Notes · see also Marching Cubes · Extended Marching Cubes · Sparse Voxel Octrees · Spatial acceleration structures