directx-11hlslmemcpycompute-shaderstructured-data

Mapping a vector to a structuredbuffer gives incorrect values in computeshader


I have a structuredbuffer in a computeshader which is supposed to hold information about several lights, pos, direction, colour, etc. I have managed to get the info into the computeshader, but the values are incorrect. A float4(1.0, 0.0, 0.0, 1.0); should give me the colour red, but for some reason, I get purple when writing to the backbuffer.

Where I bind the information and send it to the computeshader

if (FAILED(immediateContext->Map(lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mpdResource)))
    {
        return false;
    }

    std::vector<LightBufferType> lightsBuf(2);

    DirectX::XMMATRIX matrix;

    for (int i = 0; i < 2; i++) 
    {
        lightsBuf[i].lightPos = lights[i].GetPos();
        lightsBuf[i].lightDir = lights[i].GetDir();

        lights[i].GetViewMatrix(matrix);
        lightsBuf[i].lightViewMatrix = DirectX::XMMatrixTranspose(matrix);
        lights[i].GetProjMatrix(matrix);
        lightsBuf[i].lightProjMatrix = DirectX::XMMatrixTranspose(matrix);

        lightsBuf[i].lightColor = lights[i].GetDiffCol();

        lightsBuf[i].angle = 30.0f;
        lightsBuf[i].type = lights[i].GetType();

    }

    memcpy(mpdResource.pData, lightsBuf.data(), sizeof(LightBufferType) * 2);

    immediateContext->Unmap(lightBuffer, 0);

    immediateContext->CSSetShaderResources(6, 1, &structuredSRV);

My hypothesis is that my problem is that I use the incorrect size in memcpy

Sent structured buffer to computeshader, but it has incorrect values


Solution

  • Found the problem, it seemed like transposing the matrixes made them larger, and therefore they kinda "leaked" over to the lightcolor. I found that storing the matrixes in Float4X4 stopped this from happening.

            lights[i]->GetViewMatrix(matrix1);
            lights[i]->GetProjMatrix(matrix2);
            
            matrix1 = DirectX::XMMatrixTranspose(matrix1);
            matrix2 = DirectX::XMMatrixTranspose(matrix2);
    
            DirectX::XMStoreFloat4x4(&viewFloat, matrix1);
            DirectX::XMStoreFloat4x4(&projFloat, matrix2);
    
            lightTest.lightProj = projFloat;
            lightTest.lightView = viewFloat;