Marching-squares contour extraction for 2D scalar grids.
Given a rows × cols grid of numeric values, segments/5 produces a
set of line segments in data space where the scalar field equals each
requested level. The renderer draws these segments as Contour series
output — iso-lines suitable for topography, isobars, field intensity,
level sets of optimization landscapes.
The algorithm:
- For each cell (a 2×2 square of grid values), classify its four corners as above or below the target level.
- Each classification gives a case index 0..15; the case tells us how many segments (0, 1, or 2) to emit through the cell and where they enter / exit on the cell boundary.
- Each segment endpoint is linearly interpolated along the cell edge where the scalar value crosses the level.
The 16-case table is unambiguous for 14 cases; the two saddle cases (5 and 10) are broken by the "mean of four corners" convention — adequate for typical scientific data.
Output: [{level, [{p1, p2}, {p3, p4}, ...]}, ...] where each p
is {x, y} in data space.
Summary
Functions
Returns [{level, [{{x1,y1}, {x2,y2}}, ...]}, ...] — one entry per
requested level.