Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static TriangleMesh FromModel(Model model)
- {
- var triangleMesh = new TriangleMesh();
- foreach (var modelMesh in model.Meshes)
- {
- // Get bone transformation.
- Matrix transform = GetAbsoluteTransform(modelMesh.ParentBone);
- foreach (var modelMeshPart in modelMesh.MeshParts)
- {
- // Get vertex element info.
- var vertexDeclaration = modelMeshPart.VertexBuffer.VertexDeclaration;
- var vertexElements = vertexDeclaration.GetVertexElements();
- // Get the vertex positions.
- var positionElement = vertexElements.First(e => e.VertexElementUsage == VertexElementUsage.Position);
- if (positionElement.VertexElementFormat != VertexElementFormat.Vector3)
- throw new NotSupportedException("For vertex positions only VertexElementFormat.Vector3 is supported.");
- var positions = new Vector3[modelMeshPart.NumVertices];
- modelMeshPart.VertexBuffer.GetData(
- modelMeshPart.VertexOffset * vertexDeclaration.VertexStride + positionElement.Offset,
- positions,
- 0,
- modelMeshPart.NumVertices,
- vertexDeclaration.VertexStride);
- // Apply bone transformation.
- for (int i = 0; i < positions.Length; i++)
- positions[i] = Vector3.Transform(positions[i], transform);
- // Get indices.
- var indexElementSize = (modelMeshPart.IndexBuffer.IndexElementSize == IndexElementSize.SixteenBits) ? 2 : 4;
- if (indexElementSize != 2)
- throw new NotSupportedException("Only 16 bit indices are supported.");
- var indices = new short[modelMeshPart.PrimitiveCount * 3];
- modelMeshPart.IndexBuffer.GetData(
- modelMeshPart.StartIndex * 2,
- indices,
- 0,
- modelMeshPart.PrimitiveCount * 3);
- // Remember the number of vertices already in the mesh.
- int vertexCount = triangleMesh.Vertices.Count;
- // Add the vertices of the current modelMeshPart.
- foreach (var p in positions)
- triangleMesh.Vertices.Add((Vector3F)p);
- // Add indices to triangle mesh.
- for (int i = 0; i < modelMeshPart.PrimitiveCount; i++)
- {
- // The three indices of the next triangle.
- // We add 'vertexCount' because the triangleMesh already contains other mesh parts.
- var i0 = indices[i * 3 + 0] + vertexCount;
- var i1 = indices[i * 3 + 1] + vertexCount;
- var i2 = indices[i * 3 + 2] + vertexCount;
- triangleMesh.Indices.Add(i0);
- triangleMesh.Indices.Add(i2); // DigitalRune Geometry uses other winding order!
- triangleMesh.Indices.Add(i1);
- }
- }
- }
- return triangleMesh;
- }
- private static Matrix GetAbsoluteTransform(ModelBone bone)
- {
- if (bone == null)
- return Matrix.Identity;
- return bone.Transform * GetAbsoluteTransform(bone.Parent);
- }
Advertisement
Add Comment
Please, Sign In to add comment