1. Home
  2. Explore
  3. Computer Science
  4. Ray Tracing Basics

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Ray Tracing Basics

Speaker 1Speaker 2

Ray Tracing Basics

20:46
0:00-20:46
  1. Maria

    Hello everyone, and welcome back to Coding Adventures! Today, we're diving into the fascinating world of ray tracing. Hope, I know you've played with ray matching before, so you've got some background, right?

  2. Hope

    That's right, Maria! I've dabbled a bit, mainly with the conceptual side, but I'm really excited to get into the nitty-gritty today. I've been doing some reading myself, going through the 'Ray Tracing in One Weekend' trilogy and some great blog posts on path tracing.

  3. Maria

    Excellent! I'm planning to build this inside a game engine, which is super convenient. It gives us a pre-setup scene view where we can easily place and move objects around. Plus, we can compare our fancy ray-traced renders with the engine's built-in renderer.

  4. Hope

    That's a smart approach. To ensure a fair comparison, we'll need to match the game camera's perspective. I've quickly drafted some code to visualize the projection plane and how the field of view, camera movement, and rotation affect it. It's essentially a grid of points that update correctly.

  5. Maria

    That's a great start. So, by calculating the height and width of the projection plane using the field of view and aspect ratio, we can then transform each grid point to the camera's respective position and orientation. This allows us to visualize the rays we'll be shooting out into the world.

  6. Hope

    Exactly. Now, this might seem counter-intuitive because in reality, light comes from sources and bounces into our eyes. But that's incredibly inefficient for rendering! Most light would miss our eyes. So, we're doing it 'ancient Greek style' and shooting rays out of our virtual eyes instead.

  7. Maria

    Yes, only the rays that hit a light source contribute to the image, which is far less wasteful. We'll be sending out millions of these rays, which sounds like a job for the GPU. I've set up a Ray Tracing Manager script to send camera info to a shader and draw the results.

  8. Hope

    Perfect! So, whatever we put into this shader will be drawn to every pixel on the screen. For instance, returning red gives us a red screen. Crucially, we have the pixel's coordinates. So, returning the x-coordinate gives a horizontal gradient, and the y-coordinate a vertical one.

  9. Maria

    Right. I've added code using those coordinates and camera info to calculate the pixel's position on the projection plane, essentially doing what we did earlier but with matrix multiplication. I've also defined a ray structure with an origin and direction, like we calculated before.

  10. Hope

    Let's visualize that direction as a color to double-check. Positive X should be red, positive Y green, and positive Z blue. Looking around, it all seems correct. The octant where all axes are negative appears as a black void, so everything's checking out.

  11. Maria

    Great! Our next step is drawing spheres. While most 3D graphics use triangles, a simple mathematical representation for spheres is much more accurate and efficient. The equation for a sphere centered at zero is X squared plus Y squared plus Z squared equals the radius squared.

  12. Hope

    To figure out if a ray intersects, we say it starts at the ray origin and moves along the direction for some distance. When the squared length equals the squared radius, we've hit it. Solving for distance, if the part under the square root is negative, the ray misses. Zero means it touches, and positive means two intersection points.

  13. Maria

    I've created a 'hit info' structure that tells us if a ray hit something, its distance, position, and the normal vector. The normal vector is crucial for knowing which way is 'up' on the surface, which will be helpful for bounces. To handle spheres with different positions, we can conceptually move the ray instead of the sphere.

  14. Hope

    Let's quickly edit our shader to check if a ray hits a sphere at the scene's center with a radius of one, returning white or black. And it looks pretty spherical! Now, for multiple spheres, I've created 'Ray Tracing Material' for color and a 'Sphere' structure for position, radius, and material.

  15. Maria

    This sphere information gets sent to the shader into a buffer, which our 'Ray Collision' function uses. It loops through each sphere, performs the intersection test, and keeps track of the closest hit, including the object's material. We can then replace our single sphere check with this new function and return the hit object's color.

  16. Hope

    Perfect! Back in the scene, we should now see all three spheres in their correct places. Setting colors works, and importantly, nearby objects appear properly in front of distant ones, which confirms our depth calculations are behaving as expected.

  17. Maria

    Excellent. Now, these balls are looking a bit bland, so let's add some basic lighting. When a ray of light hits a surface, the outcome depends on the material. A smooth surface causes specular reflection, where the light bounces off at the same angle it came in.

  18. Hope

    Whereas a rougher material causes diffuse reflection, scattering light in many directions. We'll focus on diffuse for now, where the ray bounces off completely randomly. I've made a test shader to figure out random numbers, using a pixel index as a seed.

  19. Maria

    So, each pixel has a unique value we can use as a seed for pseudo-random numbers. I'm experimenting with a 'random value' function that takes a seed and transforms it. I'm hoping multiplying by a large number and squaring it will overflow, making the remainders appear random when scaled between zero and one.

  20. Hope

    That's an interesting approach, but my first attempt with simple multiplication and squaring didn't look very convincing, just a funky pattern. I've been trying different random multiplications behind the scenes. My latest attempt, multiplying the seed by itself with some random offsets, actually looks reasonably random.

  21. Maria

    That's progress! To generate multiple values per pixel, we just add an 'inout' argument to the seed, so each call gets a different result. It's been fun experimenting, but I'll replace this with some well-tested code I found online to get us back on track for reliable random numbers.

  22. Hope

    With random numbers sorted, we need random directions, which means generating random points on a sphere's surface. My current simple approach is to generate three random values between -1 and 1, creating a point inside a cube. We keep generating until the point is inside a sphere, then normalize it to get our direction.

  23. Maria

    Be careful with those 'while true' loops, Hope! They can lead to crashes or interesting screen effects. I've had issues with them not clearing the screen. After a restart, I tracked down a bug and added a loop limit for safety. I was curious how bad it would look without the loop, just using the first random point.

  24. Hope

    And it clumps up near the cube's corners and edges, as expected. So, we won't be doing that! I've also come across an alternative approach: instead of uniform random numbers, we use numbers from a normal distribution. I found some code for that.

  25. Maria

    Ah, yes, normal distribution. For mathematical reasons I don't fully grasp, this distributes points uniformly randomly over the sphere's surface. On my computer, this approach was significantly faster for the GPU. I'm sure faster methods exist, but this is good for now.

  26. Hope

    Great! With random directions working, we need to consider that when a ray hits a surface, we want it to bounce in a random direction within the hemisphere oriented around the surface's normal vector. If our generated direction rudely points outside, we can detect it with a dot product.

  27. Maria

    If the dot product between the normal and random direction is negative, they're more than 90 degrees apart, so we simply invert the random direction. Just like that, it's back in the right hemisphere. I've made a tiny function for this and a quick test to verify it works as expected.

  28. Hope

    Excellent, I think we're finally ready to integrate all this into our ray tracer! I've created a function that takes a ray from the camera and traces its path as it bounces randomly through the scene, hopefully reaching a light source. It's quite simple.

  29. Maria

    It sounds like it. So, you check what the ray collides with, move the ray to the intersection point, and then pick a random direction for it to bounce off in. This repeats until the maximum bounce limit is reached, or the ray misses everything and goes into empty space, breaking the loop.

  30. Hope

    Precisely. Now, we need to figure out how much light the camera receives. I've created a 'Ray Color' variable, starting as pure white. When the ray hits something, we multiply 'Ray Color' by the object's material color. If an object absorbs all light, like a black material, 'Ray Color' becomes zero.

  31. Maria

    So 'Ray Color' tracks how incoming light is affected. We also need a variable for the light encountered, starting at zero. When an object is hit, we calculate its emitted light using new 'emission color' and 'strength' properties. This emitted light is added to the total incoming light, tinted by the 'Ray Color'.

  32. Hope

    Exactly. At the end, we return the accumulated light. It might seem backward because we're tracing from the camera, but it's more efficient. Our shader now calculates a random seed, creates a ray from the camera, and traces its path to determine the pixel color.

  33. Maria

    To test this, I've set up a simple scene: a bunch of small balls on one very large ball. Let's enable ray tracing! Right now, it's a photorealistic rendering of a room without any light, which isn't very helpful.

  34. Hope

    No, not helpful at all! Let's select one of these dark balls, duplicate it, and open its material properties. I'll set its color to black, so it only emits light, not reflects it. Now, if we raise the emission strength, we can start to see some pixels of our scene.

  35. Maria

    Much better! I'll move this glowing ball far away and scale it up to be like a sun. At the moment, the bounce limit is set to one, meaning a ray has to hit an object and then directly bounce into a light source for a pixel to be illuminated.

  36. Hope

    Right. But if we raise the limit to two, we can see the back sides of these spheres now receiving indirect illumination. Each additional bounce has less and less effect, though. If I crank it up to 30, the difference is pretty subtle, but the image is extremely noisy.

  37. Maria

    The noise is a big issue. We're only sending out a single ray per pixel, but we need many more, bouncing around on their own random paths, and then averaging their contributions. I've modified the shader to loop many times, add up the incoming light, and output the average.

  38. Hope

    So, if we take our single ray per pixel and dial that up to 100, it looks much better than just one ray, but still quite noisy. We could go even higher, but performance struggles to reach 60 frames per second with just a few spheres, which is a bit pitiful.

  39. Maria

    True, for today, real-time isn't the goal, but I don't want to slow down the editor too much. So, let's keep the rays per pixel low, but average the result over multiple frames to improve quality over time. This means combining the previous frame with the new render.

  40. Hope

    And for that to work, the rays need to bounce differently each frame, so we'll modify our random number seed by adding the current frame number to the pixel index and multiplying by a large number. Let's hope for the best!

  41. Maria

    Okay, trying it out, clearly, we can't have objects moving every frame or it turns into a smudgy mess. But conceptually, it seems to be working. Before testing it properly, I want to modify our 'Trace' function so that when a ray misses everything, it gathers some background environment lighting instead of just going into the void.

  42. Hope

    That's a good idea for realism. I've made a simple function that blends between a ground color and two sky colors based on the ray's vertical direction. It also adds a little sun circle based on a given light direction. It's nothing fancy, but nicer than pure blackness.

  43. Maria

    It definitely looks better. We can change the sun's direction, and at some point, I'd love to integrate atmosphere rendering for sunsets. But this will do for now. Let's render this scene and see how the image becomes less noisy over time.

  44. Hope

    It's improving, but I'm still not quite happy. Let's reconsider what happens when a ray hits a surface. Light comes in from all directions, and we're estimating how much randomly bounces towards the camera. Imagine a light beam hitting a surface straight down versus at an angle.

  45. Maria

    Yes, if it hits at an angle, the light spreads out more, meaning each point on the surface receives weaker light and should contribute less to the pixel's illumination. So, in our 'Trace' function, we should calculate the light strength as the cosine of the angle between the surface normal and the light direction.

  46. Hope

    And then we multiply the ray color by this light strength. This will halve the received light, so as a quick hack to maintain brightness for comparison, I'll multiply by two. Here's a render before and after this cosine weighting, and I think it looks much nicer.

  47. Maria

    It definitely adds more realism. Let's quickly compare it to the built-in renderer. It's not a fair comparison, given the speed difference, but it helps us appreciate the subtle details our raytracer captures, like the extra darkness beneath the spheres, making them look physically grounded, or that faint red light bouncing off the white ball.

  48. Hope

    Those details are what make it special. I want to go back to our 'Trace' function quickly. Through some math I don't fully understand, it turns out we can remove that light strength calculation if we tweak how we calculate random bounce directions. We can use a cosine-weighted distribution.

  49. Maria

    So, instead of uniformly distributed bounces, we have a cosine-weighted distribution. This sends fewer rays in directions that contribute less light and more in directions that contribute more. The end result is the same as the light strength calculation, but we get there a bit faster. Clever!

  50. Hope

    Exactly. I think we've spent enough time on these spheres. Let's move on to triangles! Here's the code for calculating ray-triangle intersection. Prepare yourselves for this beauteous creation!

  51. Maria

    Okay, maybe it doesn't look that exciting visually, but from humble triangles, we can build anything. I've been modeling a low-poly chess knight in Blender, made from 456 triangles. That might be taxing on our raytracer, but we'll see!

  52. Hope

    That's a good challenge! I've added a buffer to the shader for all the scene's triangles and another buffer for mesh information, telling us where a mesh begins in the triangle list and how many triangles it contains. Then, I updated the 'recollision' function.

  53. Maria

    And that 'recollision' function is essentially identical to how we handled spheres, just testing if the ray hits any triangle and storing the closest hit information, along with the material. Before checking all triangles, it quickly tests the object's bounding box for a tiny optimization.

  54. Hope

    Right. I'll set up a simple Cornell box scene now – a little room with different colored walls. Let's bring in the knight and give it a plain white color to see how it interacts. I can already tell the editor is lagging due to the inefficient ray tracing code.

  55. Maria

    Yes, it's quite laggy. Let's drop the number of rays all the way down to one per pixel for now. We'll have to optimize this at some point. To finish the room, I'll add a front wall using a quad mesh, so it's invisible from the back, allowing us to see inside.

  56. Hope

    Now the room is completely dark, so the sun is pointless. Let's duplicate the ceiling, scale it down, and use it as our light source instead. Let this render for a bit, and we can gradually see our majestic knight emerging from the noise.

  57. Maria

    It's beautiful! You can see the lovely bounce lighting – a red tint on one side, blue shading on the other, and even some green along the base from the floor. It's so interesting how the light interacts. If we only allow one bounce versus two, or back to ten, the difference is clear.

  58. Hope

    Indeed. Let's try it with another model. I'll bring in Suzanne, the Blender monkey, to pose for us. This is excruciatingly laggy, so I'll disable the raytracer while setting up the scene. And there she is! Looking pretty good.

  59. Maria

    But I know what you're thinking, Hope: what if Suzanne entered the Avatar stage and lit the room with her glowing eyeballs? There you go! I've been trying to optimize the rendering behind the scenes, and I did manage to speed things up dramatically.

  60. Hope

    The only downside is that Suzanne now looks like... well, like this. I'm torn, it's much faster, but I think I'll have to revert those changes. Let's move on to specular reflections now, where light bounces off a very smooth surface like a mirror, with the same angle going out as coming in.

  61. Maria

    Right, a perfect reflection. This can be calculated using the normal vector and the incoming direction. In our 'Trace' function, we calculate the diffuse direction, and now we'll also calculate the specular direction using a built-in 'reflect' function.

  62. Hope

    Then, the ray's new direction can blend from diffuse to specular based on a 'smoothness' property I've added to the material. Let's try it out. I've placed a few spheres in our test chamber. Let's see how they look initially.

  63. Maria

    Okay, now let's make them shiny. I'll set the smoothness on the first one to around 0.4, then the next to 0.6, then 0.8, and the last one all the way up to 1. So, here's what we had before, and now with our new specular reflections.

  64. Hope

    As expected, it goes from very blurry reflections on the left to a nice, crisp mirror on the right. I want to play with this a bit more. I've set up a similar scene with two large balls, making both fully reflective. Since they're opposite, we can see infinite reflections.

  65. Maria

    That's a classic ray tracing effect! I've animated the balls to move forwards until they're just touching, giving us some beautiful infinite reflections. I want to try one last reflection test with our little horse now.

  66. Hope

    Currently, the scene is pretty dull. Let's spice it up by making this wall a mirror. Then, the wall opposite it reflective as well, but with a smoothness just under one, so reflections get slightly blurrier with each bounce, which I think looks nice.

  67. Maria

    Why stop there? Let's make the red wall reflective, and the blue wall too. Next, the ceiling and the floor. And finally, we might as well make the horse reflective too. Truly an artwork for the ages! But what's going on with a tomato?

  68. Hope

    Ah, the tomato dilemma! A red tomato has white specular highlights, the color of the light hitting it, not tinted red. But in our ray tracer, a shiny red object has red specular highlights. It seems intuitive, but it's not quite right for a tomato.

  69. Maria

    It turns out fruits have a transparent protective coating. When light hits it, some passes through and scatters diffusely, but some also bounces off the smooth coating, giving those untinted reflections. The same applies to many materials like varnished wood.

  70. Hope

    So, in our 'Trace' function, let's determine if the current ray should bounce off an imaginary coating by checking a new 'specular probability' property against a random value. If it's not a specular bounce, the diffuse direction is used.

  71. Maria

    And we can use this information to select between the material's regular color and its specular color, which will probably just be white most of the time. To see this, I'm taking our four balls from earlier and making them all totally smooth.

  72. Hope

    But now we can say that smoothness only applies some of the time. I've set up some probabilities, and let's see how that turns out. I'd say that's looking pretty good, but for the real test, let's try it on our tomato ball.

  73. Maria

    At the moment, it looks like some strange kind of metal. But now, using our new settings, we can make something like this, which definitely feels a lot more tomato-ey! Okay, there are still so many things I want to experiment with.

  74. Hope

    Let's end today with depth of field. The basic idea is choosing a distance where things are in focus, and outside of that, they're blurry. Going back to how we calculate ray directions for each pixel, we're currently sending multiple rays, but they all start from the same position and go in the same direction.

  75. Maria

    So, it just looks like a single ray. To make things blurry, we need to make the rays diverge a little, so they head out in slightly different directions. In the code, where we send out all the rays for the current pixel, we'll move the ray setup inside the loop.

  76. Hope

    That way, we can make each ray slightly different by randomly nudging the viewpoint. To do that, I want to generate a random point inside a circle. Here's a little function that calculates a random angle, converts it to a point on the unit circle using sine and cosine, and scales it down by the square root of a random value.

  77. Maria

    The square root ensures the points spread out nicely inside the circle instead of clustering towards the center. So, we'll take that random vector, multiply it by a new 'strength' setting, and use that to create a new viewpoint that lies somewhere inside a circle around the original viewpoint, plugging it into our direction calculation.

  78. Hope

    That's not working at all! Apparently, I'm making up variables. After consulting matrix documentation for syntax, I've extracted the missing camera directions for offsetting the viewpoint. The code should compile now.

  79. Maria

    Great! I've set up a little test scene. Let's try increasing the size of that random circle using the 'strength' setting. It seems to be making things blurry, but it's also extremely noisy, as usual. Let's render it quickly.

  80. Hope

    Of course, this makes everything blurry, and we can't focus on anything, so we'll need adjustments. But it's a start. If we turn this off quickly, something it could already help with are the jagged edges due to the limited pixels. Setting the blur strength extremely low will help smooth these edges, giving us nice anti-aliasing.

  81. Maria

    That's a clever use of it. I made a little render to test this, and the edges are looking pretty smooth. Okay, so we can make things blurry, but we still need to figure out how to focus at a particular distance. What if, instead of randomly offsetting the viewpoint, we randomly offset the ray origin instead?

  82. Hope

    That would give us something where all the rays converge on the viewpoint. So, if we have a model, and we bring it over here, the rays will hit it at a bunch of different spots, giving a blurry result for the current pixel. But if the model moves further back, all the rays will hit the same point, and it'll be in focus.

  83. Maria

    Right, and if the model moves even further back, past this focal plane, it will start getting blurry again. So, to control what's in focus, we simply adjust the distance of this plane. In the code, let's keep our old approach for anti-aliasing.

  84. Hope

    And then we can calculate another random vector using our 'point in circle' function again, and use that to offset the ray origin. That's actually all we need to do, I think, because changing the focus distance is already handled by the Z component of these view parameters.

  85. Maria

    Perfect! To test this, I've set up a slightly larger scene. Let's play around a bit. I'll try setting the defocus strength to 2, which doesn't seem to have done much, so let's try 20, or maybe even 200.

  86. Hope

    Okay, that's made everything super blurry! Now, let's play with the focus distance. I'll turn on this visualization I added and try shifting the plane all the way back to the same depth as the knight. As we'd expect, the knight seems pretty sharp, while the pawns in the foreground are still very out of focus.

  87. Maria

    That's looking great! I want to see this with less noise, so I'm temporarily cranking the number of rays up from 3 to 30. My computer is dying, but I think it looks really nice! Okay, I'll turn that back down again.

  88. Hope

    And let's try bringing the foreground into focus now. We can also see how that looks with more rays. This seems to be working quite well! I'll do one last render to test it. Here we have the king and queen in focus, and now I'll animate the focus plane shifting out to highlight the knight.

  89. Maria

    That's a fantastic effect! There are still so many things I want to do, like rendering objects made from glass, adding volumetric effects, and of course, improving performance for more complex scenes. But we've covered a lot of ground today.

  90. Hope

    Absolutely, Maria. We've certainly scratched beyond the surface this time. I hope everyone enjoyed this deep dive into ray tracing. Until next time, cheers!

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent