Prepare the FBO to write to more than one textures.
// Bind the FBO
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
// Bind a buffer of the zeroth color attachment slot.
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
// Here, we use a value from the extension to make it the same as the next statement.
// You can use gl.COLOR_ATTACHMENT0 as well because these two values are equal.
gl.webGlDrawBuffers.COLOR_ATTACHMENT0_WEBGL,
gl.TEXTURE_2D,
// We attach the primitiveIndexTexture here because we will read from it later.
// We can only read (to Javascript) from the zeroth color attachment.
primitiveIndexTexture,
0);
// Bind another buffer of the first color attachment slot.
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
// This is the first color attachment slot.
gl.webGlDrawBuffers.COLOR_ATTACHMENT1_WEBGL,
gl.TEXTURE_2D,
// We attach the render buffer here because we do not need to read from it to Javascript.
renderBuffer.getWriteBuffer(),
0);
// Since we are doing 3D rendering, we need the depth buffer.
gl.framebufferRenderbuffer(
gl.FRAMEBUFFER,
gl.DEPTH_ATTACHMENT,
gl.RENDERBUFFER,
depthBuffer
);
// IMPORTANT: We need to tell WebGL to draw to two buffers.
// By default, it only draws to the zeroth color attachment slot.
// The function drawBuffersWEBGL is not available in the vanilla WebGL 1.0 context.
// You only get it with the WEBGL_draw_buffers extension.
gl.webGlDrawBuffers.drawBuffersWEBGL(
// Here, we give it the list of slots we want to draw to.
[
gl.webGlDrawBuffers.COLOR_ATTACHMENT0_WEBGL, // gl_FragData[0]
gl.webGlDrawBuffers.COLOR_ATTACHMENT1_WEBGL // gl_FragData[1]
]
);
{
gl.clearColor(0.75, 0.75, 0.75, 1.0);
gl.clearDepth(1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
// Code elided for brevity.
gl.disable(gl.DEPTH_TEST);
gl.flush();
}
//
// Here we have code that reads from the zeroth color attachment.
// This has to be done while the FBO is still bound and the texture still attached.
// We will talk about this part later.
//
// To clean up, we detach the zeroth color attachment.
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.webGlDrawBuffers.COLOR_ATTACHMENT0_WEBGL,
gl.TEXTURE_2D,
null,
0);
// Then the first color attachment.
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.webGlDrawBuffers.COLOR_ATTACHMENT1_WEBGL,
gl.TEXTURE_2D,
null,
0);
// Then the depth attachment.
gl.framebufferRenderbuffer(
gl.FRAMEBUFFER,
gl.DEPTH_ATTACHMENT,
gl.RENDERBUFFER,
null
);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
renderBuffer.swap();