stocking

git clone https://git.bradleygannon.com/stocking.git
Log | Files | Refs

commit 3193d1343701297c741155d80e7e7a0106a0c1c8
parent 01ef5128cb055813bc648c8f36374f2a041c406e
Author: Bradley Gannon <bradley@bradleygannon.com>
Date:   Sat, 13 Dec 2025 15:48:28 -0500

Add a sphere

Complete Chapter 5

Diffstat:
Msrc/color.rs | 2+-
Msrc/main.rs | 13++++++++++++-
Msrc/ray.rs | 14++++++--------
Msrc/vec3.rs | 2+-
4 files changed, 20 insertions(+), 11 deletions(-)

diff --git a/src/color.rs b/src/color.rs @@ -1,6 +1,6 @@ use std::ops::{Add, Mul}; -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)] pub struct Color { red: f64, green: f64, diff --git a/src/main.rs b/src/main.rs @@ -4,6 +4,15 @@ mod color; mod ray; mod vec3; +fn hit_sphere(center: Vec3, radius: f64, r: Ray) -> bool { + let oc = center - r.origin(); + let a = r.direction().dot(&r.direction()); + let b = -2. * r.direction().dot(&oc); + let c = oc.dot(&oc) - radius * radius; + let discriminant = b * b - 4. * a * c; + discriminant >= 0. +} + struct Image { data: Vec<Vec<Color>>, } @@ -69,7 +78,9 @@ fn main() { pixel_origin + (i as f64 * pixel_delta_u) + (j as f64 * pixel_delta_v); let ray_direction = pixel_center - CAMERA_CENTER; let ray = Ray::new(CAMERA_CENTER, ray_direction); - let color = { + let color = if hit_sphere(Vec3::new(0., 0., -1.), 0.5, ray) { + Color::new(1., 0., 0.) + } else { let unit_direction = ray.direction().unit(); let a = 0.5 * (unit_direction.y() + 1.); (1. - a) * Color::new(1., 1., 1.) + a * Color::new(0.5, 0.7, 1.) diff --git a/src/ray.rs b/src/ray.rs @@ -1,20 +1,18 @@ use crate::vec3::Vec3; +#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)] pub struct Ray { - _origin: Vec3, + origin: Vec3, direction: Vec3, } impl Ray { pub const fn new(origin: Vec3, direction: Vec3) -> Self { - Ray { - _origin: origin, - direction, - } + Ray { origin, direction } } - pub const fn _origin(&self) -> Vec3 { - self._origin + pub const fn origin(&self) -> Vec3 { + self.origin } pub const fn direction(&self) -> Vec3 { @@ -22,6 +20,6 @@ impl Ray { } pub fn _at(&self, t: f64) -> Vec3 { - self._origin + t * self.direction + self.origin + t * self.direction } } diff --git a/src/vec3.rs b/src/vec3.rs @@ -3,7 +3,7 @@ use std::{ ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub}, }; -#[derive(Copy, Clone, Debug, Default)] +#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)] pub struct Vec3 { x: f64, y: f64,