一步一步学RenderMonkey(4)--点光源光照模型

转载请注明出处:http://blog.csdn.net/tianhai110

 

点光源 光照模型:

公式:

I = Icolor*attenuation;                        attenuation表示衰减值

Attenuation = 1-d*d;                                       d为光源到该点的距离

通常我们用一个r来做点光源的衰减范围

attenuation = 1 - mul(Light/r, Light/r);

 

Phong光照的例子进行修改

1.       vecLightDir 改名为 vecLightPos 表示光源位置,而不是光的方向; 设置其值如下:

一步一步学RenderMonkey(4)--点光源光照模型_第1张图片

2.       修改vertex shader;

float4x4 matViewProjection; float4x4 matWorld; float4 vecLightPos; float4 vecEye; struct VS_INPUT { float4 Position : POSITION0; float3 Normal : NORMAL0; float2 Texcoord : TEXCOORD0; }; struct VS_OUTPUT { float4 Position : POSITION0; float2 Texc : TEXCOORD0; float3 Light : TEXCOORD1; float3 Norm : TEXCOORD2; float3 View : TEXCOORD3; }; VS_OUTPUT vs_main( VS_INPUT Input ) { VS_OUTPUT Output; Output.Position = mul( Input.Position, matViewProjection ); float3 posWorld = normalize(mul(Input.Position, matWorld)); Output.Light = vecLightPos - posWorld; Output.View = vecEye - posWorld; Output.Norm = mul(Input.Normal, matWorld); Output.Texc = Input.Texcoord; return( Output ); }

主要就是 outPut.Light 由原来直接传个方向,变成每次都要计算该点到光源的向量;

 

3.       修改 pixel shader;

sampler2D baseMap; float4 ps_main( float2 Texc:TEXCOORD0, float3 Light:TEXCOORD1, float3 Norm:TEXCOORD2, float3 View:TEXCOORD3) : COLOR0 { float4 ambient = { 0.3686f, 0.3686f, 0.3686f, 1.0f}; float4 diffuse = { 0.88f, 0.88f, 0.88f, 1.0f}; float3 Normal = normalize( Norm); float3 LightDir = normalize( Light); float3 ViewDir = normalize( View); float4 diff = saturate( dot( Normal, LightDir)); float3 Reflect = normalize( 2 * diff * Normal - LightDir); float4 shadow = saturate(4*diff); float4 fvBaseColor = tex2D( baseMap, Texc ); float4 specular = pow(saturate(dot(Reflect, ViewDir)), 25); float4 color = fvBaseColor * (shadow * diff + ambient) + shadow * specular; float4 attenuation = mul(Light/64.0, Light/64.0); return color*(1-attenuation); }

主要是 加入衰减值 float4 attenuation = mul(Light/64.0, Light/64.0);

 

4.       运行效果如下:

一步一步学RenderMonkey(4)--点光源光照模型_第2张图片

你可能感兴趣的:(struct,input,float,output)