GLSL spot shader moving with camera

I am trying to create a basic static spotlight using shaders for the LWJGL game, but it seems that the light moves when the camera position is moved and rotated. These shaders are slightly modified from the OpenGL 4.3 manual, so I'm not sure why they do not work properly. Can someone explain why these shaders are not working properly and what can I do to make them work?

Vertex Shader:

varying vec3 color, normal; varying vec4 vertexPos; void main() { color = vec3(0.4); normal = normalize(gl_NormalMatrix * gl_Normal); vertexPos = gl_ModelViewMatrix * gl_Vertex; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } 

Fragment Shader:

 varying vec3 color, normal; varying vec4 vertexPos; void main() { vec3 lightPos = vec3(4.0); vec3 lightColor = vec3(0.75); vec3 lightDir = lightPos - vertexPos.xyz; float lightDist = length(lightDir); float attenuation = 1.0 / (3.0 + 0.007 * lightDist + 0.000008 * lightDist * lightDist); float diffuse = max(0.0, dot(normal, lightDir)); vec3 ambient = vec3(0.4, 0.4, 0.4); vec3 finalColor = color * (ambient + lightColor * diffuse * attenuation); gl_FragColor = vec4(finalColor, 1.0); } 
+1
source share
2 answers

If anyone is interested, I found a solution. Removing calls to gl_NormalMatrix and gl_ModelViewMatrix solved the problem.

+2
source

The critical value here, lightPos, was set as the vertexPos function that you expressed in screen space (this was because its original shape of the world space was multiplied by modelView). The screen space remains in the camera, not in the 3D world. Therefore, in order to have a fixed light source relative to some absolute point in world space (for example, [4.0, 4.0, 4.0]), you could simply leave your objects in this space, as you know.

But getting rid of modelview is not a good idea, since the whole point of the model matrix is ​​to put your objects where they belong (so that you can reuse your vertex arrays with changes only to the model matrix, and not burden them with specifying all vertex vertices from scratch).

It is best to multiply modelView on both vertices and lightPos. Thus, you treat lightPos, as originally, a quantity in world space, but then perform a comparison in screen space. Mathematics to get the light intensity from the normals will work the same in any space, and you will get the right light source.

0
source

Source: https://habr.com/ru/post/1412894/


All Articles