https://github.com/mattlack15/MarchingSquares
This is my implementation of the marching squares algorithm in Kotlin. Given any function f(x, y), it draws the curve where f(x, y) = 0. Right now it's drawing meta balls, because they look cool, but it can draw any function you give it.
The Problem
Drawing y = x² is easy, you go along the x-axis and compute y. But a lot of curves can't be written that way. A circle is x² + y² - r² = 0, and for something like the meta balls above there is no nice way to solve for y at all. What you can do is evaluate the function at any point and see whether it's positive or negative. Marching squares turns that into a curve.
How it works
- Sample a grid. The screen is divided into 8x8 pixel squares, and the function is evaluated at every corner. Each corner is either inside (f ≥ 0) or outside (f < 0).
- Skip the boring squares. If all four corners of a square are inside, or all four are outside, the curve doesn't pass through it. This is most of the screen.
The renderer has a debug mode (showDots) that draws the corner samples on top of the curve. Here it is zoomed in on three meta balls that have merged into one blob. Green dots are inside, gray dots are outside, and the curve only gets drawn through the squares that have both.
- Look up the case. The four corners give a 4-bit number, so there are 16 possible cases. Each case says which edges of the square the curve crosses, and therefore which edges to connect with a line:
// From left to right in 0b???? format:
// Bottom Left, Bottom Right, Top Right, Top Left
when (case) {
0b1100, 0b0011 -> lines.add(getLine(sides[1], sides[3]))
0b1001, 0b0110 -> lines.add(getLine(sides[0], sides[2]))
0b1110, 0b0001 -> lines.add(getLine(sides[2], sides[3]))
// ...
}
- Handle the ambiguous cases. When two diagonally opposite corners are inside and the other two are outside (0b1010 and 0b0101), there are two different ways the curve could pass through the square. To decide, I sample one more point in the middle of the square and connect the edges based on whether the middle is inside or outside.
- Find where the curve actually crosses. Most implementations linearly interpolate between the corner values to place the line endpoints. I do a binary search along the edge instead, 8 steps, which gets within 1/256 of a square (a few hundredths of a pixel here). The nice part is that it only needs to know whether a point is inside or outside, so it works for any function, not just ones that behave nicely between the grid points.
Here's all of that on a grid that's much coarser than the real one, so you can see the individual squares. Each square the curve passes through is labelled with its case, in the same bit order as the code above. The highlighted square is an ambiguous 1010: its middle sample is inside, so the edges get connected in the way that keeps the two blobs joined. The small white dots are every point the binary search tested, bunching up where the curve crosses each edge.
The binary search makes more of a difference than you might expect. This is the same shape on a coarse grid with 0, 2 and 8 search steps. With 0 steps every end-point lands in the middle of its edge, which gives the blocky look. The thin white line is the same function on a very fine grid, for reference.
If the function returns NaN or infinity at any corner of a square, that square is skipped. Otherwise, something like 1/x would draw a vertical line straight through its asymptote. Here's a scaled 1/x - y with the asymptote lined up on a grid column, so the corners on it come back as infinity. On the left the squares touching it (shaded) are skipped. On the right I swapped the infinity for a huge finite number so the check never sees it, and the line shows up.
Rendering
The algorithm gives back a big pile of tiny line segments. Before drawing, I stitch them back together into continuous curves by building a map from each endpoint to the segments touching it, and walking along it. Each curve is then drawn as a single polyline with rounded joins and a red-to-blue gradient, which looks a lot smoother than thousands of separate segments.
Meta Balls
Each meta ball contributes this function, and the drawn curve is where the sum over all the balls crosses zero:
val function = { x: Double, y: Double ->
val dx = x - this.x
val dy = y - this.y
val r = radius
r * r / (dx * dx + dy * dy) - 1.0
}
Close to a ball the value shoots up, and far away it fades out, so when two balls get close their regions merge into one blob. There are six balls bouncing around the screen, and holding space pauses them.
Differentiable Functions
While working on this I also wrote a small library for building differentiable functions, in the function package. Functions can be added, multiplied, divided and composed with normal Kotlin operators, and each one knows its own derivative. For example, composition implements the chain rule:
class ChainedFunction(
val parent: DifferentiableFunction,
val child: DifferentiableFunction
) : DifferentiableFunction() {
override fun invoke(x: Double): Double {
return parent(child(x))
}
override fun derivative(): DifferentiableFunction {
return ChainedFunction(parent.derivative(), child) * child.derivative()
}
}
I might expand this project into a graphing calculator one day, and this would be the start of it.
Fun Fact
At first I computed the grid in parallel on a ForkJoinPool. It turned out to be slower: each task was so short that the overhead of scheduling it was more than the work itself, so I took the parallelization back out.