Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Precalculate model's bounding box (by its vertices + bone transforms)
- /// - inspired by http://dzindzinovic.blogspot.com/2010/05/xna-get-model-vertices-for-boundingbox.html
- /// - BoundingBox can be also loaded by custom Content Pipeline processor (ModelBoundingBoxProcessor)
- /// </summary>
- public static BoundingBox GetBoundingBox(Model model, Matrix[] boneTransforms)
- {
- Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
- Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
- model.CopyAbsoluteBoneTransformsTo(boneTransforms);
- List<Vector3> vertices = new List<Vector3>();
- foreach (ModelMesh mesh in model.Meshes)
- {
- // Get the transform of the current mesh
- Matrix transform = boneTransforms[mesh.ParentBone.Index];
- foreach (ModelMeshPart part in mesh.MeshParts)
- {
- // Get the current mesh info
- int stride = part.VertexBuffer.VertexDeclaration.VertexStride;
- int numVertices = part.NumVertices;
- byte[] verticesData = new byte[stride * numVertices];
- part.VertexBuffer.GetData<byte>(verticesData);
- for (int i = 0; i < verticesData.Length; i += stride)
- {
- float x = BitConverter.ToSingle(verticesData, i);
- float y = BitConverter.ToSingle(verticesData, i + sizeof(float));
- float z = BitConverter.ToSingle(verticesData, i + 2 * sizeof(float));
- // Apply transform to the current point
- Vector3 vector = new Vector3(x, y, z);
- vector = Vector3.Transform(vector, transform);
- vertices.Add(vector);
- if (vector.X < min.X) min.X = vector.X;
- if (vector.Y < min.Y) min.Y = vector.Y;
- if (vector.Z < min.Z) min.Z = vector.Z;
- if (vector.X > max.X) max.X = vector.X;
- if (vector.Y > max.Y) max.Y = vector.Y;
- if (vector.Z > max.Z) max.Z = vector.Z;
- }
- }
- }
- return new BoundingBox(min, max);
- }
Advertisement
Add Comment
Please, Sign In to add comment