Sunday 5 August 2018

HLSL tutorial : Create spot light


This article is about how to implementing spot light in HLSL.

Understanding

Attenuation
Different light type has different light attenuation.  Attenuation is describing how light intensity is falloff relate to angle / position and so on.

Inner corn  &  Outer corn 
A spot light has two major parameters that make it different from other kind of light. Inner corn and outer corn. They are shown as 2 yellow corns in the image. 

Corn Attenuation
light inside the inner is 100% intensity.
light get dimmer as it  get closer to the outer corn. 
light get 0% intensity when out of the outer corn.

Math

mapping the range
when doing mapping, 0 is a very important value. Because 0 scale by any value is zero. This will give you a point on the chart that will not move.

to achieve the corn Attenuation, we need a function that take angle (0~Pi) as input and turn it to attenuation (0~1)

The best way to do it is use cos. This map the input from (0~Pi) to (1~0)

Given the target angle is  : Theta
Now we have : Cos(Theta)

When Theta is larger than Out, we want the result to be 0. We achieve this by moving the curve down by Out.

Now we have : Cos(Theta)-Cos(Out)

The next step is quite obvious, we scale the curve up . The scale factor will be 1/(cos (In) - cos(Out)). Because we want the Cos(In) to be one. Then we can saturate the number to get the range we want. 

calculate Cos(Theta)
As can be seen , given the factor that the Light vector and Light to vertex vector is normalized, cos(Theta) = ab / 1. and ab is the projection of Light to vertex vector on light vector, which is dot(light to vertex , light direction). 

Implimentation
As we know all the math by now,  the implementation is quite straight forward : 


you can check the source code here

A test rendering:


As can be seen the bunny is dimmer when they are further away from the center




No comments:

Post a Comment