片段着色器中的多纹理输出数据

Multiple texture output data in fragment shader

我正在尝试使用 GPU 来求解算法,并且我正在使用着色器来这样做(不是计算着色器,只是顶点和片段着色器)。为此,我需要在我的片段着色器中使用两个输出变量来提取数据,我对输入数据没有任何问题(工作得很好)但到目前为止我无法使用两个输出变量 运行 因为只有一个他们真的在工作,或者他们之间发生了一些奇怪的事情。

我也希望这个问题可以作为这种实践的参考(GPGPU 的片段着色器中的几个输出),因为到目前为止我所看到的只是具体情况。 首先,我有两个纹理,我只加载一次,如下所示:

第一 纹理

glBindTexture(GL_TEXTURE_2D, texture[4]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32I, width, height,
    0, GL_RED_INTEGER, GL_INT, 0);

第二 纹理

glBindTexture(GL_TEXTURE_2D, texture[5]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32I, width, height,
    0, GL_RED_INTEGER, GL_INT, 0);

这两个纹理应该存储我的输出数据(每个纹理应该是一个变量输出)在这两种情况下,我都使用红色组件将数据存储为整数。

现在我创建一个帧缓冲区并将这两个纹理绑定到帧缓冲区,每个纹理都在 color_attachment.

glGenFramebuffers(1, &resultFBO); // frame buffer id
glBindFramebuffer(GL_FRAMEBUFFER, resultFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
    GL_TEXTURE_2D, texture[4], 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
    GL_TEXTURE_2D, texture[5], 0);

现在,对于片段着色器,我这样设置输出变量的位置:

layout(location = 0) out int resultFlow;
layout(location = 1) out int resultAccumFlow;

最后,我在绑定同一个帧缓冲区后调用了 DrawArrays()(在渲染循环中):

    glBindFramebuffer(GL_FRAMEBUFFER, resultFBO);
    // Render
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

我很确定这最后一步不是 "working" 但也许我还需要其他东西。我试图查找它,但没有找到任何文档,无论如何,如果确实有一些与此相关的论文,那将非常有帮助。

... but so far I wasnt able to make it run with two output variable because just one of them is actually working ...

当您想在片段着色器中写入多个目标时,您错过的最后一步是指定要绘制到的颜色缓冲区列表。 这可以通过 glDrawBuffers:

来完成
glBindFramebuffer(GL_FRAMEBUFFER, resultFBO);

GLenum drawBuffers[]={GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
glDrawBuffers(2, drawBuffers);

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

提示:您可以使用glClearBuffer清除帧缓冲区的各个缓冲区


OpenGL 4.6 API Core Profile Specification; 17.4.1 Selecting Buffers for Writing; page 513:

17.4.1 Selecting Buffers for Writing

.....

The set of buffers of a framebuffer object to which all fragment colors are written is controlled with the commands

void DrawBuffers( sizei n, const enum *bufs );
void NamedFramebufferDrawBuffers( uint framebuffer, sizei n, const enum *bufs );

.....

For framebuffer objects, in the initial state the draw buffer for fragment color zero is COLOR_ATTACHMENT0. For both the default framebuffer and framebuffer objects, the initial state of draw buffers for fragment colors other then zero is NONE.