- Ray Tracing
- Raybench - Factor
- Sharing Memory With WebAssembly
- Ray Casting
- Fast Canvas Drawing
- Back to basics - Binary search
- Back to basics - Bubble sort
- Remote machine development
- WebAssembly In The Browser
- WebAssembly Brief Intro
Full disclosure, I won't be explaining how the ray tracing algorithm works in detail, you can go to this wikipedia article to learn more. Maybe some day I'll do an in-depth explanation, but that is not today.
In this article I want to focus on a very simple thing: modifiying the ray casting algorithm to support simple ligthing, and thus, converting it in a very basic ray tracing implementation.
This whole implementation is based on the previous ray casting article, not all the code is visible or editable, but you can see it if you choose to look at this page's source. Only the code that needs to be modified is going to be shown in code editors.
The first code that needs updating is
createScene, we want to add an sphere, and a point light. Point lights as their name implies, is just a single point in 3D space that emits light.
To calculate the light that incides in a sphere, we need first to know the normal of the surface at the point that the ray intersected, this is easily calculated as substracting the point the ray hit the sphere from its center.
The normal of the intersection point is included as part of the hit structure, so it will allow us to calculate the angle of incidence of ligth.
To approximate the amount of light that reaches the hit point, the next step is to add a new shading function.
The shading function calculates how much light reaches the point, if at all. This function is used in the
generateBitmap function to apply shading for each pixel where an object has been found.
There are more nuisances to physical accurate lighting, for now, we only use the angle of indicende to apply lighting to the found surfaces. Another simple change that can be included later is to add intensity to the point light so it will illuminate less the farther the surface is.
This ray tracing implementaiton, as shown, is a very simple update to the ray casting algorithm that generates a nice shading effect on the objects in the scene.
You can play around with the scene, add lights and more spheres, it only gets more interesting from here.