0

Can I calculate normals given vertices and indices? Can't figure out the code. Any help appreciated.

Edit: Could be it as simple as?:

function calculateVertexNormal(vertices:Array<Vector3>) {
        var vertNormal:Array<Vector3> = [];

        for(i in 0...vertices.length){
            var v0 = vertices[i];
            vertNormal.push(new Vector3(v0.x, v0.y, v0.z).normalized());
        }
        return vertNormal;
    }

Edit 2: Trying like this, with no luck

function calculateVertexNormal(vertices:Array<Vector3>) {
        var i = 0;

        while(i<indices.length){
            var A = vertices[indices[i]];
            var B = vertices[indices[i+1]];
            var C = vertices[indices[i+2]];

            var v1 = new Vec3().subvecs(A,B);
            var v2 = new Vec3().subvecs(A,C);
            var norm = new Vec3().crossvecs(v1, v2);

            normals.push(norm.x);
            normals.push(norm.y);
            normals.push(norm.z);

            i+=3;
        }
    }
Janis Taranda
  • 496
  • 5
  • 19
  • It could be that simple, but only if you know in advance that your object is a sphere centered at the origin. For most other objects, the direction the normal points has no particular relationship to the direction from the origin to the vertex, which is what you're calculating in this code. Generally we want to note which faces each vertex touches, compute the two edges of each face and cross them to get a face normal, and average the face normals around a vertex to get the smoothed vertex normal, as explained at the linked duplicate Q&A. – DMGregory Jan 26 '20 at 13:02
  • Can't decode that pseudo-code :( – Janis Taranda Jan 26 '20 at 13:36
  • 1
    I've added a new answer at the linked duplicate question to show the averaging of face normals to make vertex normals in more detail. – DMGregory Jan 26 '20 at 15:15

0 Answers0