c++openglglslshaderfbo

How can I draw the text attachment of an FBO to the default frame buffer?


I want to use a fragment shader to output to an FBO and then draw its texture attachment to the default framebuffer. Ultimately I want to be able to output to one FBO, then pass it along to another FBO using another shader and so on in a chain. But I figure getting it to work on the default framebuffer is a good first step, especially for debugging the shader's output.

I'm not sure what I'm doing wrong and I've set up a small program to demonstrate it. It's mostly the same code as the complete example on learnopengl.com here: https://learnopengl.com/Getting-started/Textures

The program binds to the FBO, then draws a dot where the cursor is clicked using a shader. If it isn't clicked it draws it to a default location. Then it binds to the default framebuffer and uses another shader (assign.frag.glsl) to draw the FBO's texture attachment.

That's what I want it to do anyway...the problem is I just get a black screen as if either the FBO's texture attachment was never written to or it is somehow not being bound to the uniform sampler2D in the shader. If I comment out the "assignProgram.use();" line then I see the dot where I click with the mouse. This surprised me because the cursor shader's output went to the FBO...yet I'm seeing it in default framebuffer. Even when I commented out "glBindTexture(GL_TEXTURE_2D, tex0);" I can still see the dot.

Here's the vertex shader (the problem occurs even if I leave this out of the program):

#version 330 core
layout (location = 0) in vec3 aPos;

void main()
{
    gl_Position = vec4(aPos, 1.0);
}

Cursor dot shader:

#version 330 core

uniform vec2 cursor;
uniform float rdx;

out vec4 FragColor;

void main()
{

    float distance = distance(cursor, gl_FragCoord.xy) * rdx;
    distance = step(0.02, distance);
    vec3 colour = vec3(distance);

    FragColor = vec4(colour, 1.0f);
}

Assignment shader:

#version 330 core

uniform sampler2D mytexture;
uniform float rdx;

out vec4 FragColor;

void main()
{
    FragColor = texture2D(mytexture, gl_FragCoord.xy);
    FragColor.a = 1.0f;
}

And the C++ code:

#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <learnopengl/shader_s.h>

#include <iostream>

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);

// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 800;

int main()
{
    // glfw: initialize and configure
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    // glfw window creation
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    Shader cursorProgram("default.vert.glsl", "cursor.frag.glsl"); // you can name your shader files however you like
    Shader assignProgram("default.vert.glsl", "assign.frag.glsl"); // you can name your shader files however you like

    float vertices[] = {
       1.f,  1.f, 0.0f,  // top right
        1.f, -1.f, 0.0f,  // bottom right
        -1.f, -1.f, 0.0f,  // bottom left
        -1.f,  1.f, 0.0f,   // top left 
    };

    unsigned int indices[] = {  // note that we start from 0!
        0, 1, 3,   // first triangle
        1, 2, 3    // second triangle
    };

    unsigned int VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO); 

    // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    // position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindVertexArray(0);

    unsigned int tex0, fbo0;

    glGenTextures(1, &tex0);
    glBindTexture(GL_TEXTURE_2D, tex0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glGenFramebuffers(1, &fbo0);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo0);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex0, 0);
    glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
    glClearColor(0.f, 0.f, 0.f, 0.f);
    glClear(GL_COLOR_BUFFER_BIT);
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        std::cout << "uh oh :(" << std::endl;


    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    float rdx = 1.f / SCR_WIDTH;

    while (!glfwWindowShouldClose(window))
    {
        // input
        processInput(window);


        // Draw to FBO
        glBindFramebuffer(GL_FRAMEBUFFER, fbo0);
        GLenum targets[1] = { GL_COLOR_ATTACHMENT0 };
        glDrawBuffers(1, &targets[0]);

        cursorProgram.use();
        cursorProgram.setFloat("rdx", rdx);
        
        if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)
        {
            double x = 0, y = 0;
            glfwGetCursorPos(window, &x, &y);
            cursorProgram.setVec2("cursor", (float)x, SCR_HEIGHT - (float)y);
        }
        else
        {
            cursorProgram.setVec2("cursor", 0.f, 0.f);
        }

        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);


        // Draw fbo0 to default buffer
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        assignProgram.use();
        assignProgram.setFloat("rdx", rdx);
        assignProgram.setInt("mytexture", 0);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, tex0);

        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        Sleep(16);

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // optional: de-allocate all resources once they've outlived their purpose:
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);

    // glfw: terminate, clearing all previously allocated GLFW resources.
    glfwTerminate();
    return 0;
}

void processInput(GLFWwindow* window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);
}

Solution

  • You have to set the texture minifying function (GL_TEXTURE_MIN_FILTER) by glTexParameter:

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    

    If you are not generating mipmaps (with glGenerateMipmap) it is important to set GL_TEXTURE_MIN_FILTER. Since the default filter is GL_NEAREST_MIPMAP_LINEAR, the texture would be "Mipmap Incomplete" if you did not change the minimize function to GL_NEAREST or GL_LINEAR.


    You missed to multiply gl_FragCoord.xy by rdx in the assignment shader:

    FragColor = texture2D(mytexture, gl_FragCoord.xy);

    FragColor = texture2D(mytexture, gl_FragCoord.xy * rdx);