Hello all. I’m using onBeforeCompile in the vertex shader to manually transform/rotate the vertices and the normal of a double-sided mesh. The only issue is that the backside of the mesh is not flipping the normal correctly, so it’s reflecting light when it shouldn’t. When I try to use gl_FrontFacing in the fragment shader to manually flip the normal then I get an error:
ERROR: 0:1007: 'assign' : l-value required (can't modify an input "vNormal")
Yet I can’t use gl_FrontFacing in the vertex shader. So how do I go about editing the normal inside the fragment shader?
relevant code:
this.material = new MeshPhongMaterial({ side: DoubleSide });
this.material.onBeforeCompile = (shader) => {
const vertexPars = `
attribute vec3 offset;
attribute vec2 rotation;
vec3 rotateVectorByQuaternion(vec3 v, vec4 q){
return 2.0 * cross(q.xyz, v * q.w + cross(q.xyz, v)) + v;
}
`;
const vertexBegin = `
vec3 vPosition = position;
vec4 direction = vec4(0.0, rotation.x, 0.0, rotation.y);
vPosition = rotateVectorByQuaternion(vPosition, direction);
vNormal = rotateVectorByQuaternion(vNormal, direction);
vec3 transformed = vPosition + offset;
`;
const colorFragment = `
// attempting to flip the normal... throws an error
if(gl_FrontFacing){
vNormal = normalize(vNormal);
}else{
vNormal = normalize(-vNormal);
}
diffuseColor = vec4(1.0, 0.0, 0.0, 1.0);
`;
shader.vertexShader = (vertexPars + shader.vertexShader).replace('#include <begin_vertex>', vertexBegin);
shader.fragmentShader = shader.fragmentShader.replace('#include <color_fragment>', colorFragment)
this.material.userData.shader = shader;
};