DirectX HLSL - 像素着色器中的常量缓冲区为空,但顶点着色器中没有

DirectX HLSL - Constant Buffer empty in Pixel Shader but not Vertex Shader

我正在我的 DirectX 11 项目中实现光照。我遇到的问题是,当我尝试从像素着色器函数访问一个 cbuffer 值时,它只是返回 float3(0, 0, 0) 同时当我在顶点着色器函数中访问相同的值时,它 returns 正确价值。这是着色器:

/*********************************************\
                 VERTEX SHADER
\*********************************************/

//Constant buffers
cbuffer Object : register(cb0) {
    float4x4 WorldMatrix;
};
cbuffer Camera : register(cb1) {
    float4x4 ViewMatrix;
    float4x4 ProjectionMatrix;
};
cbuffer LightBuffer : register(cb2) {
    float3 AmbientColor;
}


//IO Structs
struct VS_INPUT {
    float3 Position : POSITION;
    float2 UV : TEXCOORD;
    float3 Normal : NORMAL;
};
struct VS_OUTPUT {
    float4 Position : SV_POSITION;
    float2 UV : TEXCOORD;
    float3 Normal : NORMAL;
};

VS_OUTPUT VS(VS_INPUT input){
    VS_OUTPUT output;

    float4 Position;

    //Multiply position with AmbientColor (should be 1, 1, 1), position unchanged
    Position = mul(ViewMatrix, float4(input.Position * AmbientColor, 1));
    Position = mul(ProjectionMatrix, Position);
    Position = mul(WorldMatrix, Position);

    output.Position = Position;
    output.UV = input.UV;
    output.Normal = mul(WorldMatrix, input.Normal);
    return output;
}

/*********************************************\
                PIXEL SHADER
\*********************************************/

SamplerState TextureState;
Texture2D<float4> Texture;
float4 PS(VS_OUTPUT input) : SV_TARGET {
    float4 MaterialColor = Texture.Sample(TextureState, input.UV);

    //Multiply color with AmbientColor (should be 1, 1, 1), returns black
    float3 FinalColor = MaterialColor.xyz * AmbientColor;

    return float4(FinalColor, MaterialColor.a);
}

这是我发送的值 (c++):

_LightsUniform.AmbientColor = XMFLOAT3(1, 1, 1); 
DeviceContext->UpdateSubresource(_LightBuffer, 0, NULL, &_LightsUniform, 0, 0);
DeviceContext->VSSetConstantBuffers(2, 1, &_LightBuffer);
DeviceContext->PSSetConstantBuffers(2, 1, &_LightBuffer);

结果如下: http://i.gyazo.com/357f1ed3ea33e6569ad2346b368cd975.png

不乘色的结果:http://gyazo.com/b60b385daa94d3373e9552a523928e3f

我看不出有什么问题。还有其他人遇到同样的问题吗?

我发现了问题。事实证明,我的 cbuffer(s) 的寄存器是错误的,我在应该使用 b# 的地方使用了 cb#。 (我误解了这里写的内容:https://msdn.microsoft.com/en-us/library/windows/desktop/hh447212(v=vs.85).aspx

错误代码:

cbuffer LightBuffer : register(cb2) {

更改为:

cbuffer LightBuffer : register(b2) {