Search code examples
c++openglglslshadervertex-shader

uniform sampler2D in Vertex Shader


I tried to realize height map with GLSL. For it, i need to sent my picture to VertexShader and get grey component.

glActiveTexture(GL_TEXTURE0);
Texture.bind();

glUniform1i(mShader.getUniformLocation("heightmap"), 0);

mShader.getUniformLocation uses glGetUniformLocation and work good for other uniforms values, that used in Fragment, Vertex Shaders. But for heightmap return -1...

VertexShader code:

#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec4 color;
layout (location = 2) in vec2 texCoords;
layout (location = 3) in vec3 normal;

out vec3 Normal;
out vec3 FragPos;
out vec2 TexCoords;
out vec4 ourColor;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

uniform sampler2D heightmap;

void main()
{
    float bias = 0.25;
    float h = 0.0;
    float scale = 5.0;

       h = scale * ((texture2D(heightmap, texCoords).r) - bias);
        vec3 hnormal = vec3(normal.x*h, normal.y*h, normal.z*h);
        vec3 position1 = position * hnormal;
       gl_Position = projection * view *  model * vec4(position1, 1.0f);


    FragPos = vec3(model * vec4(position, 1.0f));
    Normal = mat3(transpose(inverse(model))) * normal;
    ourColor = color;
    TexCoords = texCoords;
}

may be algorithm of getting height is bad, but error with getting uniformlocation stops my work.. What is wrong? Any ideas?

UPD: texCoords (not TexCoords) of course is using in

h = scale * ((texture2D(heightmap, texCoords).r) - bias);

my mistake, but it doesn't solve the problem. Having same error..


Solution

  • My bet is your variable has been optimized out by driver or the shader did not compile/link properly. After trying to compile your shader (on my nVidia) I got this in the logs:

    0(9) : warning C7050: "TexCoords" might be used before being initialized
    

    You should always check the GLSL compile/link logs ? see

    especially how the glGetShaderInfoLog is used.

    In line

    h = scale * ((texture2D(heightmap, TexCoords).r) - bias);
    

    You are using TexCoords which is output variable and not yet set so the behavior is undefined and most likely your gfx driver throw that line away (and may be others) removing the TexCoords from shader completely but that is just my assumption.


    What driver and gfx card you got?
    What returns the logs on your setup?