nicklockwood/Euclid

Is there a way to calculate the enclosed volume of a mesh?

Opened this issue · 6 comments

Is there a way to calculate the enclosed volume of a mesh?

From what I can understand, the bounding volume (aka "size") is determined by the 2 most outer diagonal corners of the mesh and a square volume is calculated.

Yes, the size is the rectangular bounding volume, so it will be an overestimate in most cases

So here is the pseudo-code for how the volume of enclosed meshes can be found using Swift. But RealityKit does not give access to the array of vertices and indices. Is this possible with Euclid? Just wanted your opinion before I start delving into how to gain access to this info.

func signedVolumeOfTriangle(p1: SIMD3<Float>, p2: SIMD3<Float>, p3: SIMD3<Float>) -> Float {
    let v321 = p3.x * p2.y * p1.z
    let v231 = p2.x * p3.y * p1.z
    let v312 = p3.x * p1.y * p2.z
    let v132 = p1.x * p3.y * p2.z
    let v213 = p2.x * p1.y * p3.z
    let v123 = p1.x * p2.y * p3.z
    return (1.0 / 6.0) * (-v321 + v231 + v312 - v132 - v213 + v123)
}

func volumeOfMesh(mesh: MeshResource) -> Float {
    var volume: Float = 0.0
    
    let vertices = mesh.positions // Realitykit doesn't now allow access to this array
    let indices = mesh.indices // Or this one
    
    for i in stride(from: 0, to: indices.count, by: 3) {
        let p1 = vertices[Int(indices[i])]
        let p2 = vertices[Int(indices[i + 1])]
        let p3 = vertices[Int(indices[i + 2])]
        volume += signedVolumeOfTriangle(p1: p1, p2: p2, p3: p3)
    }

Yes, Euclid trivially gives you this info - each Mesh has an array of polygons, and each polygon has an array of vertices. If you need triangles instead, there is a mesh.triangulate() method

Great. I'm going to try to figure this out. I can submit a pull request once I'm done if you would like this feature.

That would be very much appreciated - thank you!