Ray-Cast Ambient Occlusion

In this example, we begin by creating a variable for position - offsetting it from the surface very slightly to avoid unintended ray intersections.

Once we have assigned how many samples we want, and the hemispherical radius of our ambient occlusion (which determines how close geometry has to be to occlude), we use a for loop to iterate over each sample.

We then generate a random hemispherical direction using our point normal, and use that directional vector as the ray. If our ray hits geometry, its distance from initial position is fit within a 1-0 range - 1 being the closest a ray could possibly be, and 0 being the furthest.

This value is added and accumulated through the ‘ao’ variable, and then divided by the total number of samples added to the variable. We finally return the complement, in order to make close intersections dark, and distant rays / non intersections bright.