Skip to content

Commit

Permalink
feat: implement shading with surface normals
Browse files Browse the repository at this point in the history
  • Loading branch information
alanjian85 committed Jul 7, 2024
1 parent 3c55a1b commit 418b912
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,22 @@ use indicatif::ProgressBar;
use nalgebra::{Point3, Vector3};
use ray::Ray;

fn hit_sphere(center: Point3<f64>, radius: f64, ray: &Ray) -> bool {
fn hit_sphere(center: Point3<f64>, radius: f64, ray: &Ray) -> Option<f64> {
let a = ray.dir.magnitude_squared();
let b = (-2.0 * ray.dir).dot(&(center - ray.orig));
let c = (center - ray.orig).magnitude_squared() - radius * radius;
return b * b - 4.0 * a * c > 0.0;
let discriminant = b * b - 4.0 * a * c;
if discriminant < 0.0 {
return None;
}
Some((-b - discriminant.sqrt()) / (2.0 * a))
}

fn ray_color(ray: &Ray) -> Vector3<f64> {
if hit_sphere(Point3::new(0.0, 0.0, -1.0), 0.5, ray) {
return Vector3::new(1.0, 0.0, 0.0);
let sphere_center = Point3::new(0.0, 0.0, -1.0);
if let Some(t) = hit_sphere(sphere_center, 0.5, ray) {
let normal = (ray.at(t) - sphere_center).normalize();
return 0.5 * (normal + Vector3::new(1.0, 1.0, 1.0));
}

let dir = ray.dir.normalize();
Expand Down
4 changes: 4 additions & 0 deletions src/ray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,8 @@ impl Ray {
pub fn new(orig: Point3<f64>, dir: Vector3<f64>) -> Self {
Self { orig, dir }
}

pub fn at(&self, t: f64) -> Point3<f64> {
self.orig + t * self.dir
}
}

0 comments on commit 418b912

Please sign in to comment.