Sharing buffers         Sharing vertex and index buffers across multiple meshes

Many times you have a large mesh made up of vertex and index data that you want to "chunk" into several smaller meshes for use in -LOD or simple frustrum culling. Such as with terrain data. In these cases, you usually want these chunks to index into central vertex and index hardware buffers so that the number of chunks can change without having to reorganize any buffers.

-Meshes are built by referencing in to a VertexData and IndexData structure. Each SubMesh references its own IndexData. VertexData can be linked to a -Mesh through Mesh::sharedVertexData (in which case it will be available for all SubMeshes to use. Just be sure to set SubMesh::useSharedVerticies(true)), or to each SubMesh individually. In the case of chunking terrain, you generally will only have a single SubMesh for each -Mesh, so either method is fine.

Ogre keeps track of each Mesh's VertexData and IndexData. When Ogre shuts down, the meshes still surviving are iterated through, and each one is destroyed. Because of this, it's important that each Mesh's VertexData and IndexData point to unique instances, otherwise Ogre will try to destroy them twice, resulting in a difficult-to-trace error.

The following code snippet (C# Mogre) shows the correct (in that it runs without causing errors) way of creating meshes from shared instances of VertexData and IndexData. This code assumes that VertexData has only a single buffer binding, which is at 0.

MeshPtr CreateMesh(string Name, string Group, IndexData IndexDataArg, VertexData VertexDataArg, AxisAlignedBox BoundingBox)
     Mogre.Mesh -Mesh = Mogre.MeshManager.Singleton.CreateManual(Name, Group);
     SubMesh SubMesh = Mesh.CreateSubMesh();
     //Shallow copy the IndexBuffer argument into the SubMesh's indexData property
     SubMesh.indexData.indexBuffer = IndexDataArg.indexBuffer;
     SubMesh.indexData.indexCount = IndexDataArg.indexCount;
     //Deep copy the VertexData argument into the Mesh's sharedVertexData
     SubMesh.useSharedVertices = true;
     Mesh.sharedVertexData = new VertexData();
     Mesh.sharedVertexData.vertexBufferBinding.SetBinding(0, VertexDataArg.vertexBufferBinding.GetBuffer(0));
     Mesh.sharedVertexData.vertexDeclaration = VertexDataArg.vertexDeclaration.Clone();
     Mesh.sharedVertexData.vertexCount = VertexDataArg.vertexCount;
     return mMesh;