Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

opengl - How can I render to multiple attachments of a FBO?

After some studying I found out how to render to a single texture using a color attachment. However, I'd like to create multiple textures using multiple attachments. Here is the code I use:

glGenFramebuffers(1, &myFBO);
glBindFramebuffer(GL_FRAMEBUFFER, myFBO);

glGenTextures(1, &RGBTexture);
glBindTexture(GL_TEXTURE_2D, RGBTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, W_WIDTH/2, W_HEIGHT/2, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, RGBTexture, 0);

glGenTextures(1, &normalMapTexture);
glBindTexture(GL_TEXTURE_2D, normalMapTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, W_WIDTH/2, W_HEIGHT/2, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, normalMapTexture, 0);

unsigned int attachments[2] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
glDrawBuffers(2, attachments);

The fragment shader :

#version 330 core

layout(location=0) out vec3 fragment_color;
layout(location=1) out vec3 normal;

void main()
{
fragment_color = vec3(1, 1, 1);
normal=vec3(0,1,0);
}

Just for testing, I render a white and a green texture. However, when I render them on a quad later, they are empty.

When using only one attachment, I avoid the "location" commands in the fragment shader. I just declare an out vec3 and the single texture is generated just fine. I render it on a quad and it is indeed ok. So there has to be something wrong with my FBO or the fragment shader.

Note that I have also bound a depth component ( not shown above ) which works properly. I mention it in case it matters.

Update-Solution

If I define the outputs in the fragment shader as vec4 everything works just fine. WHY?

question from:https://stackoverflow.com/questions/65872762/how-can-i-render-to-multiple-attachments-of-a-fbo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...