# How to use FrameBuffer objects (OpenGL)

I want to draw a 2D scene and after the scene i want to draw some light effects.

When i draw some light, i create a FBO, draw in it and when finished with drawing, i want to create a texture where i draw the content of the FBO.

My current code:

//////////
//Init_

//Create Texture
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, out _texfbo);
glBindTexture(GL_TEXTURE_2D, _texfbo);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _screenWidth, _screenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);
glBindTexture(GL_TEXTURE_2D, 0);

//Create Renderbuffer
glGenRenderbuffers(1, out _rb);
glBindRenderbuffer(GL_RENDERBUFFER, _rb);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, _screenWidth, _screenHeight);
glBindRenderbuffer(GL_RENDERBUFFER, 0);

//Create Framebuffer
glGenFramebuffers(1, out _fbo);
glBindFramebuffer(GL_FRAMEBUFFER, _fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texfbo, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _rb);
glBindFramebuffer(GL_FRAMEBUFFER, 0);

//////////
//Loop:

glBindFramebuffer(GL_FRAMEBUFFER, _fbo);

//Draw Scene

glBindFramebuffer(GL_FRAMEBUFFER, 0);

glBindTexture(GL_TEXTURE_2D, _texfbo);

//Draw Rectangle with texture from Framebuffer


The Scene is not drawn on the screen, i think that means it's drawn in the right buffer. But i can't get someting on the screen. What is wrong?

• This is essentially a "debug my code" question. I suggest you get a working example of using FBOs and build from there. Alternatively you can use the debugger to ensure your data looks correct before going to the GPU and you can use something like gDEBugger to check it out on the GPU. Further, see these related questions: gamedev.stackexchange.com/questions/61524/… gamedev.stackexchange.com/questions/8790/… (see how both answers turned out to be coding issues). – MichaelHouse Jan 18 '14 at 16:47

## 1 Answer

You are missing a glDrawBuffers (...) call. You need to establish that color attachment 0 is the first buffer your fragment shader is going to output.

### This should fix your problem:

glBindFramebuffer(GL_FRAMEBUFFER, _fbo);

const GLenum draw_buffer = GL_COLOR_ATTACHMENT0;
glDrawBuffers (1, &draw_buffer);

//Draw Scene

glBindFramebuffer(GL_FRAMEBUFFER, 0);


You do not have to do this in the loop, you could do it once when you initialize your FBO. But you do have to do it somewhere while your FBO is bound.

• I assume this is written in C? the out in your code is confusing me. You may have to slightly alter the code in the answer if this is not C. – Andon M. Coleman Jan 19 '14 at 1:32
• It's C#. out give the reference of the variable instead of the value. Like a Pointer. – fedab Jan 19 '14 at 1:53