Skip to content

Instantly share code, notes, and snippets.

@cathode
Created January 11, 2013 00:56
Show Gist options
  • Select an option

  • Save cathode/4507101 to your computer and use it in GitHub Desktop.

Select an option

Save cathode/4507101 to your computer and use it in GitHub Desktop.
private void InitMarchingCubesAlgorithm()
{
// We need to calculate a list of the poly counts for each configuration of 'solid' and 'air' vertices.
// There are eight vertices, each one representing a bit of a byte.
// Look-up array for polygon count value that indicates how many (up to 5) polygons we need to create.
var pc = new byte[256];
// Look-up array for polygon edge connections, indicating which edges we need to connect together.
var ec = new EdgeConnections[256];
// Vertex neighbors. Each vertex of a cube has three neighbor vertices.
int[,] n = { { 1, 3, 4 }, { 0, 2, 5 }, { 1, 3, 6 }, { 0, 2, 7 }, { 0, 5, 7 }, { 1, 4, 6 }, { 2, 5, 7 }, { 3, 4, 6 } };
// Vertex edges. Each vertex has three outgoing edges.
int[,] en = { { 0, 3, 8 }, { 0, 1, 9 }, { 1, 2, 10 }, { 2, 3, 11 }, { 4, 7, 8 }, { 4, 5, 9 }, { 5, 6, 10 }, { 6, 7, 11 } };
var vs = new int[8];
// Loop over all 254 possible variations of a cube's vertices.
for (int i = 0; i < 255; ++i)
{
// this is our count for vertices that are solid.
var v = 0;
// Each vertex is either 'solid' or 'not solid', with eight vertices this means we
// decompose a byte into bits in a loop.
for (int j = 0; j < 8; v += vs[j++])
vs[j] = (i & (1 << j)) >> j;
for (int nv = 0; nv < 8; ++nv)
{
int nc = 1;
for (int k = 0; k < 3; ++k)
if (vs[n[nv, k]] > 0)
++nc;
// We don't connect any edges where both vertices of the edge are solid.
if (nc == 4)
--v;
}
var c = new EdgeConnections();
ec[i] = c;
// assign our final polygon count for 'i' configuration.
pc[i] = (byte)v;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment