Lighting
 Site Map Feedback

### Tutorial:

 ←Previous Index Next→
 Button Noise Wait Wall

In the last tutorial a simple lit sphere was developed. In this tutorial several lamp positions will be mixed and filtered to look like several specular light reflections.

Two lighting positions are added together and mixed with a hue to give an ambient shade to the sphere (1+2) and a further two are added as specular highlights (3+4).

1:This browser doesn't support the canvas element :-( 2: 1+2:
3: 4: 3+4:
1+2+3+4: Hue+Highlights
As with all of these tutorial pages, you can see how the images are drawn by viewing the source for this page on your browser.

Each lighting position has two numbers that get adjusted. One dims the result (a simple division to make the parameter smaller), the other filters the result to select a particular size of white blob. Since white areas are being selected, a filter that takes the top fifth, for example, makes any pixel with a lower value black and re-shades that top fifth to spread from zero to one. The circle created from the `Upper` function that was introduced before, is a little too linear to look realistic, so the result is cubed to create a bright middle with plenty of dimmer edge to blend with the adjacent circle in a slightly modified function:

```function Upper3(n,t) {return t<(n-1)/n ? 0 : Math.pow((t-(n-1)/n)*n,3);} // if n=5, the upper fifth is spread out to [0,1]. That result is then cubed and returned.
```
Using these functions it is easy to select a good-looking circle-size by altering the parameter that creates the fraction to keep.

The code that generates the sphere is fairly short:

```var Specular=0;
var  Ambient=0;
function GetSphereZ(x,y) {return Math.sqrt(Math.abs(1-x*x-y*y));}
function GetGlassColor(x,y) { // x,y vary over the interval [0,1]
var  z=GetSphereZ(x,y);
var s1=Upper3( 5,Unsigned(( 2*x    +6*z)/ 7  )); // take the Upper fifth and spread it
var s2=Upper3( 3,Unsigned((   x+4*y+6*z)/ 8.5)); // take the Upper third and spread it
var s3=Upper3(15,Unsigned((-6*x-3*y+9*z)/11.7));
var s4=Upper3(17,Unsigned((-3*x-6*y+9*z)/11.3));
Ambient =s1+s2; // Minimise garbage collection by not returning these two as a single object.
Specular=s3+s4; // r=Ambient*r+Specular; g=Ambient*g+Specular; b=Ambient*b+Specular;
}
```

The code for this page draws all the monochrome drawings using the same function so you can play with the parameters and see how they effect the result. Since this process is developed by trial and error this page has been laid out to be experimented with. The next tutorial will blend the Wait/Loading animation with this 'sphere' as a background.