Reprinted please indicate the source: http://blog.csdn.net/tianhai110
Point Light Source Illumination Model:
Formula:
I = icolor * attenuation; attenuation indicates the attenuation value.
Attenuation = 1-D * D; D indicates the distance from the light source to this point.
Generally, we use an R as the attenuation range of the point light source.
And attenuation = 1-Mul (light/R, light/R );
Modify the Phong lighting example
1. Change veclightdir to veclightpos to indicate the position of the light source, rather than the direction of the light. Set the value as follows:
2. Modify vertex shader;
Float4x4 matviewprojection; </P> <p> float4x4 matworld; </P> <p> float4 veclightpos; </P> <p> float4 veceye; </P> <p> struct vs_input </P> <p >{</P> <p> float4 position: position0; </P> <p> float3 normal: normal0; </P> <p> float2 texcoord: texcoord0; </P> <p> }; </P> <p> struct vs_output </P> <p >{</P> <p> float4 position: position0; </P> <p> float2 texc: texcoord0; </P> <p> float3 light: texcoord1; </P> <p> float3 norm: texcoord2; </P> <p> float3 view: texcoord3; </P> <p >}; </P> <p> vs_output vs_main (vs_input input) </P> <p >{</P> <p> vs_output output; </P> <p> output. position = MUL (input. position, matviewprojection); </P> <p> float3 posworld = normalize (MUL (input. position, matworld); </P> <p> output. light = veclightpos-posworld; </P> <p> output. view = veceye-posworld; </P> <p> output. norm = MUL (input. normal, matworld); </P> <p> output. texc = input. texcoord; </P> <p> return (output); </P> <p >}</P> <p>
The main difference is that the output. Light is directly transferred from the original direction to the vector from the point to the light source;
3. Modify pixel shader;
Sampler2d basemap; </P> <p> float4 ps_main (float2 texc: Plain, float3 light: texcoord1, </P> <p> float3 norm: texcoord2, float3 view: texcoord3): color0 </P> <p >{</P> <p> float4 ambient = {0.20.6f, 0.20.6f, 0.20.6f, 1.0f }; </P> <p> float4 diffuse = {0.88f, 0.88f, 0.88f, 1.0f}; </P> <p> float3 normal = normalize (Norm ); </P> <p> float3 lightdir = normalize (light); </P> <p> float3 viewdir = normalize (View ); </P> <p> float4 diff = saturate (dot (normal, lightdir )); </P> <p> float3 reflect = normalize (2 * diff * normal-lightdir); </P> <p> float4 shadow = saturate (4 * diff ); </P> <p> float4 fvbasecolor = tex2d (basemap, texc); </P> <p> float4 specular = POW (saturate (dot (reflect, viewdir )), 25); </P> <p> float4 color = fvbasecolor * (shadow * diff + ambient) + shadow * specular; </P> <p> float4 attenuation = MUL (light/64.0, light/64.0); </P> <p> return color * (1-attenuation ); </P> <p >}</P> <p>
It mainly adds the attenuation value float4 attenuation = MUL (light/64.0, light/64.0 );
4. The running effect is as follows: