Texture display dislocation?

Hello!

So I am drawing a full screen rect and displaying textures - when I encountered this:

This is the image in its correct form:

switch_1

So something is definitely wrong here. It’s also weird, because my code can display some JPEG images well:

I really am out of ideas at this point. Here’s my code to load images:

void App::load_textures(std::string path, bool append) {
    if (!append) {
        for (auto p = textures_.begin(); p != textures_.end(); p++) {
            p->second.destroy();
        }
        textures_.clear();
        texture_list_.clear();
        showing_image_index_ = -1;
    }
    if (texture_list_raw_) {
        delete texture_list_raw_;
        texture_list_raw_ = nullptr;
    }
    namespace fs = std::filesystem;
    stbi_set_flip_vertically_on_load(true);
    for (auto &p : fs::directory_iterator(path)) {
        std::string path = p.path();
        std::string ext = p.path().extension();
        if (ext != ".jpg" && ext != ".jpeg") {
            continue;
        }
        int w, h, ch;
        unsigned char *data = stbi_load(path.c_str(), &w, &h, &ch, 0);
        if (!data) {
            panic("Failed to load image: " + path, 3);
        }
    
        GLuint tex;
        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);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
    
        std::string file_name = p.path().filename();
        textures_[file_name] = Texture(tex, w, h);
        texture_list_.push_back(file_name);
        showing_image_index_ = (int) texture_list_.size() - 1;
    
        stbi_image_free(data);
        O();
    }

    texture_list_raw_ = new const char *[texture_list_.size()];
    for (int i = 0; i < texture_list_.size(); i++) {
        texture_list_raw_[i] = texture_list_[i].c_str();
    }
}

And here’s my code to display an image:

glViewport(0, 0, framebuffer_width, framebuffer_height);
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(rect_vao);
program_.use();
if (showing_image_index_ >= 0) {
    program_.image("image", last_pass->get_texture()); // last_pass is just a framebuffer
}
glDrawArrays(GL_TRIANGLES, 0, 6);

This is really weird, because some textures work just fine while some others are dislocated. I will be so grateful if someone could help me solve this issue. Huge thanks in advance!

Try adding this before uploading texel data to your textures:

glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );

For details, see:

1 Like