Thursday, December 7, 2006

Render to Texture

OpenGL supports fast crossplatform offscreen rendering through the GL_EXT_framebuffer_object extension.

To render to a texture using the framebuffer object you must

1) Create a framebuffer object
glGenFramebuffersEXT(1, &myFBO);


2) Bind the framebuffer object
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, myFBO);


3) Attach a texture to the FBO
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, myTexture, 0);


4) If you need depth testing, create and attach a depth renderbuffer

// Gen renderbuffer
glGenRenderbuffersEXT(1, &myRB);

// Bind renderbuffer
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, myRB);

// Init as a depth buffer
glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, width, height);

// Attach to the FBO for depth
glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, myRB);

5) Render just like you normally would.

6) Unbind the FBO (and renderbuffer if necessary). glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

7) Use the texture you rendered to!

NOTES:

All textures and renderbuffers attached to the framebuffer object must have the same dimensions.

You must use the GL_EXT_packed_depth_stencil extension to use stencil testing with framebuffer objects.

You can only render to RGB, RGBA, and depth textures using framebuffer objects.


References:

Framebuffer object specification

4 comments:

Anders Riggelsen said...

>> You can only render to RGB, RGBA, and depth textures using framebuffer objects.
I successfully rendered to an FBO containing a GL_INTENSITY16F_ARB buffer. I used this with a pixel shader to store a high quality linear z-depth value in my texture for use in volumetric fog/water.

Alex Scarborough said...

Some drivers will let you render to other formats, but it is a violation of the spec and behavior you should never rely on.

Brandon Kiesling said...

Thanks for this, this was a much more clear example than most of what I had seen previously.

Nexii Malthus said...

Thank you so much for this tip, very concise and clear to the point, now I really understand how this works. Thanx!