MarchingSquares

I've been working on a 2d voxel based game with dynamic terrain, blah blah. In the interest of proof-of-concepting I used 3d marching cubes to compute the shape of the voxel space, which I basically projected to 2D, and then triangulated. It worked, but was a hotspot in my profiling.

I did some googling to see if there were any 2D versions... but as it happens, "MarchingSquares" is a totally different algorithm.

So I put pen to paper and worked out the edge tables and whatnot for a 2D variant of MarchingCubes -- much easier given there are only 16 intersection types instead of 256 -- and got it working yesterday.

Since I've gotten so much help in this forum over the years I'm contributing it here, for anybody who may need it in the future. It's C++ ( I know, yuck, whatever ) and I thin kit's fairly clean. It does depend on you providing some kind of Vec2f and Vec2i vector type with basic math operators. I'm using libcinder but you can provide your own easily enough.

/*
Given a GridCell and isolevel, compute the Segments required to represent
the isosurface through the cell.
Return the number of segments, the array 'segments' will be populated
with up to 2 Segments. Returns the number of Segments computed.

Now, here's demo code that calls marching squares and generates an array of continous clockwise windings from the unconnected segments marching squares generates. Holes in your isosurface will be wound in the counter-clockwise.

Note, this is demo code -- for dumb reasons my pretend voxel store is using a std::map instead of a 2d array so it's slow. The actual game uses faster lookups, but that's an irrelevant detail here