Search code examples
c++openglshadertextures

OpenGL texture black in fragment shader


When attempting to use a texture in a fragment shader, the texture is just all black. I feel like there is something missing, but everything I've looked at seems ok. Here's my code for using the texture:

GLuint shaderProg = compileShaderPair(vsource, fsource);
GLint texSampler = glGetUniformLocation(shaderProg, "tex");
glUniform1i(texSampler, 0);
glUseProgram(shaderProg);
...
GLuint tex;
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
int width, height, components;
unsigned char* img = stbi_load("texture.jpg", &width, &height, &components, 3);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img);
glGenerateMipmap(GL_TEXTURE_2D);

Vertex Shader:

#version 330
in vec3 pos;
in vec2 uv;
out vec2 texcoord;
void main() {
    texcoord = uv;
    gl_Position = vec4(pos, 1.0)
}

Fragment shader:

#version 330
in vec2 texcoord;
out vec4 outColor;
uniform sampler2D tex;
void main() {
    outColor = vec4(texture(tex, texcoord).rgb, 1.0);
}

I have verified that the texture is loading, and that the texture coordinates are fine.

EDIT: It works fine when debugging it in RenderDoc, but when running by itself, it does not work.


Solution

  • Oops! I forgot Visual Studio messes with the working directory when debugging, and stb_image wasn't throwing any errors while trying to load the image. Running it outside of Visual Studio, it works fine.