简体   繁体   中英

Should I reuse the same constant buffer in multiple shader stages?

For example, instead of:

VertexShader.hlsl

cbuffer VSPerInstance : register(b0){
    matrix World, View, Projection;
};

PixelShader.hlsl

cbuffer PSPerInstance : register(b0){
    float4 AmbientColor;
    float4 DiffuseColor;
    float4 SpecularColor;
    float4 EmissiveColor;
};

I could have:

MyInclude.hlsl

cbuffer PerInstance : register(b0){
    matrix World, View, Projection;
    float4 AmbientColor;
    float4 DiffuseColor;
    float4 SpecularColor;
    float4 EmissiveColor;
};

In a include file, when updating the constant buffer this would reduce the number of calls to ID3D11DeviceContext::Map , although I would still have to copy the same amount of bytes and set the constant buffer for each stage, like: ID3D11DeviceContext::VSSetShader , ID3D11DeviceContext::PSSetShader , etc.

So my question is, is it even legal to set the same constant buffer in multiple shader stages? And is there anything negative about it that I should reconsider? Since I started learning Direct3D programming, all the examples that I have seem use individual buffers for each stage as in the first example, so I don't know if this is a good practice.

Just to make things clearer, I'm still using more than one constant buffer anyway, I have one constant buffer for each frequency of update, one for each instance, for each partition, for each draw call...

You generally want to organize the constant buffers by "frequency of update". So in your case, you'd probably want:

cbuffer VSPerInstance : register(b0){
    matrix World, View, Projection;
};

which is updated per render frame and a different.

cbuffer PerInstance : register(b1){
    float4 AmbientColor;
    float4 DiffuseColor;
    float4 SpecularColor;
    float4 EmissiveColor;
};

which is updated per material.

You can reuse the same cbuffers at different stages of the render pipeline, and it's generally a good idea to minimize binding and update costs. The only real restriction is you can't have the same resource bound as an input and output at the same time (such as a texture bound for reading by the pixel shader and as render target in the same Draw ).

See this venerable presentation from Gamefest 2007) for general recommendations on constant buffer usage for Direct3D 10 and 11.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM