Home > other >  Loading texture causes access violation
Loading texture causes access violation

Time:01-22

I'm trying to load a height map into my program and it causes an access violation error and I don't know why.

    unsigned int texture;
    glGenTextures(1, &texture);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture); 
    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_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    int width, height, nr_channels;
    unsigned char *height_map = stbi_load("textures/noise.jpg", &width, &height, &nr_channels, 0);
    if (height_map)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, height_map);
        glGenerateMipmap(GL_TEXTURE_2D);

        set_int(shader_program, "height_map", 0);
        printf("Loaded a height map that's %i in width and %i in height", width, height);
    }
    else
    {
        printf("Failed to load texture");
    }
    stbi_image_free(height_map);

CodePudding user response:

You cannot assume that the texture has 4 channels. nr_channels is an integral output parameter like width and height. It tells you how many channels the texture image actually has. The returned value is 1, 2, 3 or 4. So if nr_channels is equal to 1, the texture has 1 channel and you have to use the GL_RED format. 3 means GL_RGB and 4 means GL_RGBA. The last parameter of "stbi_load" is an input parameter that allows you to force the desired number of channels. Pass 4 to the las argument to get a texture image with 4 color channels (GL_RGBA):

unsigned char *height_map = stbi_load("textures/noise.jpg", &width, &height, &nr_channels, 0);

unsigned char *height_map = stbi_load("textures/noise.jpg",
                                      &width, &height, &nr_channels, 4);

CodePudding user response:

Changing nr_channels from GL_RGBA to GL_RED fixes this.

  • Related