Marching Squares
Extract contour lines from a scalar field using the marching squares algorithm. Paint values onto a grid, choose a threshold, and watch isolines form in real time — the same technique behind topographic maps, weather isobars, and medical imaging.
What’s happening
The marching squares algorithm
Marching squares extracts contour lines (isolines) from a 2D scalar field. The field is sampled on a regular grid, and each 2×2 block of samples forms a cell. Each corner is classified as above or below the threshold, producing a 4-bit index (0–15) that maps to one of 16 possible edge configurations. Line segments are placed along the cell edges where the contour crosses, and linear interpolation positions them precisely.
The 16 cases
Four corners, each binary (above/below), gives 24 = 16 cases. Two are trivial (all above or all below — no contour). The remaining 14 produce one or two line segments per cell. The ambiguous cases (where diagonally opposite corners are above threshold) require a disambiguation rule — this implementation uses the average of all four corners to decide which connection to make.
Why it matters
Marching squares is used everywhere: topographic maps extract elevation contours, weather maps show isobars (pressure) and isotherms (temperature), medical imaging traces organ boundaries in CT scans, and computer graphics renders implicit surfaces. Its 3D sibling, marching cubes, does the same for volumetric data — extracting triangle meshes from MRI and CT scans.
Linear interpolation
Without interpolation, contours snap to cell midpoints, producing blocky staircase patterns. With interpolation, the crossing point along each edge is computed as a weighted average of the two corner values, placing the contour line exactly where the field equals the threshold. The result is smooth, accurate contours from coarse grid data.
The lookup table
Case index = (TL ≥ t)·8 + (TR ≥ t)·4 + (BR ≥ t)·2 + (BL ≥ t)·1 Each case maps to 0, 1, or 2 line segments Edge crossings interpolated: x = x0 + (t - v0)/(v1 - v0) · (x1 - x0)
The elegance of marching squares is that a simple lookup table replaces complex geometric reasoning. The same principle — classify, look up, interpolate — extends to marching cubes (256 cases), marching tetrahedra, and even higher dimensions.