随机3D多边形(obj文件或stl文件)的质心

时间:2015-01-06 10:30:08

标签: java 3d java-3d wavefront stl-format

目前,我在三维笛卡尔坐标系中有一个顶点ArrayList。多边形是随机的。它可以是汽车,杯子甚至是龙。

假设密度没有变化,如何计算这个3D物体的质心(x,y,z)?

我将面和顶点存储在ArrayList中。

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

1 个答案:

答案 0 :(得分:1)

我使用this来计算表面,该表面与每个面或三角形的质量成比例。并且为了计算每个三角形的中心质量和整个物体的质心我使用this。我将辅助方法getCenter()和getSurface()添加到Face类,以封装特定于一个面/三角形的计算。

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;
}