pub mod vec3; pub mod color; pub mod ray; pub mod sphere; pub mod hittable; pub mod hittable_list; pub mod rtweekend; pub mod camera; use std::{io::{BufWriter, Write}, fs::File}; use crate::{ color::*, sphere::*, rtweekend::*, hittable_list::*, vec3::*, ray::*, hittable::*, camera::*, }; fn ray_color(r: &Ray, world: &mut dyn Hittable, depth: i32) -> Color { let mut rec = HitRecord::new_empty(); // Limit the bounces if depth <= 0 { return Color::new(0.0, 0.0, 0.0); } if world.hit(r, 0.0, INFINITY, &mut rec) { let target = rec.p + rec.normal + random_in_unit_sphere(); return 0.5 * ray_color(&Ray::new(rec.p, target - rec.p), world, depth - 1) } let unit_direction: Vec3 = r.direction().unit_vector(); let t = 0.5 * (unit_direction.y() + 1.0); ((1.0 - t) * Color::new(1.0, 1.0, 1.0)) + (t * Color::new(0.5, 0.7, 1.0)) } fn main() { // Image let aspect_ratio: f64 = 1.0 / 1.0; let image_width: i32 = 512; let image_height: i32 = (image_width as f64 / aspect_ratio as f64) as i32; let samples_per_pixel: i32 = 100; let max_depth: i32 = 4; // World let mut world = HittableList::new_empty(); world.add(Box::new(Sphere::new(Point3::new(0.0, 0.0, -1.0), 0.5))); world.add(Box::new(Sphere::new(Point3::new(0.0, -100.5, -1.0), 100.0))); // Camera let cam = Camera::new(); // Render //let mut rng = rand::thread_rng(); let mut file = BufWriter::new(File::create("img.ppm").expect("File creation failed")); write!(file, "P3\n{image_width} {image_height}\n255").expect("Error while writing Magic Byte"); for j in (0..image_width).rev() { write!(file, "\n").expect("Error writing to File"); for i in 0..image_height { let mut pixel_color = Color::new(0.0, 0.0, 0.0); for _s in 0..samples_per_pixel { let u = (i as f64 + random_f64()) / (image_width - 1) as f64; let v = (j as f64 + random_f64()) / (image_height - 1) as f64; let r: Ray = cam.get_ray(u, v); pixel_color += ray_color(&r, &mut world, max_depth) } write_color(&mut file, pixel_color, samples_per_pixel); } println!("[ {:.2} % ]", (1.0 - ((j + 1) as f64 / image_width as f64)) * 100.0); } }