Skip to content

Commit 4e3da96

Browse files
committed
🐆 camera focus distance
1 parent 41f4982 commit 4e3da96

File tree

2 files changed

+41
-7
lines changed

2 files changed

+41
-7
lines changed

src/camera.rs

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,31 @@
11
use crate::ray::Ray;
22
use vec3D::Vec3D;
33

4+
fn random_in_unit_disk() -> Vec3D {
5+
let mut p: Vec3D;
6+
7+
loop {
8+
p = Vec3D::new(rand::random::<f64>(), rand::random::<f64>(), 0.0) * 2.0 - Vec3D::new(1.0, 1.0, 0.0);
9+
10+
if p.dot(p) < 1.0 {
11+
break;
12+
}
13+
}
14+
p
15+
}
16+
417
pub struct Camera {
518
pub origin: Vec3D,
619
pub lower_left_corner: Vec3D,
720
pub horizontal: Vec3D,
821
pub vertical: Vec3D,
22+
pub lens_radius: f64,
23+
u: Vec3D,
24+
v: Vec3D,
925
}
1026

1127
impl Camera {
12-
pub fn new(look_from: Vec3D, look_at: Vec3D, up: Vec3D, vfov: f64, aspect: f64) -> Camera {
28+
pub fn new(look_from: Vec3D, look_at: Vec3D, up: Vec3D, vfov: f64, aspect: f64, aperture: f64, focus_distance: f64) -> Camera {
1329
let theta = vfov * std::f64::consts::PI / 180.0;
1430
let half_height = (theta / 2.0).tan();
1531
let half_width = aspect * half_height;
@@ -20,14 +36,19 @@ impl Camera {
2036
let origin = look_from;
2137

2238
Camera {
23-
lower_left_corner: origin - u * half_width - v * half_height - w,
24-
horizontal: u * half_width * 2.0,
25-
vertical: v * half_height * 2.0,
39+
lower_left_corner: origin - u * focus_distance * half_width - v * focus_distance * half_height - w * focus_distance,
40+
horizontal: u * half_width * 2.0 * focus_distance,
41+
vertical: v * half_height * 2.0 * focus_distance,
2642
origin,
43+
lens_radius: aperture / 2.0,
44+
u,
45+
v,
2746
}
2847
}
2948

30-
pub fn get_ray(&self, u: f64, v: f64) -> Ray {
31-
Ray::new(self.origin, self.lower_left_corner + (self.horizontal * u) + (self.vertical * v) - self.origin)
49+
pub fn get_ray(&self, s: f64, t: f64) -> Ray {
50+
let rd = random_in_unit_disk() * self.lens_radius;
51+
let offset = self.u * rd.x + self.v * rd.y;
52+
Ray::new(self.origin + offset, self.lower_left_corner + (self.horizontal * s) + (self.vertical * t) - self.origin - offset)
3253
}
3354
}

src/main.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,20 @@ fn main() {
5050
Material::Dielectric(Dielectric::new(1.5))
5151
)));
5252

53-
let camera = Camera::new(120.0, nx as f64 / ny as f64);
53+
let look_from = Vec3D::new(3.0, 3.0, 2.0);
54+
let look_at = Vec3D::new(0.0, 0.0, -1.0);
55+
let distance_to_focus = (look_from - look_at).mag();
56+
let aperture = 2.0;
57+
58+
let camera = Camera::new(
59+
look_from,
60+
look_at,
61+
Vec3D::new(0.0, 1.0, 0.0),
62+
20.0,
63+
nx as f64 / ny as f64,
64+
aperture,
65+
distance_to_focus
66+
);
5467

5568
for j in (0..ny).rev() {
5669
for i in 0..nx {

0 commit comments

Comments
 (0)