只有第一个Compute Shader数组元素出现更新

时间:2015-12-30 22:32:22

标签: c++ opengl shader compute-shader

尝试将一个整数数组发送到计算着色器,为每个整数设置一个任意值,然后读回CPU / HOST。问题是只有我的数组的第一个元素得到更新。我的数组在CPU中初始化所有元素= 5,然后我尝试在Compute Shader中将所有值设置为2:

C ++代码:

   this->numOfElements = std::vector<int> numOfElements; //num of elements for each voxel

   //Set the reset grid program as current program
    glUseProgram(this->resetGridProgHandle);

    //Binds and fill the buffer 
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, this->counterBufferHandle);
    glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(int) * numOfVoxels, this->numOfElements.data(), GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, this->counterBufferHandle);

    //Flag used in the buffer map function
    GLint bufMask = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT;

    //calc maximum size for workgroups
    //glGetIntegerv(GL_MAX_COMPUTE_WORK_GROUP_SIZE, &result);

    //Executes the compute shader
    glDispatchCompute(32, 1, 1); // 
    glMemoryBarrier(GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT);

    //Gets a pointer to the returned data
    int* returnArray = (int *)glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_WRITE);

    //Free the buffer mapping
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

着色器:

#version 430
layout (local_size_x = 32) in;
layout(binding = 0) buffer SSBO{
    int counter[];
};

void main(){
    counter[gl_WorkGroupID.x * gl_WorkGroupSize.x + gl_LocalInvocationID.x] = 2;
}

如果我打印returnArray [0]它是2(正确),但任何索引&gt; 0给出了5,这是在主机中初始化的初始值。

2 个答案:

答案 0 :(得分:1)

glMemoryBarrier(GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT);

//Gets a pointer to the returned data
int* returnArray = (int *)glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_WRITE);

您用于glMemoryBarrier的位表示您想要读取着色器写入的数据的方式。 GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT说&#34;我将通过使用顶点属性数组的缓冲区来读取这些写入的数据&#34;。实际上,您将通过映射来读取缓冲区。

所以你应该使用适当的屏障位:

glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT);

答案 1 :(得分:0)

好,我也有这个问题 我改变了:

layout(binding = 0) buffer SSBO{

收件人:

layout(binding = 0, std430) buffer SSBO{