@@ 9,16 9,16 @@ pub struct HittableList {
}
impl HittableList {
- fn empty() -> Self {
+ pub fn empty() -> Self {
HittableList{ objects: vec![] }
}
- fn clear(&mut self) {
+ pub fn clear(&mut self) {
self.objects.clear();
}
- fn add(&mut self, object: &Arc<dyn Hittable>) {
- self.objects.push(object.clone());
+ pub fn add(&mut self, object: Arc<dyn Hittable>) {
+ self.objects.push(object);
}
}
@@ 1,3 1,5 @@
+use std::sync::Arc;
+
mod vec3;
use vec3::*;
@@ 13,6 15,9 @@ use hittable_list::*;
mod sphere;
use sphere::*;
+mod rtweekend;
+use rtweekend::*;
+
fn hit_sphere(center: &Point3, radius: f64, r: &Ray) -> f64 {
let oc = r.origin() - *center;
let a = r.direction().length_squared();
@@ 27,11 32,9 @@ fn hit_sphere(center: &Point3, radius: f64, r: &Ray) -> f64 {
}
}
-fn ray_color(r: &Ray) -> Color {
- let t = hit_sphere(&Point3::new(0.0, 0.0, -1f64), 0.5, r);
- if t > 0.0 {
- let N = unit_vector(r.at(t) - Vec3::new(0.0, 0.0, -1.0));
- return 0.5 * Color::new(N.x() + 1.0, N.y() + 1.0, N.z() + 1.0);
+fn ray_color(r: &Ray, world: &dyn Hittable) -> Color {
+ if let Some(rec) = world.hit(r, 0.0, INFINITY) {
+ return 0.5 * (rec.normal + Color::new(1.0,1.0,1.0));
}
let unit_direction = unit_vector(r.direction());
let t = 0.5 * (unit_direction.y() + 1.0);
@@ 48,6 51,11 @@ fn main() {
let image_width = 800;
let image_height = (image_width as f64 / aspect_ratio) as i32;
+ // World
+ let mut world = HittableList::empty();
+ world.add(Arc::new(Sphere::new(Point3::new(0.0,0.0,-1.0), 0.5)));
+ world.add(Arc::new(Sphere::new(Point3::new(0.0,-100.5,-1.0), 100.0)));
+
// Camera
let viewport_height = 2.0;
@@ 73,7 81,7 @@ fn main() {
&origin,
&(lower_left_corner + u * horizontal + v * vertical - origin),
);
- let pixel_color = ray_color(&r);
+ let pixel_color = ray_color(&r, &world);
write_color(&mut handle, pixel_color);
}
}
@@ 9,7 9,7 @@ pub struct Sphere {
}
impl Sphere {
- fn new(center: Point3, radius: f64) -> Self {
+ pub fn new(center: Point3, radius: f64) -> Self {
Self { center, radius }
}
}