To render to a texture and then apply that texture to a scene in a second pass, use the following steps:
- Within the main OpenGL program, use the following code to set up the framebuffer object:
GLuint fboHandle; // The handle to the FBO // Generate and bind the framebuffer glGenFramebuffers(1, &fboHandle); glBindFramebuffer(GL_FRAMEBUFFER, fboHandle); // Create the texture object GLuint renderTex; glGenTextures(1, &renderTex); glActiveTexture(GL_TEXTURE0); // Use texture unit 0 glBindTexture(GL_TEXTURE_2D, renderTex); glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, 512, 512); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Bind the texture to the FBO glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTex, 0); // Create the depth buffer GLuint depthBuf; glGenRenderbuffers(1, &depthBuf); glBindRenderbuffer(GL_RENDERBUFFER, depthBuf); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 512, 512); // Bind the depth buffer to the FBO glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuf); // Set the target for the fragment shader outputs GLenum drawBufs[] = {GL_COLOR_ATTACHMENT0}; glDrawBuffers(1, drawBufs); // Unbind the framebuffer, and revert to default glBindFramebuffer(GL_FRAMEBUFFER, 0);
- In your render function within the OpenGL program, bind to the framebuffer, draw the scene that is to be rendered to the texture, then unbind from that framebuffer and draw the cube:
// Bind to texture's FBO glBindFramebuffer(GL_FRAMEBUFFER, fboHandle); glViewport(0,0,512,512); // Viewport for the texture
// Use the texture for the cow here int loc = glGetUniformLocation(programHandle, "Texture"); glUniform1i(loc, 1); // Setup the projection matrix and view matrix // for the scene to be rendered to the texture here. // (Don't forget to match aspect ratio of the viewport.) renderTextureScene(); // Unbind texture's FBO (back to default FB) glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0,0,width,height); // Viewport for main window // Use the texture that is linked to the FBO int loc = glGetUniformLocation(programHandle, "Texture"); glUniform1i(loc, 0); // Reset projection and view matrices here...
renderScene();