OpenGL计算着色器SSBO [英] OpenGL Compute Shader SSBO

查看:1708
本文介绍了OpenGL计算着色器SSBO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个在输出缓冲区中写入1的计算着色器.我编译着色器并将其毫无问题地附加到程序中,然后调用 glDispatchCompute()函数,然后等到计算着色器结束.但是当我看到数组时,只有0.

I want a compute shader that writes 1's in the output buffer. I compile the shader and attach it to the program without problem, then I call glDispatchCompute() function and I wait until compute shader ends. But when I see the array, there are only 0's.

谁能告诉我哪里出了错?

Can anyone tell me where is the mistake?

这是我的计算着色器代码:

This is my compute shader code:

#version 430 core

layout  (local_size_x  =  2)  in;

layout(std430, binding=0) writeonly buffer Pos{
    float Position[];
};

void main(){
    Position[gl_GlobalInvocationID.x] = 1.0f;
}

这是我的主要内容:

GLuint program_compute = 0, SSBO = 0;

//...(Create, compile and link the program with the shader)...

vector<GLfloat> initPos;
int num_numeros = 12;

for (int i = 0; i < num_numeros; i++){
    initPos.push_back(0.0f);
}

glUseProgram(program_compute);

glGenBuffers(1, &SSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, SSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, num_numeros * sizeof(GLfloat), &initPos, GL_DYNAMIC_DRAW);

glDispatchCompute(num_numeros/2, 1, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);

for (int i = 0; i < num_numeros; i++){
    cout << "p" << i << ": " << initPos[i] <<  endl;
}
cout << endl;

终于可以了.谢谢BDL.

正如BDL所说,我忘记了从GPU内存中读回缓冲区.现在可以了.这是新代码:

As BDL has said, I've forgotten read the buffer back from GPU memory. Now it works. This is the new code:

GLuint program_compute = 0, SSBO = 0;

// ...The same code as above

glDispatchCompute(num_numeros/2, 1, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);

glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO);

GLfloat *ptr;
ptr = (GLfloat *) glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_WRITE_ONLY);
initPos.clear();

for (int i = 0; i < num_numeros; i++){
    initPos.push_back(ptr[i]);
}

glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

for (int i = 0; i < num_numeros; i++){
    cout << "p" << i << ": " << initPos[i] <<  endl;
}
cout << endl;

谢谢Andon M. Coleman.

我从只写缓冲区读取.这是固定的行:

I read from a write only buffer. Here is the line fixed:

ptr = (GLfloat *) glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY);

推荐答案

glBufferData 将的内容复制到SSBO中.然后,着色器将在缓冲区上而不是在cpu内存阵列上进行操作.除非您将缓冲区从GPU读回CPU内存,否则initPos将永远不会改变.

glBufferData copies the content of initPos into the SSBO. The shader then operates on the buffer, not on the cpu memory array. Unless you read the buffer back from GPU to CPU memory somewhere, initPos will never change.

这篇关于OpenGL计算着色器SSBO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