nicklockwood / Euclid

A Swift library for creating and manipulating 3D geometry
MIT License
644 stars 53 forks source link

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

Open Tony-j77 opened 4 months ago

Tony-j77 commented 4 months ago

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.

nicklockwood commented 4 months ago

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

Tony-j77 commented 4 months ago

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)
    }
nicklockwood commented 4 months ago

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

Tony-j77 commented 4 months ago

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.

nicklockwood commented 4 months ago

That would be very much appreciated - thank you!