Max Roncace
Max Roncace

Reputation: 1262

Averaging normals results in zero-length vector

I have four normals which I am attempting to average by adding the x, y, and z values, then normalizing the result. However, when I add the different axis values, the resulting vector has a length of zero. I get the feeling that this issue is very easily solved, but I'm relatively new to OpenGL, and don't know vectors in and out yet.

Code for getting the face and vertex normals, respectively.

public Vector3f getNormal(Vector3f p1, Vector3f p2, Vector3f p3){
        Vector3f v = new Vector3f();

        Vector3f calU = new Vector3f(p2.x - p1.x, p2.y - p1.y, p2.z - p1.z);
        Vector3f calV = new Vector3f(p3.x - p1.x, p3.y - p1.y, p3.z - p1.z);

        v.setX(calU.getY() * calV.getZ() - calU.getZ() * calV.getY());
        v.setY(calU.getZ() * calV.getX() - calU.getX() * calV.getZ());
        v.setZ(calU.getX() * calV.getY() - calU.getY() * calV.getX());

        return (Vector3f)v.normalise();
    }

    public Vector3f getVectorNormal(Vector3f p){
        Vector3f t1 = getNormal(p, new Vector3f(p.getX() - 1, p.getY(), p.getZ()), new Vector3f(p.getX(), p.getY(), p.getZ() - 1));
        Vector3f t2 = getNormal(p, new Vector3f(p.getX() + 1, p.getY(), p.getZ()), new Vector3f(p.getX(), p.getY(), p.getZ() - 1));
        Vector3f t3 = getNormal(p, new Vector3f(p.getX() + 1, p.getY(), p.getZ()), new Vector3f(p.getX(), p.getY(), p.getZ() + 1));
        Vector3f t4 = getNormal(p, new Vector3f(p.getX() - 1, p.getY(), p.getZ()), new Vector3f(p.getX(), p.getY(), p.getZ() + 1));

        float x = t1.getX() + t2.getX() + t3.getX() + t4.getX();
        float y = t1.getY() + t2.getY() + t3.getY() + t4.getY();
        float z = t1.getZ() + t2.getZ() + t3.getZ() + t4.getZ();

        Vector3f v = new Vector3f(x, y, z);

        return (Vector3f)v.normalise();
    }

Upvotes: 1

Views: 306

Answers (1)

datenwolf
datenwolf

Reputation: 162164

This doesn't make sense

    Vector3f t1 = getNormal(p, new Vector3f(p.getX() - 1, p.getY(), p.getZ()), new Vector3f(p.getX(), p.getY(), p.getZ() - 1));
    Vector3f t2 = getNormal(p, new Vector3f(p.getX() + 1, p.getY(), p.getZ()), new Vector3f(p.getX(), p.getY(), p.getZ() - 1));
    Vector3f t3 = getNormal(p, new Vector3f(p.getX() + 1, p.getY(), p.getZ()), new Vector3f(p.getX(), p.getY(), p.getZ() + 1));
    Vector3f t4 = getNormal(p, new Vector3f(p.getX() - 1, p.getY(), p.getZ()), new Vector3f(p.getX(), p.getY(), p.getZ() + 1));

You can't extract a normal from a single point. Whatever you're adding and subtracting there, this is not what you're supposed to do.

UPDATE

I think you're mostly strugling with linear algebra basics here. This is not really OpenGL specific. This is math. I can't give you better advice than grabbing some good textbook on the topic and, well, learn it.

Upvotes: 1

Related Questions