- Home /
Using IJobParallelFor for generating meshes with an unknown number of vertices
I'm trying to convert my implementation of the Marching Cubes algorithm to use the Jobs system, but can't figure out whether it is possible to do so using IJobParallelFor.
Each 'cell', or 'voxel' the needs to be generated can create anywhere from 0-5 triangles (and corresponding vertices), and I need to be able to return the vertices generated in the job back to the main thread, so that I can apply them to the mesh.
static void GenerateCell((int x, int y, int z)position, float[] corners, Dictionary<Vector3, int> verts, List<int> tris, float surface)
{
byte vertFlags = 0x0;
for (int i = 0; i < 8; i++)
if (corners[i] <= surface)
vertFlags |= (byte)(1 << i);
int edgeFlags = EdgeFlags[vertFlags];
// Return early if no new geometry will be made
if (edgeFlags == 0) return;
// Loop over edges
for (int i = 0; i < 12; i++)
{
if ((edgeFlags & (1 << i)) != 0) // Edge flag is set for this edge
{
float offset = GetOffset(corners[EdgeConnections[i].a], corners[EdgeConnections[i].b], surface);
_edgeVertices[i].x = position.x + VertexOffsets[EdgeConnections[i].a].x + EdgeDirections[i].x * offset;
_edgeVertices[i].y = position.y + VertexOffsets[EdgeConnections[i].a].y + EdgeDirections[i].y * offset;
_edgeVertices[i].z = position.z + VertexOffsets[EdgeConnections[i].a].z + EdgeDirections[i].z * offset;
}
}
// Loop over triangles (to be made)
for (int i = 0; i < 5; i++)
{
if (TriTable[vertFlags, i * 3] < 0) break; // -1 termination (in table)
for (int j = 0; j < 3; j++)
{
int index = TriTable[vertFlags, i * 3 + j];
Vector3 vert = _edgeVertices[index];
if (!verts.ContainsKey(vert)) // If vertex is new, add to verts and add triangle
{
tris.Add(verts.Count); // Add tri before adding vert (before verts.Count changes)
verts.Add(vert, verts.Count); // Append to verts
}
else // If vertex already exists, get its index
{
tris.Add(verts[vert]);
}
}
}
}
// Fast version of Mathf.InverseLerp(a, b, surface)
static float GetOffset(float a, float b, float surface)
{
float delta = b - a;
return delta == 0 ? surface : (surface - a) / delta;
}
I'm having trouble figuring out how to return an unknown number of values for each index from IJobParallelFor, while still being able to read those values.
Your answer
Follow this Question
Related Questions
Voxel Marching Hibrid 0 Answers
How do I get my game to run faster? 4 Answers
Cleaner scripting 0 Answers
Making a GetComponent array 1 Answer
unity 3.0 or 3.1 script reference can't search ? But 2.6 did not have this problem. 3 Answers