Fast way to build a mesh

Hi,

we have a grasshopper component that builds meshes from arrays of integers and floats and we always have to go through the Mesh.Vertices.Add() and similar. This method is awfully slow

var mesh = new Mesh();

var faces = new List<MeshFace>();
for (int i = 0; i < tris.Length; i += 3) {
  mesh.Faces.AddFace(tris[i + 0], tris[i + 1], tris[i + 2]);
}

for (int i = 0; i < verts.Length; i += 3) {
  mesh.Vertices.Add(verts[i + 0], verts[i + 1], verts[i + 2]);
}

For a 2M verts/4M faces mesh it takes almost 600ms, while converting from mesh to int[] and float[] takes 20ms using ToFloatArray()and ToIntArray(bool)

Is there a faster way to build meshes?

Thanks
Alberto

Mesh.Vertices.AddVertices is usually faster than a large loop. And depending on the case, Mesh.Faces.AddFaces can be quite performant.

I tried using those and got worse performance actually. I saw that that is still not directly calling the underlying C++ code but rather looping through the given faces/vertices and calling the C++ for each face/vert

Alberto

Assuming you do this in RhinoCommon, by far the fastest way would be to create the mesh with the right size, assigning count and then using the unsafe access as here:

This is because https://developer.rhino3d.com/api/rhinocommon/rhino.geometry.meshunsafelock gives access to the underlying mesh data structures as pinned pointers.

Thanks,

Giulio


Giulio Piacentino
for Robert McNeel & Associates
giulio@mcneel.com

3 Likes

Grazie Giulio! We are doing this in RhinoCommon as it is in a grasshopper component.

1 Like