4
我想要一個在輸出緩衝區中寫入1的計算着色器。我編譯着色器並將其附加到程序沒有問題,然後我打電話glDispatchCompute()函數,我等待,直到計算着色器結束。但是當我看到數組時,只有0。OpenGL計算着色器SSBO
有誰能告訴我哪裏錯了?
這是我的計算着色器代碼:
#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內存中讀取緩衝區。現在它可以工作。這是新代碼:
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.科爾曼。
我從只寫緩衝區讀取。這裏是固定線路:
ptr = (GLfloat *) glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY);
舉起......這裏有些事情是嚴重錯誤的。你不會像***只寫***一樣映射內存,然後轉身,除了***之外什麼都不做。你需要儘快解決這個問題。你應該映射它'GL_READ_ONLY';你正在讀取未定義的內存。 –