Framebuffer Objects (FBO) and Render To Texture (RTT)

When rendering a scene directly to the screen (neglect double buffering for a second), OpenGL uses multiple buffers for storing the information. Beside the obvious buffer that holds the colour information of the generated image, other buffers can coexist like a buffer for storing the Depth values (also known as z-buffer) or even a buffer containing stencil values, that limit the area that is rendered to.

If you do not want to render to the screen frame buffer directly, but for example instead into a texture and use the render result later on, you can use your “own” framebuffer using OpenGL’s Framebuffer Object.

The Framebuffer Object provides attachment points where Renderbuffers as well as Texture Images can be attached to. By using the Framebuffer Object you can specify the Colour Buffer (also multiple), Depthbuffer, …, OpenGL will use for rendering.

You can create a Framebuffer Object by calling

var myFramebuffer = gl.createFramebuffer();

This will return an ID >0. You will use this ID later on for rendering.
To specify the active framebuffer you call

gl.bindFramebuffer(gl.FRAMEBUFFER, myFramebuffer);

Notice that to switch back to the “default” framebuffer just call

gl.bindFramebuffer(gl.FRAMEBUFFER, 0);

Now you need to attach the buffers. The Framebuffer object does not provide memory itself, just the attachment points. Therefore we create a texture and use one of its images as the colour buffer of the Framebuffer. As depth buffer we create and specify a render buffer (in opposite to a texture (image)). You can use texture images as well as render buffer for any attachment point. They have different advantages and disadvantages, an easy way to decide which one to use is:

If you want to use the outcome as a texture later on, use a texture image, else use a frame buffer. As we want to use the colour buffer as a texture later on we use a texture image and as we do not care about the depth buffer we use a render buffer.

As it is common that all attached buffers have the same size, we create two auxiliary variables holding the size of the buffers.

var myFBWidth = 512;
var myFBHeight = 512;

Comments are closed.