简单的GLSL Spotlight Shader

Bas*_*sti 4 opengl graphics shader glsl

我需要一个简单的聚光灯着色器的帮助.锥体内的所有顶点应为黄色,锥体外的所有顶点应为黑色.我无法让它发挥作用.我认为它与从世界到眼睛坐标的转换有关.

顶点着色器:

uniform vec4  lightPositionOC;   // in object coordinates
uniform vec3  spotDirectionOC;   // in object coordinates
uniform float spotCutoff;        // in degrees

void main(void)
{
   vec3 lightPosition;
   vec3 spotDirection;
   vec3 lightDirection;
   float angle;

    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

    // Transforms light position and direction into eye coordinates
    lightPosition  = (lightPositionOC * gl_ModelViewMatrix).xyz;
    spotDirection  = normalize(spotDirectionOC * gl_NormalMatrix);

    // Calculates the light vector (vector from light position to vertex)
    vec4 vertex = gl_ModelViewMatrix * gl_Vertex;
    lightDirection = normalize(vertex.xyz - lightPosition.xyz);

    // Calculates the angle between the spot light direction vector and the light vector
    angle = dot( normalize(spotDirection),
                -normalize(lightDirection));
    angle = max(angle,0);   

   // Test whether vertex is located in the cone
   if(angle > radians(spotCutoff))
       gl_FrontColor = vec4(1,1,0,1); // lit (yellow)
   else
       gl_FrontColor = vec4(0,0,0,1); // unlit(black)   
}
Run Code Online (Sandbox Code Playgroud)

片段着色器:

void main(void)
{
   gl_FragColor = gl_Color;
}
Run Code Online (Sandbox Code Playgroud)

编辑:
蒂姆是对的.这个

if(angle > radians(spotCutoff))
Run Code Online (Sandbox Code Playgroud)

应该:

if(acos(angle) < radians(spotCutoff))
Run Code Online (Sandbox Code Playgroud)

新问题:
灯光似乎没有停留在场景中的固定位置,而是当我向前或向后移动时,它似乎相对于我的相机移动,因为锥体变小或变大.

Tim*_*Tim 5

(让spotDirection为向量A,lightDirection为向量B)

你在分配;

angle = dot(A,B)

公式不应该是:

cos(angle) = dot(A,B)

要么

angle = arccos(dot(A,B))

http://en.wikipedia.org/wiki/Dot_product#Geometric_interpretation

  • @Basti如果您有其他问题,为了将来参考,您应该考虑发布单独的问题.此问题已标记为已解决,很可能很少关注帖子底部的编辑.话虽如此,我没有足够的信息来了解答案.如果你真的是在对象坐标中定义你的灯光位置,而不是移动物体,那么我不希望看到灯光发生变化,所以可能出现了一些错误,上面没有显示.尝试制作一个新帖子,其中包含描述问题的图片链接. (2认同)