opengl - 简单的 GLSL 聚光灯着色器

标签 opengl graphics glsl shader

我需要一个简单的聚光灯着色器的帮助。
圆锥内的所有顶点都应为黄色,圆锥外的所有顶点都应为黑色。
我只是无法让它工作。我认为这与从世界到眼睛坐标的转换有关。

顶点着色器:

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)   
}

片段着色器:
void main(void)
{
   gl_FragColor = gl_Color;
}

编辑:
蒂姆是对的。此
if(angle > radians(spotCutoff))

应该是:
if(acos(angle) < radians(spotCutoff))

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

最佳答案

(让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

关于opengl - 简单的 GLSL 聚光灯着色器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10628538/

相关文章:

python - Visual Python - 可视化与运动相关的图表

glsl - 平滑低倍频程柏林噪声

opengl - 非 GLSL OpenGL 应用程序中的 GPU 使用

opengl-es - 如何创建一个着色器以使用距中心点的度数偏移进行 mask ?

c++ - SDL2 OpenGL 窗口立即关闭

c++ - 修复了 VSync 打开时的时间步长卡顿

java - 分层边框——这在 Java Swing 中是否可行?

c - 辅助线程中的 Opengl 渲染(纹理)

OpenGL 从当前绑定(bind)到帧缓冲区的纹理单元读取

javascript - 如何创建水平条形堆叠并以不同方式对齐标签