0
votes

I am having a problem with some simple vertex point light in a glsl shader.

I am still confused by what coordinate space to do the lighting in.

Right now I am transforming the position by the modelview and the normal by the upper 3x3 modelview(no translation). I am also transforming the lightposition by the view matrix to get it into the same space.

The problem is the light position moves when the camera moves.

void main()  {
attribute vec4 position;
attribute vec3 normal;
attribute vec2 texcoord0;

varying vec4 colorVarying;
varying vec2 texOut0;

uniform mat4 Projection;
uniform mat4 Modelview;
uniform mat3 NormalMatrix;//this is the upper 3x3 of the modelview
uniform vec3 LightPosition; //already transformed by view matrix

vec3 N = NormalMatrix * normal;
vec4 P = Modelview * position;  //no view    
vec3 L = normalize(LightPosition - P.xyz);
float df = max(0.0, dot(N, L.xyz));
vec3 final_color = AmbientMaterial + df * DiffuseMaterial;
colorVarying = vec4(final_color,1);
gl_Position = Projection * Modelview * position;
}

I figured out my error - I am using es 2.0 and was sending my normal matrix via

glUniformMatrix3fv(gVertexLightingShader->Uniforms[UNIFORM_NORMALMATRIX], 1, 0, m_modelview.data());

But m_modelview was a 4x4 matrix - so the normal matrix was not correct.

1
Could you please show the code with which you calculate Modelview matrix and do the transformation for LightPosition? Something in your transformation setup seems not to be right.datenwolf
Do you really use just the upper left 3×3 modelview as normal matrix. Technically this might work, as long this is made sure to be orthonormal; otherwise you need to use the inverse transpose of the modelview.datenwolf

1 Answers

0
votes

As @datenwolf said, the way you calculate the normal matrix will only work if it's orhtonormal, that is, it doesn't contain roations or scaling.

This is the way to solve this issue:

var normalMatrix = mat3.create();
mat4.toInverseMat3(mvMatrix, normalMatrix);
normalMatrix = mat3.toMat4(normalMatrix);
mat4.transpose(normalMatrix);