RalleYTN
RalleYTN

Reputation: 138

Problem with calculating the bounding box of a 3D object with transformation

So I have a really weird behavior for my bounding boxes. Everytime I translate an object with any value being negative the bounding box gets stretched to the 0 point.

Here is how it looks with a positive translation: enter image description here

Everything is fine. But now I translate it with a negative Z coordinate. enter image description here

Here is my code for creating the bounding box:

private final void calcBoundingBox() {

    if(this.mesh != null) {

        float[] vertices = this.mesh.getVertexArray().getBuffer(0).getDataAsFloats();

        float xn = Float.MAX_VALUE;
        float yn = xn;
        float zn = xn;

        float xf = Float.MIN_VALUE;
        float yf = xf;
        float zf = xf;

        for(int index = 0; index < vertices.length; index += 3) {

            Vector3f vertex = MatrixUtil.multiply(this.transformation, vertices[index], vertices[index + 1], vertices[index + 2]);

            float x = vertex.x;
            float y = vertex.y;
            float z = vertex.z;

            if(x < xn) xn = x; else if(x > xf) xf = x;
            if(y < yn) yn = y; else if(y > yf) yf = y;
            if(z < zn) zn = z; else if(z > zf) zf = z;
        }

        float width = xf - xn;
        float height = yf - yn;
        float depth = zf - zn;

        this.boundingBox.setBounds(xn, yn, zn, width, height, depth);
    }
}

public static final Vector3f multiply(Matrix4f matrix, float x, float y, float z) {

    Vector3f result = new Vector3f();
    result.x = (x * matrix.m00) + (y * matrix.m10) + (z * matrix.m20) + matrix.m30;
    result.y = (x * matrix.m01) + (y * matrix.m11) + (z * matrix.m21) + matrix.m31;
    result.z = (x * matrix.m02) + (y * matrix.m12) + (z * matrix.m22) + matrix.m32;
    return result;
}

My question now is: What did I do wrong?

Upvotes: 1

Views: 1031

Answers (2)

Cyannide
Cyannide

Reputation: 11

There is also an issue with finding the min/max values:

  if(x < xn) xn = x; else if(x > xf) xf = x;
  if(y < yn) yn = y; else if(y > yf) yf = y;
  if(z < zn) zn = z; else if(z > zf) zf = z;

Because of the 'else' conditions, depending on the orientation of the shape, not all bounding boxes are calculated correctly. All six if statements should be checked for all vertices.

Upvotes: 0

meowgoesthedog
meowgoesthedog

Reputation: 15035

Problem: float xf = Float.MIN_VALUE;

This is the smallest positive value that can be represented by a float. You should use -Float.MAX_VALUE instead.

See here for more details.

Upvotes: 3

Related Questions