camera: implement Camera::render.

This commit is contained in:
Bill Thiede 2021-07-17 21:45:15 -07:00
parent ad02d7e945
commit 059f710706

View File

@ -1,4 +1,4 @@
use crate::{matrices::Matrix4x4, rays::Ray, tuples::Tuple};
use crate::{canvas::Canvas, matrices::Matrix4x4, rays::Ray, tuples::Tuple, world::World, BLACK};
pub struct Camera {
hsize: usize,
@ -121,4 +121,39 @@ impl Camera {
Ray::new(origin, direction)
}
/// Use camera to render an image of the given world.
///
/// # Examples
/// ```
/// use std::f32::consts::PI;
///
/// use rtchallenge::{
/// camera::Camera,
/// transformations::view_transform,
/// tuples::{Color, Tuple},
/// world::World,
/// };
///
/// // Rendering a world with a camera.
/// let w = World::test_world();
/// let mut c = Camera::new(11, 11, PI / 2.);
/// let from = Tuple::point(0., 0., -5.);
/// let to = Tuple::point(0., 0., 0.);
/// let up = Tuple::vector(0., 1., 0.);
/// c.transform = view_transform(from, to, up);
/// let image = c.render(&w);
/// assert_eq!(image.get(5, 5), Color::new(0.38066, 0.47583, 0.2855));
/// ```
pub fn render(&self, w: &World) -> Canvas {
let mut image = Canvas::new(self.hsize, self.vsize, BLACK);
for y in 0..self.hsize {
for x in 0..self.vsize {
let ray = self.ray_for_pixel(x, y);
let color = w.color_at(&ray);
image.set(x, y, color);
}
}
image
}
}