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

πŸ’‘ Ray Tracing Fundamentals & Implementation

This document explores the foundational concepts and practical implementation of a ray tracer within a game engine environment. It covers camera setup, object intersection (spheres and triangles), lighting models (diffuse and specular reflections), random number generation for physically based rendering, and advanced effects like depth of field.


πŸ“Έ Camera Setup & Ray Generation

To accurately render a scene, the ray tracer must simulate the perspective of a virtual camera. This involves calculating the projection plane and generating rays that originate from the camera and pass through each pixel.

πŸ“ Projection Plane Calculation

The dimensions of the projection plane are crucial for mapping screen pixels to world space.

  • The height of the projection plane is calculated using the camera's field of view (FOV) and basic trigonometry.

  • The width is then derived from the height and the aspect ratio of the display.

➑️ Visualizing Rays

A grid of points is generated on this projection plane. Each point is transformed according to the camera's position and orientation.

  • Ray directions are calculated from the camera's position towards each of these transformed points.

  • These directions can be visualized as arrows originating from the camera, representing the paths light would take to reach the sensor.

πŸ”„ Ray Tracing vs. Reality

  • In reality, light originates from sources, bounces off objects, and enters the camera. This is highly inefficient to simulate directly because most light rays miss the camera.

  • Ray tracing (or "ancient Greek style") reverses this: rays are "shot" out of the camera into the scene. Only rays that eventually hit a light source contribute to the final image, making the process much more efficient.


πŸ’» GPU Implementation & Shader Basics

Ray tracing involves sending out millions of rays, a task perfectly suited for parallel processing on the GPU. A Ray Tracing Manager script handles sending camera information to a custom shader and drawing the results.

🎨 Shader Operations

  • A shader is a program that runs on the GPU, executing code for every pixel on the screen.

  • Returning a color, e.g., red, fills the entire screen with that color.

  • Accessing pixel coordinates (e.g., x or y) allows for creating gradients, where values range from 0 (left/bottom) to 1 (right/top).

