Marching cubes / isosurface extraction
What it does
Two related entry points sharing one engine:
extract_isosurface(values, bmin, bmax, iso, surface, status)— module-level subroutine. Given a 3D scalar field on a regular grid, extract the iso=isosurface as afacet_objectarray.surface%resample_via_distance_field(resolution, surface_out, status)— TBP. Sampleself's signed distance on a regular grid spanning the bbox, then callextract_isosurfaceat iso=0. Closes the SDF → STL loop: any FOSSIL surface can be re-tessellated through its own distance field.
The marching cubes algorithm itself is well-known (Lorensen & Cline SIGGRAPH 1987); FOSSIL embeds Bourke's canonical 256-entry case-table data. The engineering interest is the second TBP: it turns FOSSIL into a level-set repair tool. Sample SDF, extract iso=0, get a watertight triangulation whose distribution is determined by the grid spacing (not the input's noisy tessellation).
A rounded box decimated to 402 facets, most of them long slivers (the box of the decimation page), resampled at resolution 32: 4192 facets of the grid's size, watertight, volume 1.9710 to 1.9587:
Pipeline
For each grid cell with corners (i..i+1, j..j+1, k..k+1):
- Classify each corner as inside (
value < iso) or outside. The 8 corners give an 8-bit case index in[0, 255]. - Look up triangulation pattern in Bourke's case table — up to 5 triangles per cell, with edges identified by their endpoint cube-edge index.
- Linearly interpolate each triangle vertex along its cube edge:
t = (iso - v_a) / (v_b - v_a)is the fractional position between corneraand cornerb. Position isbmin + (i, j, k + offsets) * cell_sizein world coordinates. - Append the resulting triangles to a flat output buffer.
After extraction, adjacent cubes share edge-vertices that get emitted twice (once per cube). When the result is adopted into a surface_stl_object, analyze runs connect_nearby_vertices which dedupes them via the vertex pool, producing a watertight mesh.
Nodes on the level. A node whose value equals iso counts as outside, and every crossing on its edges is the node itself, bit for bit: the triangles that collapse there have coincident vertices and are not emitted. A node within round-off of iso is treated the same way (issue #87): if every crossing on its grid edges lies within 1e-12 of a cell side of it, it takes the value iso. A sphere sampled on a grid with nodes on it is the common case: norm2(p) - 1 at (0, −0.6, −0.8) on a grid of spacing 0.1 is −1.1e-16, not 0, and the crossings 1e-16 from the node made slivers of area 1e-32 that the curvature and smoothing routines report as degenerate (status 2). Fields with no node that close to the level give the same triangles, bit for bit.
The four stages on 3³ cells of side 1, the field the signed distance to a sphere of radius 2.3 about (3.4, −0.4, 3.4): 7 corners inside, 57 outside, 13 triangles. Every triangle vertex lies on a cell edge between an inside and an outside corner:
API
extract_isosurface (module function)
use fossil, only : extract_isosurface
call extract_isosurface(values, bmin, bmax, iso, surface, status)
real(R8P), intent(in) :: values(:, :, :)
type(vector_R8P), intent(in) :: bmin, bmax
real(R8P), intent(in) :: iso
type(facet_object), allocatable, intent(out) :: surface(:)
integer(I4P), intent(out), optional :: statussurface is a flat array of triangles; pass it to surface_stl_object%adopt_facets to turn it into a queryable surface.
resample_via_distance_field (TBP)
call self%resample_via_distance_field(resolution, surface_out, status)
class(surface_stl_object), intent(in) :: self
integer(I4P), intent(in) :: resolution
type(surface_stl_object), intent(out) :: surface_out
integer(I4P), intent(out), optional :: statusresolutionis the grid-corner count along the longest bbox axis; the other two scale proportionally so cells stay cubic.- A 5 % bbox-diagonal margin is added around the source to make sure the geometry doesn't touch the grid boundary.
surface_outmust be distinct fromself— aliasing them would consumeself%facetmid-loop.
Example
extract_isosurface on the signed distance of the unit sphere, sampled on [-1.5, 1.5]³ with the spacing h halved twice, measured against the exact volume
previous = 0._R8P
do m = 0, 2
n = 16 * 2**m + 1 ! 17, 33, 65 samples per side of [-1.5, 1.5]^3
h = 3._R8P / (n - 1)
allocate(phi(n, n, n))
do k = 1, n ; do j = 1, n ; do i = 1, n
phi(i, j, k) = norm2(-1.5_R8P + h * ([i, j, k] - 1)) - 1._R8P ! signed distance to the unit sphere
enddo ; enddo ; enddo
call extract_isosurface(values=phi, bmin=vector_R8P(-1.5_R8P, -1.5_R8P, -1.5_R8P), &
bmax=vector_R8P(1.5_R8P, 1.5_R8P, 1.5_R8P), iso=0._R8P, surface=facets, status=status)
if (status /= MC_STATUS_OK) error stop 'marching cubes failed'
call sphere%adopt_facets(facets=facets) ! analyze merges the vertices shared by cells
error = EXACT - sphere%get_volume()
print '(A,F7.5,A,I5,A,L1,A,ES8.2)', 'sphere, h ', h, ': ', sphere%get_facets_number(), ' facets, watertight ', &
sphere%is_watertight(), ', volume error ', error
if (m > 0) print '(A,F4.2)', ' error ratio to the previous h ', previous / error
previous = error ; deallocate(phi)
enddoresample_via_distance_field on cube-01.stl, at three resolutions:
call body%load_from_file(file_name='cube-01.stl', guess_format=.true.) ! the unit cube, 48 facets
do m = 0, 2
n = 12 * 2**m ! grid points along the longest side
call body%resample_via_distance_field(resolution=n, surface_out=resampled, status=status)
if (status /= MC_STATUS_OK) error stop 'resample failed'
print '(A,I2,A,I5,A,L1,A,F7.5,A,ES8.2)', 'cube at ', n, ': ', resampled%get_facets_number(), ' facets, watertight ', &
resampled%is_watertight(), ', volume ', resampled%get_volume(), ', deficit ', 1._R8P - resampled%get_volume()
enddo$ ref_marching_cubes
sphere, h 0.18750: 1064 facets, watertight T, volume error 8.72E-02
sphere, h 0.09375: 4280 facets, watertight T, volume error 2.20E-02
error ratio to the previous h 3.97
sphere, h 0.04688: 17192 facets, watertight T, volume error 5.47E-03
error ratio to the previous h 4.02
cube at 12: 1196 facets, watertight T, volume 0.98567, deficit 1.43E-02
cube at 24: 4796 facets, watertight T, volume 0.98800, deficit 1.20E-02
cube at 48: 21164 facets, watertight T, volume 0.99759, deficit 2.41E-03- Watertight. Every extraction is closed once
adopt_facetshas merged the vertices that neighbouring cells emit twice: nosanitizeis needed on these smooth fields. - Second order. The sphere's volume error falls by 3.97 and 4.02 when
hhalves: the linear interpolation along the cell edges puts the vertices on the sphere to O(h²), and the chords between them cut inside it by O(h²). The facet count grows as(1064, 4280, 17192). - Corners and edges. On the cube, the distance is linear across every face, so the faces come out flat and exact; the deficit comes from the cells across the 12 edges and 8 corners, where the chords cut them. How much depends on where the faces fall inside the cells (the grid spans the box plus a 5 % margin), so it does not fall smoothly with the resolution: 1.43e-2, 1.20e-2, 2.41e-3.
- Count. 1196 to 21164 facets for a body of 48:
decimatebrings the count back down when it matters.
Visual reference
Sphere extracted from analytic SDF at 64³ grid resolution (9452 facets, volume 4.179 vs analytic 4.189):
Cube resampled through its own SDF at resolution=64 (40 364 facets, volume 0.99997: close, not bit-exact, the deficit is 3.4e-5); a corner, zoomed (the whole surface is too heavy to draw):
The resampled cube has far more triangles than the input (12 → 40 k) because MC tessellates by grid cell, not by silhouette. Run decimate afterwards if the count matters.
Known limitations
- Lorensen-Cline ambiguity on cases 105 / 150. The standard 256- entry MC table doesn't disambiguate the diagonally-opposite- corners-inside cases — the same case index can produce surfaces with topologically-different connectivity at adjacent cubes, occasionally leaving small holes. MC33 (Chernyaev 1995) is the documented upgrade path; for typical AMR-CFD use cases (smooth SDF, well-resolved grid), the ambiguity rarely fires.
resample_via_distance_field'ssurface_outcannot aliasself. Passing the same surface for both consumesself%facetmid-loop and produces an empty output. Always use a distinct destination surface.- Output triangle count grows as
resolution²(surface area / cell-face area). 32³ resolution typically gives a few thousand facets; 128³ gives hundreds of thousands. Plan fordecimateafter if downstream cares about count. - The output isn't exactly watertight by construction — MC's per-cell triangulation can create tiny T-junctions at refinement transitions of the input SDF.
adopt_facets'sconnect_nearby_verticesfilters most of these; the rest are closed bysanitizeif needed.
See also
surface%distance— the signed-distance query thatresample_via_distance_fieldsamples internally.decimate— the natural follow-up if the MC output is denser than the downstream pipeline can handle.alpha_wrap— the heavyweight alternative for inputs too dirty for SDF resampling to repair.
References
- Lorensen & Cline, Marching Cubes: A High Resolution 3D Surface Construction Algorithm, SIGGRAPH 1987. The reference algorithm.
- Bourke, Polygonising a scalar field, 1994 (online article). The canonical 256-entry case table FOSSIL embeds.
- Chernyaev, Marching Cubes 33: Construction of Topologically Correct Isosurfaces, GVG technical report 1995. The topology-correct upgrade path (MC33) that closes the ambiguity gap.