【问题标题】:Array of structures into Compute Shader计算着色器中的结构数组
【发布时间】:2017-02-15 16:40:15
【问题描述】:

在 OpenGL 中编写一个简单的计算着色器以了解其工作原理,但无法获得想要的结果。

我想将一个结构数组 colourStruct 传递给我的计算着色器来为输出纹理着色。

当我的计算着色器中的“wantedColor”= 0 时,我想要一个红色图像和一个绿色图像“wantedColor” = 1,蓝色代表 2。

但实际上,当“wantedColor”= 1 或 2 或 3 时,我只有红色,而当“wantedColor” > 2 时,我只有黑色...

如果有人有想法,或者我不理解计算着色器输入的想法。

感谢您的帮助,这是我的代码中有趣的部分。

我的计算着色器:

 #version 430 compatibility

layout(std430, binding=4) buffer Couleureuh
{
  vec3 Coul[3]; // array of structures
};

layout(local_size_x = 1, local_size_y = 1) in;
layout(rgba32f, binding = 0) uniform image2D img_output;

void main() {

  // base pixel colour for image
  vec4 pixel = vec4(0.0, 0.0, 0.0, 1.0);

  // get index in global work group i.e x,y, position
  ivec2 pixel_coords = ivec2(gl_GlobalInvocationID.xy);
  ivec2 dims = imageSize (img_output);


  int colorWanted = 0;
  pixel = vec4(Coul[colorWanted], 1.0);

  // output to a secific pixel in the image
  imageStore (img_output, pixel_coords, pixel);

}

计算着色器和 SSBO 初始化:

    GLuint structBuffer;
    glGenBuffers(1, &structBuffer);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, structBuffer);
    glBufferData(GL_SHADER_STORAGE_BUFFER, 3*sizeof(colorStruct), NULL, GL_STATIC_DRAW);

        GLint bufMask = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT; // invalidate makes a ig difference when re-writting

    colorStruct *coul;
    coul = (colorStruct *) glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, 3*sizeof(colorStruct), bufMask);


    coul[0].r = 1.0f;
    coul[0].g = 0.0f;
    coul[0].b = 0.0f;

    coul[1].r = 0.0f;
    coul[1].g = 1.0f;
    coul[1].b = 0.0f;

    coul[2].r = 0.0f;
    coul[2].g = 0.0f;
    coul[2].b = 1.0f;

    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, structBuffer);

    m_out_texture.bindImage();

    // Launch compute shader
    m_shader.use();

    glDispatchCompute(m_tex_w, m_tex_h, 1);

    // Prevent samplign before all writes to image are done
    glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

【问题讨论】:

    标签: opengl shader opengl-4 compute-shader shader-storage-buffer


    【解决方案1】:

    vec3 始终是 16 字节对齐的。因此,当它们在数组中时,它们的行为就像vec4s。即使使用std430 布局。

    Never use vec3 in interface blocks。您应该使用 floats 数组(单独访问所需的 3 个成员)或 vec4 数组(带有未使用的元素)。

    【讨论】:

    • 它使用浮点数和 vec4 工作!非常感谢你! :)。
    猜你喜欢
    • 2021-04-29
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    相关资源
    最近更新 更多