4

It is desirable that I wipe the different color attachments of an FBO with different clear colors. Is this possible with GL commands or will I have to do it within shaders?

11

glClear(GL_COLOR_BUFFER_BIT) clears the current color buffers with the same color that is globally set (GL_COLOR_CLEAR_VALUE).

OpenGL 2+

To specify a different color for each buffer you have to change the current buffer through glDrawBuffer:

glDrawBuffer(GL_COLOR_ATTACHMENT0);
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
glDrawBuffer(GL_COLOR_ATTACHMENT1);
glClearColor(1,0,0,1);
glClear(GL_COLOR_BUFFER_BIT);

OpenGL 3.0+

If you already have your draw buffers set up, then you can use glClearBuffer to shorten that to:

static const GLenum draw_buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
glDrawBuffers(2, draw_buffers);
// ...
static const float transparent[] = { 0, 0, 0, 0 };
glClearBufferfv(GL_COLOR, 0, transparent);
static const float red[] = { 1, 0, 0, 1 };
glClearBufferfv(GL_COLOR, 1, red);

OpenGL 4.4+

However, if the FBO is backed by textures, then the easiest way would be to use glClearTexImage on those textures directly:

// clear to transparent:
glClearTexImage(color_texture0, 0, GL_RGBA, GL_FLOAT, 0);

// clear to specified color:
static const float red = { 1, 0, 0, 1 };
glClearTexImage(color_texture1, 0, GL_RGBA, GL_FLOAT, red);
| improve this answer | |
  • @livin_amuk: the glClearTexImage one? I don't know of any. It's simply the latest bindless way to do that, which in practice means that it's likely to outperform the others, but be not supported by some older hardware. – Yakov Galka Jun 26 '17 at 10:35
  • Yeh the glClearTexImage one. I see, thanks for the secret intel. – livin_amuk Jun 26 '17 at 10:39
  • 2
    @ybungalobill: "which in practice means that it's likely to outperform the others" That really depends on the hardware. Working with Vulkan, I've seen documentation from some vendors that suggest that framebuffer clearing is much faster than direct texture clearing. Granted, these were TBR GPUs, but in principle the possibility is still there. If you have images in a framebuffer, you should clear them through the framebuffer clearing APIs, not the texture clearing APIs. And glClearNamedFramebuffer* is the DSA equivalent of that. – Nicol Bolas Jun 26 '17 at 14:14
  • @NicolBolas: yes, glClearNamedFramebuffer is the DSA equivalent of glClearBuffer. – Yakov Galka Jun 26 '17 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.