Brandon Eleuterio

Articles

Learning Rust – Part 3: Rays, Camera, Background

Brandon Eleuterio

In Part 1, I created my first image – a rainbow square. Part 2, involved refactoring code and creating a new struct for handling colors, vectors, and points. In Part 3 I start using some algebra and actually build the ray tracer.

The magic of 3D

Rays are lines defined with a starting point, a direction, and an intersection point if there is an image in their path. The starting point is called the camera, the perspective through which you view the image. Rays are a tool used to add effects to 2D images like lighting and shadow to make them look 3D. Here’s a nice visual I found:

Source: What is Ray Tracing?

The “rasterization” mentioned above refers to an older image rendering technology used in some computer games.

Coding Challenges

  1. Rust variables are constants or immutable by default. This is the opposite of C++.
  2. Borrowed references in Rust – indicated by the ‘&’ character – essentially take the place of pointers and references in C++.
  3. The Rust compiler is very helpful if you actually pay attention to what it tells you.

This essentially means I’ve poured many teaspoons of ampersand sugar over my cornflake code to appease the compiler. For example:

let r = Ray::new(
    &origin,
    &(&(&((&lower_left_corner) + &(u * &horizontal)) + &(v * &vertical)) - &origin),
);

The Resulting Rectangle

The new ray casting code generates a rectangle with blue and white tastefully blended together:

Blue and White Rectangle

While this rectangle may only seem marginally better than the original rainbow square, it’s actually much better. Trust me!

Moving On

As always, my code is on Github, and here is the online book I’m following. Next up, drawing a sphere!

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top