Search code examples
copengltexturesopengl-4

texture appears to be reading off uninitialized memory


I create a texture like this:

GLuint tex;
unsigned char data[12] = {255, 255, 255,
                          255, 255, 255,
                          255, 255, 255,
                          255, 255, 255};

glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

I get the location of it:

GLuint texloc = glGetUniformLocation(program, "tex_map");

and then inside my drawing loop I have:

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glUniform1i(texloc, 0);

and then inside my fragment shader I have:

out vec3 color;

uniform sampler2D tex_map;

void  main()
{
    .
    .

    color = texture(tex_map, vec2(-0.1, -0.5));

}

And sometimes when I run the program the object I am drawing becomes a random non white color, often red. I thought I had handled the out of bound case by using GL_CLAMP_TO_EDGE. What is causing this behavior?

EDIT: this behavior also occurs when both values inside vec2(_, _) are inside the range of 0-1...


Solution

  • Try adding

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    

    The default alignment is 4 bytes but your data array is assuming tight packing.