Home > Net >  How to get smooth shading with bufferGeometry in three js?
How to get smooth shading with bufferGeometry in three js?

Time:10-07

I am making a cube sphere with LOD, and I ran into a little problem the normal that I was generating is by this code block.

// VectorVertices is an array of Vector3
let VectorNormals = new Array(this.VectorVertices.length);

for (let i = 0; i < VectorNormals.length; i  ) {
    VectorNormals[i] = new THREE.Vector3();    
}

for (let i = 0; i < this.Triangles.length; i  = 3) {
    let vertexIndexA = this.Triangles[i];
    let vertexIndexB = this.Triangles[i   1];
    let vertexIndexC = this.Triangles[i   2];

    let pointA = this.VectorVertices[vertexIndexA];
    let pointB = this.VectorVertices[vertexIndexB];
    let pointC = this.VectorVertices[vertexIndexC];

    pointB.sub(pointA);
    pointC.sub(pointA);
    let vertexNormal = new THREE.Vector3().crossVectors(pointB, pointC).normalize();

    VectorNormals[vertexIndexA].add(vertexNormal);
    VectorNormals[vertexIndexB].add(vertexNormal);
    VectorNormals[vertexIndexC].add(vertexNormal);
}

for (let i = 0; i < VectorNormals.length; i  ) {
    VectorNormals[i].normalize();
    this.Normals.push(VectorNormals[i].x, VectorNormals[i].y, VectorNormals[i].z);
}

The this.Normals is then set to a bufferGeometry. I am creating the mesh with MeshPhongMaterial.

The normals between the neighbouring faces weren't calculated properly, and I don't what's going wrong. I apologize for my grammar. Thanks!

EDIT: Showing my image problem This is the result I am getting

CodePudding user response:

You're trying to make a smooth sphere, but you are assigning all of the normals of a triangle to the value of the face normal, which is what you're calculating by subtracting and crossing the vertex values. (Note: You may need to be careful regarding the direction of the crossed vector! Ensure it's pointing in the same direction as your original vertex vectors!)

To make a smooth surface, the normals of adjoining vetices need to be the same. So if you have two triangles:

A -- C
|  / |
| /  |
B -- D

Then to make the transition from ABC to DCB a smooth one, the normals at B and C must be the same. In the case of a sphere, they should also be the average of all surrounding face normals, which ensures a smooth transition in all directions.

Actually for a sphere, if the vertices all originate from the geometric origin, then all you have to do is normalize the vertex value, and that is the normal for that vertex.

  • Related