Optimizing Unity mesh generation | Faster than SetVertexBufferData/ SetIndexBufferData

Viewed 56

I’m trying to squeeze every bit of performance out of some voxel mesh generation, and it takes about 1.1ms per chunk at the moment (average measurements):

  • ~0.04ms for vertex, normal, and triangle index calculation in a burst job
  • ~0.61ms for the SetVertexBufferData call
  • ~0.45ms for SetIndexBufferData call

Is there a better way to update a mesh than this? Maybe one that works inside a burst job? I know 1.1ms is pretty fast but I can't help but feel like I'm missing out on performance when the actual data generation is an order of magnitude faster.

Here's what I have:

// Input heightmap
// arr is an int[] created from perlin noise
NativeArray<int> heights = new NativeArray<int>(arr, Allocator.TempJob);
int numVerts = heights.Length * 20;

// VData is the struct: { float3 Vert; float3 Norm; }
NativeArray<VData> verts = new NativeArray<VData>(numVerts, Allocator.TempJob);

// Triangle indices
NativeArray<ushort> tris = new NativeArray<ushort>(heights.Length * 30, Allocator.TempJob);

// create Verts, Tris, and Norms in IJob
Job job = new Job
{
    Heights = heights,
    Verts = verts,
    Tris = tris
};

// Calculate the values
job.Schedule().Complete();

int indices = heights.Length * 30;

Mesh mesh = new Mesh();

mesh.SetVertexBufferParams(numVerts,
    new VertexAttributeDescriptor(VertexAttribute.Position),
    new VertexAttributeDescriptor(VertexAttribute.Normal)
);

// slow
mesh.SetVertexBufferData(verts, 0, 0, numVerts, 0, MeshUpdateFlags.DontValidateIndices);


mesh.SetIndexBufferParams(indices, IndexFormat.UInt16);

// also slow
mesh.SetIndexBufferData(tris, 0, 0, indices, MeshUpdateFlags.DontValidateIndices);

mesh.SetSubMesh(0, new SubMeshDescriptor(0, indices));

If you have any alternatives or if you see any ways I could improve this, I'm all ears!

0 Answers
Related