跨不同着色器使用多个 image2d 的问题

Problem using mutiple image2d across diferent shaders

我是 opengl 的新手,我在跨两个计算着色器调用使用多个 image2d 对象时遇到问题。

我这样创建纹理:

GLuint light_texture[3];
glGenTextures(3, light_texture);
for (int i = 0; i < 3; i++) {
    glActiveTexture(GL_TEXTURE1 + i);
    glBindTexture(GL_TEXTURE_2D, light_texture[i]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GL_RED, GL_UNSIGNED_INT, NULL);        
    glBindImageTexture(i+1, light_texture[i], 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32UI);    
}
computeShader.use();
computeShader.setInt("img_red",1);
computeShader.setInt("img_green", 2);
computeShader.setInt("img_blue", 3);
mixShader.use();
mixShader.setInt("img_red", 1);
mixShader.setInt("img_green", 2);
mixShader.setInt("img_blue", 3); 

和运行着色器:

computeShader.use();
glDispatchCompute((GLuint)TEXTURE_WIDTH, (GLuint)TEXTURE_HEIGHT, 1);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
  
mixShader.use();
glDispatchCompute((GLuint)TEXTURE_WIDTH, (GLuint)TEXTURE_HEIGHT, 1);

第一个着色器只是为每个图像设置一些值

计算着色器:

layout (local_size_x = 1, local_size_y = 1) in;


layout (binding = 1,r32ui) uniform coherent uimage2D img_red;
layout (binding = 2,r32ui) uniform coherent uimage2D img_green;
layout (binding = 3,r32ui) uniform coherent uimage2D img_blue;


void main()
{
    ivec2 pixel_position = ivec2(gl_GlobalInvocationID.xy);
    imageStore(img_red, pixel_position, uvec4(600));
    imageStore(img_green, pixel_position, uvec4(1));
    imageStore(img_blue, pixel_position, ivec4(1));


    
} 

为了测试它是否有效,我只是让混合着色器在读取大于 0 的值时渲染为白色,在读取值大于 0 时渲染为红色。

混合着色器:

#version 460 core

layout (local_size_x = 1, local_size_y = 1) in;
layout (binding = 0,rgba32f) uniform image2D target_texture;
layout (binding = 1,r32ui) uniform coherent uimage2D img_red;
layout (binding = 2,r32ui) uniform coherent uimage2D img_green;
layout (binding = 3,r32ui) uniform coherent uimage2D img_blue;



void main(){
    ivec2 pixel_position = ivec2(gl_GlobalInvocationID.xy);
    vec4 color;
    if(imageLoad(img_red, pixel_position).r>0 ||imageLoad(img_green, pixel_position).r>0||imageLoad(img_blue, pixel_position).r>0){
        color =vec4(1,1,1,1);
    }else{
        color = vec4(1,0,0,1);
    }
    

    imageStore(target_texture, pixel_position, color);


}

我一直在变红。 我不知道问题出在纹理创建还是着色器中,但我无法让它工作。

通过改变创建纹理的方式解决了这个问题:

GLuint color_textures[3];
glGenTextures(3,color_textures);
for (int i = 0; i < 3; i++) {
    glBindTexture(GL_TEXTURE_2D, color_textures[i]);
    glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32UI,TEXTURE_WIDTH,TEXTURE_HEIGHT);
    glBindImageTexture(i+1, color_textures[i], 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32UI);

}