🌐 Calculating Pixel Position

  • The position of the current pixel on the camera's projection plane is calculated using its coordinates and the camera's information. This often involves matrix multiplication.

  • A Ray structure is defined, containing an Origin (the camera's position) and a Direction (calculated as described above).

🌈 Visualizing Ray Directions

  • The Direction vector can be visualized as a color, where X, Y, and Z components map to Red, Green, and Blue, respectively.

  • Looking along the positive X-axis shows more red, positive Y shows more green, and positive Z shows more blue.

  • Areas where all axes are negative (e.g., behind the camera) appear black.


🌐 Object Intersection: Spheres

For simple shapes like spheres, a pure mathematical representation is more accurate and efficient than using triangles.

πŸ§ͺ Sphere Equation

  • The equation for a sphere centered at the origin is x2+y2+z2=r2x^2 + y^2 + z^2 = r^2x2+y2+z2=r2, where rrr is the radius.

  • To handle spheres at different positions, the ray can be conceptually moved away from the sphere, keeping the sphere centered at zero for the calculation.

🎯 Ray-Sphere Intersection

  • A ray starts at an origin and moves along a direction for some distance.

  • Intersection occurs when the squared length of the ray's position equals the sphere's squared radius.

  • Solving for distance results in a quadratic equation.

    • If the discriminant (part under the square root) is negative, there are no real solutions, and the ray misses the sphere.

    • If it's zero, the ray touches the sphere at one point (tangent).

    • If it's positive, the ray intersects the sphere at two points.

πŸ“Š Hit Information

A HitInfo structure stores details about an intersection:

  • didHit: A boolean indicating if an intersection occurred.

  • distance: The distance from the ray origin to the intersection point.

  • position: The 3D coordinates of the intersection point.

  • normalVector: The vector perpendicular to the surface at the intersection point, crucial for lighting and reflections.

πŸ“¦ Handling Multiple Spheres

  • RayTracingMaterial: Stores properties like the object's color, emissionColor, emissionStrength, smoothness, and specularProbability.

  • Sphere structure: Holds position, radius, and material.

  • RayCollision function:

    1. Loops through all spheres in the scene.

    2. Performs an intersection test for each sphere.

    3. If a hit occurs, it checks if this is the **closest hit so far**.

    4. Updates the `HitInfo` with the closest intersection details and the `material` of the hit object.

  • This allows for rendering multiple spheres with different colors and ensures depth sorting (nearby objects appear in front of distant ones).


✨ Diffuse Lighting & Random Numbers

Making objects look interesting requires simulating how light interacts with their surfaces. Diffuse reflection is a common type of light scattering.

πŸ’‘ Diffuse Reflection

  • When light hits a rough material, it scatters in random directions. This is known as diffuse reflection.

  • For ray tracing, this means when a ray hits a surface, it should bounce off in a completely random direction.

🎲 Random Number Generation (RNG)

Generating pseudo-random numbers on the GPU for each pixel is essential for diffuse lighting.

  • A pixel index (a unique value from 0 to the total number of pixels) serves as a seed for the random number generator.

  • A randomValue function takes this seed and transforms it to produce a pseudo-random number between 0 and 1.

  • To generate multiple random values per pixel, the seed is modified within the randomValue function, ensuring subsequent calls yield different results.

πŸ”„ Generating Random Directions

Generating random directions is equivalent to generating random points on the surface of a sphere.

  • Rejection Sampling (Cube Method):

    1. Generate three random values (X, Y, Z) between -1 and 1, creating a point inside a cube.

    2. Keep generating points until one falls *inside* a unit sphere.

    3. Normalize this point to get a random direction on the sphere's surface.

    4. *Caveat*: This method can be inefficient and prone to infinite loops if not carefully implemented with loop limits. Points can also clump near cube edges if not properly normalized.

  • Normal Distribution Method:

    1. Generate random numbers using a **normal (Gaussian) distribution** instead of a uniform distribution.

    2. Using these values to generate a point results in a **uniform random distribution** of points over the sphere's surface (due to complex mathematical reasons involving probability). This method is generally faster for GPUs.

🌐 Random Directions in a Hemisphere

  • When a ray hits a surface, we want it to bounce randomly within a hemisphere oriented around the surface's normal vector.

  • To ensure the random direction is within the correct hemisphere:

    1. Calculate the **dot product** between the surface normal and the generated random direction.

    2. If the dot product is **negative** (meaning the angle is greater than 90 degrees, pointing away from the hemisphere), **invert** the random direction.


πŸšΆβ€β™‚οΈ Ray Path Tracing & Light Accumulation

The core of the ray tracer involves tracing the path of a ray as it bounces through the scene, accumulating light along its journey.

πŸ›€οΈ Trace Function

This function takes an incoming ray and simulates its path:

  1. Collision Detection: Uses the RayCollision function to find what the ray hits.

  2. Bounce: If it hits something:

    • The ray's origin is moved to the intersection point.

      • A random direction is picked for the ray to bounce off in (diffuse reflection).

  3. Looping: This process repeats until:

    • A maximum bounce limit is reached.

      • The ray misses everything and shoots into empty space.

πŸ’‘ Light Accumulation

  • rayColor: Starts as pure white. Whenever the ray hits an object, rayColor is multiplied by the object's material.color. This simulates how light is absorbed or reflected by objects (e.g., a black object absorbs all light, making rayColor zero).

  • incomingLight: Starts at zero.

    • When a ray hits an object, the object's emitted light (material.emissionColor * material.emissionStrength) is calculated.

    • This emitted light is added to incomingLight, tinted by the current rayColor (representing the colors of all objects the ray has encountered so far).

  • The Trace function returns the total incomingLight accumulated along the path.

πŸ–₯️ Shader Integration

  • The main shader code calculates a random seed for the current pixel.

  • It creates a ray originating from the camera.

  • It calls the Trace function to determine the pixel's color.

🌍 Environment Lighting

  • When a ray misses all objects, instead of returning black, it can gather background environment lighting.

  • A simple function can blend between ground and sky colors based on the ray's vertical direction, and add a sun disc based on a light direction.

β˜€οΈ Cosine Weighting for Diffuse Surfaces

  • When light hits a surface at an angle, it spreads out more, resulting in weaker illumination per point. This is accounted for by multiplying the light strength by the cosine of the angle between the surface normal and the light direction.

  • Alternatively, this light strength calculation can be removed if the random bounce directions are generated with a cosine-weighted distribution instead of a uniform distribution. This means more rays are sent in directions that contribute more light, achieving the same physical accuracy more efficiently.


πŸ–ΌοΈ Addressing Noise & Performance

A common problem in ray tracing, especially with diffuse lighting, is noise in the image, which arises from sending out too few rays.

πŸ“‰ Single Ray per Pixel

  • Initially, only a single ray is sent out per pixel. This leads to extremely noisy images, especially with random bounces.

⬆️ Multiple Rays per Pixel (Sampling)

  • To reduce noise, the shader can loop multiple times per pixel, sending out many rays.

  • Each ray follows a different random path.

  • The incomingLight from all these rays is summed up, and the average is output as the pixel's color.

  • While this improves quality, it significantly impacts performance.

🎞️ Averaging Over Multiple Frames (Temporal Accumulation)

  • To improve quality over time without a massive immediate performance hit, the results from the current frame can be averaged with the previous frame's render.

  • This requires the random number seed to change with each frame (e.g., by adding the current frame number to the pixel index) to ensure rays bounce differently.

  • Caveat: This approach is unsuitable for scenes with moving objects, as it leads to "smudgy" trails.


πŸ”Ί Object Intersection: Triangles

While spheres are simple, most complex 3D models are built from triangles.

🧩 Triangle Representation

  • A buffer in the shader holds all the triangles in the scene.

  • Another buffer stores information about each mesh, indicating where its triangles start in the main triangle list and how many it contains.

πŸ“ Ray-Triangle Intersection

  • The RayCollision function is extended to handle triangles.

  • It iterates through the triangles of each mesh.

  • For each triangle, it performs an intersection test.

  • Before checking individual triangles, an optimization is used: testing if the ray intersects the object's bounding box. If it doesn't, all triangles within that object can be skipped.

πŸ›οΈ Cornell Box Example

  • A classic test scene, the Cornell Box, is used: a simple room with colored walls (red, blue, green, white).

  • This helps visualize bounce lighting: light from a white light source will pick up the color of the walls as it reflects, creating subtle color tints on other surfaces.


🌟 Specular Reflections & Materials

Beyond diffuse scattering, surfaces can also exhibit specular reflections, like mirrors.

πŸͺž Specular Reflection

  • On a smooth surface, light bounces off perfectly, with the angle of incidence equaling the angle of reflection.

  • The reflection direction can be calculated using the surface's normalVector and the incomingDirection of the ray.

  • A smoothness property is added to the material, ranging from 0 (fully diffuse) to 1 (perfectly specular). The ray's new direction is a blend between the diffuse and specular directions based on this smoothness.

  • Higher smoothness values result in crisp, mirror-like reflections, while lower values produce blurry reflections.

♾️ Infinite Reflections

  • When two fully reflective surfaces face each other, they create infinite reflections, where each surface reflects the other, and that reflection contains a reflection of the first, and so on. This is naturally handled by the recursive nature of ray tracing.

πŸ… Specular Tinting (Fresnel Effect)

  • Real-world objects like tomatoes (or varnished wood) have a transparent protective coating.

  • When light hits this coating, some of it is specularly reflected (untinted, reflecting the light source's color), while some passes through to be diffusely scattered by the object's underlying color.

  • To simulate this:

    • A specularProbability is added to the material.

    • A random value is compared against this probability to decide if the current bounce is specular or diffuse.

    • If it's a specular bounce, the ray's color is multiplied by the material's specularColor (often white); otherwise, it's multiplied by the regular color.

    • This allows for untinted specular highlights on colored objects, making them appear more realistic.


🌫️ Depth of Field (DoF)

Depth of field creates a photographic effect where objects at a certain distance appear in focus, while objects closer or farther away are blurred.

🎯 Basic Idea

  • Instead of all rays for a pixel starting from the exact same camera position and going in the exact same direction, they are made to diverge slightly.

  • This divergence is achieved by randomly nudging the ray's origin within a small circle around the original viewpoint.

β­• Generating Random Points in a Circle

  • A function generates a random point inside a circle:

    1. Calculates a random angle.

    2. Uses sine and cosine to convert the angle to a point on the **unit circle**.

    3. Scales this point down by the **square root** of another random value to distribute points uniformly *inside* the circle (without the square root, points would cluster towards the center).

  • This random vector is scaled by a defocusStrength setting.

  • This new, randomly offset viewpoint is used to calculate the ray's direction.

🌫️ Blurring & Anti-Aliasing

  • Increasing the defocusStrength makes everything blurry.

  • Setting defocusStrength to an extremely low value can help smooth out jagged edges (aliasing) by making the rays diverge just enough to sample slightly different sub-pixel areas.

πŸ”­ Focusing at a Distance

  • To achieve a specific focal distance, instead of randomly offsetting the viewpoint, the ray origin is randomly offset.

  • These offset rays are then directed to converge at a specific point on a "focal plane."

  • Objects on this focal plane will appear sharp, as all rays for a pixel will hit the same point on the object.

  • Objects in front of or behind the focal plane will appear blurry, as the diverging/converging rays will hit different points on them.

  • The focus distance is controlled by the Z-component of the camera's view parameters.


πŸš€ Future Enhancements

The current ray tracer provides a solid foundation, but many advanced features and optimizations can be explored:

  • Glass objects: Implementing refraction and transparency.

  • Volumetric effects: Simulating fog, smoke, or clouds.

  • Performance improvements: Optimizing intersection tests (e.g., using spatial data structures like BVH or Octrees) to handle more complex scenes in real-time.

  • Atmosphere rendering: Integrating more sophisticated sky and sun models for realistic sunsets and environmental lighting.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent