first normal shaded sphere
This commit is contained in:
25
src/main.rs
25
src/main.rs
@@ -9,24 +9,31 @@ use crate::{
|
||||
ray::*
|
||||
};
|
||||
|
||||
fn hit_sphere(center: &Point3, radius: f64, r: &Ray) -> bool {
|
||||
fn hit_sphere(center: &Point3, radius: f64, r: &Ray) -> f64 {
|
||||
let oc = r.origin() - *center;
|
||||
let a = r.direction().dot(&r.direction());
|
||||
let b = 2.0 * oc.dot(&r.direction());
|
||||
let c = oc.dot(&oc) - radius*radius;
|
||||
let discriminant = b*b - 4.0*a*c;
|
||||
|
||||
discriminant > 0.0
|
||||
if discriminant < 0.0 {
|
||||
-1.0
|
||||
} else {
|
||||
(-b - discriminant.sqrt()) / (2.0 * a)
|
||||
}
|
||||
}
|
||||
|
||||
fn ray_color(r: &Ray) -> Color {
|
||||
if hit_sphere(&Point3::new(0.0, 0.0, -1.0), 0.5, r) {
|
||||
return Color::new(1.0, 0.0, 0.0);
|
||||
let t = hit_sphere(&Point3::new(0.0, 0.0, -1.0), 0.5, r);
|
||||
|
||||
if t > 0.0 {
|
||||
let n = (r.at(t) - Vec3::new(0.0, 0.0, -1.0)).unit_vector();
|
||||
return 0.5 * Color::new(n.x() + 1.0, n.y() + 1.0, n.z() + 1.0);
|
||||
}
|
||||
|
||||
let unit_direction: Vec3 = r.direction().unit_vector();
|
||||
let t = 0.5 * (unit_direction.y() + 1.0);
|
||||
//println!("{}", t);
|
||||
|
||||
((1.0 - t) * Color::new(1.0, 1.0, 1.0)) + (t * Color::new(0.5, 0.7, 1.0))
|
||||
}
|
||||
|
||||
@@ -53,12 +60,10 @@ fn main() {
|
||||
|
||||
writeln!(file, "P3\n{image_width} {image_height}\n255").expect("Error while writing Magic Byte");
|
||||
|
||||
for j in (0..image_width).rev() {
|
||||
//println!("{}", j);
|
||||
//println!("Rows remaining: {j}");
|
||||
for j in 0..image_width {
|
||||
println!("Rows remaining: {}", image_width - j);
|
||||
write!(file, "\n").expect("grr");
|
||||
for i in (0..image_height).rev() {
|
||||
//println!("{}", i);
|
||||
for i in 0..image_height {
|
||||
let u: f64 = i as f64 / image_width as f64;
|
||||
let v: f64 = j as f64 / image_height as f64;
|
||||
let r = Ray::new(origin, lower_left_corner + u * horizontal + v * vertical - origin);
|
||||
|
||||
Reference in New Issue
Block a user