Tuesday, November 03, 2009

Extending the Basic Lighting Function - Attenuation

Following the cg tutorial chapter on lighting i introduced now some light attenuation. This makes the effect that an object is brighter when the light is close and darker when the light is far. It depends on basically four parameters: Range, and constant, linear and quadratic fall-off.







struct Material
{
float4 Ka;
float4 Ke;
float4 Kd;
float4 Ks;
float shininess;
};

struct Light
{
float3 position; // Light Position
float4 diffuseColor; // Diffuse Color
float4 specularColor; // Specular Color
float range; // Light Range
float Kc; // Constant Attenuation Coefficient
float Kl; // Linear Attenuation Coefficient
float Kq; // Quadratic Attenuation Coefficient
};

float attenuationFunction(
float3 position,
Light light)
{
float d = distance(position, light.position);
return 1 / (light.Kc + light.Kl * d +
light.Kq * d * d);
}

float4 lighting(Material material,
Light light,
float4 globalAmbient,
float4 position,
float3 normal,
float3 eyePosition)
{
//Normalize the normal
normal = normalize(normal);

//Compute the ambient light
float4 ambient = globalAmbient * material.Ka;

//Compute the emissive term
float4 emissive = material.Ke;

//Compute the attenuation function
float attenuation = attenuationFunction(position, light);

//Compute the diffuse term
float3 lightVector = normalize(light.position - position);
float diffuseLight = max(dot(normal, lightVector), 0);
float4 diffuse = attenuation * material.Kd * light.diffuseColor * diffuseLight;

//Compute the specular term
float3 viewVector = normalize(eyePosition - position);
float3 halfAngleVector = normalize(lightVector + viewVector);
float specularLight = pow(max(dot(normal, halfAngleVector), 0), material.shininess);
if(diffuseLight <= 0) specularLight = 0; float4 specular = attenuation * material.Ks * light.specularColor * specularLight; return ambient + emissive + diffuse + specular; }



I'm also attaching a zip file with some sample shaders using the library, and the rest of ogre related material files ------> Here

Check the effect (the light is attached to the camera)





1 comment:

Anonymous said...

I would like to exchange links with your site roimatola.blogspot.com
Is this possible?