c++ - Compute Shader SSBO Only Writing to First Element – Why? - Stack Overflow

admin2025-04-19  0

I'm working with a Shader Storage Buffer Object (SSBO) in a compute shader, but I'm encountering an issue where only the first element of my array of structs is being written to. The remaining elements remain unchanged.

Expected Behavior:
All 10 elements in debugArray should be updated inside the compute shader.

Actual Behavior:
Only debugArray[0] is written to, while debugArray[1] to debugArray[9] remain zero.

I've already checked this, this, and this, but they didn’t help.


SSBO Setup (CPU Side)

struct DebugData
{
    float fx{0.0f}, fy{0.0f}, fz{0.0f}, D{0.0f}, G2{0.0f};
    float pad1{0.0f}, pad2{0.0f}, pad3{0.0f}; // Padding for std430 alignment
};

GLuint debugSSBO;
glGenBuffers(1, &debugSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, debugSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(DebugData) * 10, nullptr, GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, debugSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);

Compute shader

struct DebugData {
    float fx, fy, fz, D, G2;
    float pad1, pad2, pad3;
};

layout(std430, binding = 3) buffer DebugSSBO {
    DebugData debugArray[10];
};

void main() {
    for (int i = 0; i < K; i++) {
        const float res = foo(..., i);
    }
}

float foo(..., const in int idx) {
    if (gl_GlobalInvocationID.x == 512 && gl_GlobalInvocationID.y == 512) {
        debugArray[idx].fx = F.x;
        debugArray[idx].fy = F.y;
        debugArray[idx].fz = F.z;
        debugArray[idx].D = D;
        debugArray[idx].G2 = G2;
        debugArray[idx].pad1 = 1.0;
        debugArray[idx].pad2 = 1.0;
        debugArray[idx].pad3 = 1.0;
    }
}

Rendering with memory barrier

glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, debugSSBO);
renderer.trace(scene, frame_id); // Calls glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT) after glDispatchCompute(...)
renderer.draw_quad();

Reading back the SSBO data

glBindBuffer(GL_SHADER_STORAGE_BUFFER, debugSSBO);
DebugData *ptr = (DebugData *)glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY);
if (ptr)
{
    for (int i = 0; i < 10; i++)
    {
        std::cout << "bounce[" << i << "]: "
                  << "F(" << ptr[i].fx << ", " << ptr[i].fy << ", " << ptr[i].fz << ") "
                  << "D: " << ptr[i].D << " "
                  << "G2: " << ptr[i].G2 << " | " << ptr[i].pad1 << ptr[i].pad2 << ptr[i].pad3 << "\n";
    }
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
}
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);

Output

bounce[0]: F(0.831327, 0.158458, 0.158458) D: 0.31831 G2: 0.122287 | 111
bounce[1]: F(0, 0, 0) D: 0 G2: 0 | 000
bounce[2]: F(0, 0, 0) D: 0 G2: 0 | 000
...
bounce[9]: F(0, 0, 0) D: 0 G2: 0 | 000
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745072694a283381.html

最新回复(0)