unity – Creating the Vertices and Triangle Indices for Voxel Generated Mesh

I am running into a problem with a compute shader I am writing to generate the vertices and triangle indices for a voxel generated mesh.

Currently, I am creating an AppendStructuredBuffer of triangle structs which just have the three vertices of a triangle and reading from the AppendStructuredBuffer to the CPU. When read to the CPU, I then read from the buffer and set it in a RWStructuredBuffer in the GPU. Following that, I run a compute shader kernel to parse the triangle buffer.

Obviously if I can do this all on the GPU I should since reading and writing between the CPU and GPU is expensive.

When trying to put it all in one kernel I run into problems however. Each voxel has a range of possible triangles (0-5) that can form in it. Because of that, I can’t simply use the dispatch ID to put it in a RWStructuredBuffer (at least I don’t think so). That’s why using an AppendStructuredBuffer seems natural; it allows for the variable amount of triangles.

After getting the array of triangle vertices and array of triangle vertex indices, I bring them back to the CPU and set them to a mesh and render it. In the future I want to use a geometry shader to render the mesh since that is most likely more efficient, but I’m trying to take this one step at a time, and geometry shaders are a whole ‘nother beast I know nothing about.