WebGL illumination
In this illumination example, we are going to try to recreate this animation using pure WebGL and some primitives pre-defined to help us do the creation of the objects. You can find the complete source code HERE or watch the code running here:
We are not going to go over the creation of the Scene Graph or the creation of objects because we’ve already done that in previous examples in the blog. The thing we are going to focus is the process of creating the effect of lighting in the scene, according to day and night marked by the sun’s position and the lighting of a lightbulb and the car.
The most important thing that you need to know is that in order to play with the illumination effects, we just need to adjust the brightness of the colors in our scene gradually depending on various factors. These factors are the position of the sun, the direction of the car and the position of the lightbulb.
First of all, we need to define some things in the vertex shader and the fragment shader:
The important things come when we calculate the fragcolor attribute. We have to calculate it according to the vLighting variable passed down by the vertexShader to the fragmentShader. For every object we are going to draw we take into consideration their colors and the illumination in the moment. Depending on the illumination of the element, we increase or decrease the brightness of the color to make the effect happen.
Another important thing that we do is set apart the moments when we have the sun rising and when the sun is hidden in our world. This part can be found here:
As we can see, we rotate the sun according to the z axis and then ask ourselves if the sun y position is lower than 0. If it is, the sun is hidden and we progressively change it from bright yellow to gray. Then we set the variable isDay to false and we change progressively the multiplier variable of the vertex shader. This way we send the variable to the GPU and the colors of the scene are recalculated each frame.
Time Log
I estimated to do around 4 hours of work because it didn’t seem so hard to have illumination in the scene, but between setting up all of the objects and having the correct illumination angles, in addition to learning the concepts like ambient, spot and point lighting, I ended up working for 9 hours.