1
votes

Constant buffer, declared in vertex shader source

cbuffer c_buffer : register(b0)
{
    matrix <float, 4, 4> u_mvpMatrix;
    matrix <float, 4, 4> m44;
    matrix <float, 3, 3> m33;
    matrix <float, 2, 3> m23;
    matrix <float, 3, 2> m32;
    matrix <float, 1, 3> m13;
}

Command to compile shader

fxc /nologo /E main /T vs_4_0_level_9_3 /Fh vertex_bytes.h /Vn bytes

And, at last, comments in generated vetex_output.h

// Buffer Definitions: 
//
// cbuffer c_buffer
// {
//
//   float4x4 u_mvpMatrix;              // Offset:    0 Size:    64
//   float4x4 m44;                      // Offset:   64 Size:    64 [unused]
//   float3x3 m33;                      // Offset:  128 Size:    44 [unused]
//   float2x3 m23;                      // Offset:  176 Size:    40 [unused]
//   float3x2 m32;                      // Offset:  224 Size:    28 [unused]
//   float1x3 m13;                      // Offset:  256 Size:    36 [unused]
//
// }
//
//
// Resource Bindings:
//
// Name                                 Type  Format         Dim Slot Elements
// ------------------------------ ---------- ------- ----------- ---- --------
// c_buffer                          cbuffer      NA          NA    0        1

I expected something like this:

//   float4x4 u_mvpMatrix;              // Offset:    0 Size:    64
//   float4x4 m44;                      // Offset:   64 Size:    64 [unused]
//   float3x3 m33;                      // Offset:  128 Size:    36 [unused]
//   float2x3 m23;                      // Offset:  164 Size:    24 [unused]
//   float3x2 m32;                      // Offset:  188 Size:    24 [unused]
//   float1x3 m13;                      // Offset:  212 Size:    12 [unused]

Why matrix size is not rows*columns*4 and offset is not prev_offset+prev_size?

I send all constant data as one buffer, created in runtime

ID3D11Buffer* cb;
CD3D11_BUFFER_DESC cbDesc(buffer_width, D3D11_BIND_CONSTANT_BUFFER);
D11Device->CreateBuffer(&cbDesc, nullptr, &cb)
byte* byte_buffer;
create_and_fill_byte_buffer_here();
D11DeviceContext->UpdateSubresource(cb, 0, NULL, byte_buffer, 0, 0);
D11DeviceContext->VSSetConstantBuffers(0, 1, &cb);

What should i pass as buffer_width? And what offsets should i use to write data to byte_buffer?

P.S. This method works with more simple shaders, with one 4x4 matrix or one float4 vector (buffer_width is 64 and 16 respectively; zero offset).

UPD1: Ok, offset could be explained with "nearest 16-multiple". In other words - each new constant aligned to new register. But still no idea about sizes.

1

1 Answers

6
votes

Offset and sizes can be explained by HLSL packing rules. Basically elements are aligned to 4 bytes and can't cross 16 byte boundary.

For example:

float3x3 m33
float3[ 0 ] X
float3[ 1 ] X
float3[ 2 ] X
Size: 16 + 16 + 12 = 44 bytes