c++ - glsl 顶点着色器 glGetUniformLocation 失败

标签 c++ opengl glsl vertex-shader uniform

我想在我的顶点着色器中设置一个统一的 vector 。

int loc = glGetUniformLocation(shader, "LightPos");
if (loc != -1)
{
    //do Stuff
}

问题是 loc 一直是 -1。我用 Fragment Shader 中的变量进行了尝试,它确实有效。顶点着色器:

uniform vec3 LightPos;
varying vec2 UVCoord;
varying float LightIntensity;

void main()
{           
    UVCoord = gl_MultiTexCoord0.st;
    gl_Position = ftransform();
    vec3 Normal = normalize(gl_NormalMatrix * gl_Normal);
    LightIntensity = max(dot(normalize(vec3(0, -10, 0)), Normal), 0.0);
}

片段着色器:

uniform sampler2D tex1;
varying vec2 UVCoord;
varying float LightIntensity;

void main()
{
    vec3 Color = vec3(texture2D(tex1, UVCoord));
    gl_FragColor = vec4(Color * LightIntensity, 1.0);
}

有人知道我做错了什么吗?

最佳答案

不幸的是,您误解了一般情况下 glGetUniformLocation (...) 和统一位置分配的工作原理。

位置仅在您的着色器编译和链接后分配。这是一个两阶段操作,可有效识别 GLSL 程序所有阶段(顶点、片段、几何、曲面 segmentation )之间使用 输入和输出。因为 LightPos 没有在您的顶点着色器中使用(或与此相关的任何其他地方),所以当您的程序被链接时,它没有被分配一个位置。它只是不复存在。

这就是术语active uniform 的来源。而 glGetUniformLocation (...) 只返回事件 uniform 的位置。


Name

glGetUniformLocation — Returns the location of a uniform variable

[...]

描述

glGetUniformLocation returns an integer that represents the location of a specific uniform variable within a program object. name must be a null terminated string that contains no white space. name must be an active uniform variable name in program that is not a structure, an array of structures, or a subcomponent of a vector or a matrix. This function returns -1 if name does not correspond to an active uniform variable in program, if name starts with the reserved prefix "gl_", or if name is associated with an atomic counter or a named uniform block.

关于c++ - glsl 顶点着色器 glGetUniformLocation 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20751157/

相关文章:

C++ 多线程和 vector

c++ - 初始化非指针类成员

c++ - 多维数组函数输出垃圾?

c++ - GL_QUADS 的 Opengl 纹理映射,得到奇怪的结果

c++ - Opengl 通过使用顶点缓冲对象

javascript - 如何使用 WebGL 和 GLSL 在 J/s 文件中运行 Shadertoy 的着色器?

c++ - glsl 错误 : "v_color" not declared as an output from the previous stage while trying to render wtih tesselation shaders

c++ - 可以多次链接信号和插槽吗?

java - libgdx 透明覆盖

LibGDX - 使用着色器将纹理覆盖在另一个纹理之上