# Problem with Basic Diffuse Lighting

So recently I have been learning how to implement Diffuse Lighting in DirectX and I have done so with the following code:

float4 PS(VS_OUTPUT input) : SV_TARGET
{
input.normal = normalize(input.normal);

float4 diffuse = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

float3 finalColor;

finalColor = diffuse * light.ambient;
finalColor += saturate(dot(light.dir, input.normal) * light.diffuse * diffuse);

return float4(finalColor, diffuse.a);
}


which has produced the following results:

Before I progress any further with specular lighting I wanted to clean up my code a little so I re-implemented this with a function and few changes.

float3 DirectDiffuseBRDF(float3 diffuseAlbedo, float nDotL)
{
return (diffuseAlbedo * nDotL);
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
input.normal = normalize(input.normal);

float4 diffuseAlbedo = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

float nDotL = saturate(dot(input.normal, light.dir));

float3 diffuseLighting = DirectDiffuseBRDF(diffuseAlbedo, nDotL);

return float4(diffuseLighting, diffuseAlbedo.a);
}


Which produces:

As you can see the modified code has it's diffuse lighting a little different compared to the original. What am I missing from the original code to get it back to normal?

I have combined the before and after code and came up with this:

float3 DirectDiffuseBRDF(float3 diffuseAlbedo, float nDotL)
{
return (diffuseAlbedo * nDotL);
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
input.normal = normalize(input.normal);

float4 diffuseAlbedo = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

float nDotL = dot(input.normal, light.dir);

float3 diffuseLighting = diffuseAlbedo * light.ambient;

diffuseLighting += saturate(DirectDiffuseBRDF(diffuseAlbedo, nDotL) * light.ambient);

return float4(diffuseLighting, diffuseAlbedo.a);
}


I haven't tested it but it should work.

• Thanks! That worked really well except that I removed the second * light.ambient. Could you explain what += saturate does? I am pretty new to DirectX as you can tell. – Arjan Singh Oct 9 '16 at 5:48
• The saturate function clamps a value between 0 and 1. If it's a vector it calms all of its components between 0 and 1. – JasonPh Oct 9 '16 at 6:04
• What does the += do? I've never really come across that. – Arjan Singh Oct 9 '16 at 6:13
• Let's say you have a variable called x. If you want to add a number to it, you will have to do this every time: x = x + a; (a is the number you want to add). Unfortunately this is way to long for a simple addition. So instead of doing that every time you can do this instead: x += a;. There are also other operates like: -= *= /= – JasonPh Oct 9 '16 at 6:21