DirectX11 set shader constants

Mat picture Mat · Mar 3, 2012 · Viewed 8k times · Source

Having XNA background, I try to create a simple DirectX11 application. Now I try to figure out how to set shader constants such as projection matrix etc. I'm reading about constant-buffers - but is there no simple way to set some constants before rendering, without using buffers?

Answer

Lucius picture Lucius · Mar 3, 2012

I have taken the same path and this is something I have been struggling with as well. Since DirectX10 there have been a lot of changes to the interface, allowing more overall control.

Sooner or later you will get used to the buffers and discover they are in fact pretty neat.

Here are some advantages and tips:

  • There is now a uniform way of binding vertex, index and constant data to the pipeline, namely the Buffer class.

  • Constants are packed in registers with each holding up to four 32-bit components.

  • You can pack the constants manually using the packoffset() HLSL function. There are some rules you have to consider.

  • As you can bind multiple constant buffers to a single stage it is recommended to separate your constants by their update frequency. For example, the view and projection matrices are usually updated once every frame, while the world matrix will change for every mesh. For optimal performance you would create two buffers, one containing per frame data, and the other one per mesh data.

  • Finally, the limits for constant buffers:

Each constant buffer can hold up to 4096 vectors; each vector contains up to four 32-bit values. You can bind up to 14 constant buffers per pipeline stage (2 additional slots are reserved for internal use).