Wei Xu
Wei Xu

Reputation: 1659

Centre of mass of a random 3D polygon (obj file or stl file)

Currently I have an ArrayList of vertices in a 3-dimensional cartesian coordinates system. The polygon is random. It can be a car, a cup or even a dragon.

Assuming the density does not change, how to calculate the centre of mass (x,y,z) of this 3D object?

I am storing the faces and vertices in ArrayList.

public ArrayList<stlFace> StlFaces = new ArrayList<stlFace>();
public ArrayList<VertexGeometric> VertexList = new ArrayList<VertexGeometric>();

Upvotes: 1

Views: 1291

Answers (1)

Antonio Tomac
Antonio Tomac

Reputation: 532

I was using this for calculating surface which is proportional to mass of each face or triangle. And to calculate center off mass of each triangle and center of mass of whole object I was using this. I added helper methods getCenter() and getSurface() to Face class to encapsulate calculations specific to just one face/triangle.

public static class Vertex {

    public float x = 0;
    public float y = 0;
    public float z = 0;

    public Vertex(float x, float y, float z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}

public static class Face {

    public Vertex v1;
    public Vertex v2;
    public Vertex v3;

    public Face(Vertex v1, Vertex v2, Vertex v3) {
        this.v1 = v1;
        this.v2 = v2;
        this.v3 = v3;
    }

    public Vertex getCenter() {
        Vertex triangleCenter = new Vertex(0, 0, 0);
        triangleCenter.x += v1.x;
        triangleCenter.x += v2.x;
        triangleCenter.x += v3.x;
        triangleCenter.y += v1.y;
        triangleCenter.y += v2.y;
        triangleCenter.y += v3.y;
        triangleCenter.z += v1.z;
        triangleCenter.z += v2.z;
        triangleCenter.z += v3.z;
        triangleCenter.x /= 3;
        triangleCenter.y /= 3;
        triangleCenter.z /= 3;
        return triangleCenter;
    }

    public float getSurface() {
        float x1 = v1.x - v2.x;
        float x2 = v1.y - v2.y;
        float x3 = v1.z - v2.z;
        float y1 = v1.x - v3.x;
        float y2 = v1.y - v3.y;
        float y3 = v1.z - v3.z;
        return (float) Math.sqrt(
                Math.pow(x2 * y3 - x3 * y2, 2) + 
                Math.pow(x3 * y1 - x1 * y3, 2) + 
                Math.pow(x1 * y2 - x2 * y1, 2)
            ) / 2f;
    }
}

public static Vertex calculateMassCenter(List<Face> faces) {
    Vertex massCenter = new Vertex(0, 0, 0);
    float mass = 0;
    for (Face face : faces) {
        Vertex triangleCenter = face.getCenter();
        float faceMass = face.getSurface();
        mass += faceMass;
        massCenter.x += faceMass * triangleCenter.x;
        massCenter.y += faceMass * triangleCenter.y;
        massCenter.z += faceMass * triangleCenter.z;
    }
    massCenter.x /= mass;
    massCenter.y /= mass;
    massCenter.z /= mass;
    return massCenter;
}

Upvotes: 1

Related Questions