1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use rand::{rngs::StdRng, Rng};
use rand_distr::UnitDisc;
use crate::shape::Ray;
#[derive(Copy, Clone, Debug)]
pub struct Camera {
pub eye: glm::DVec3,
pub direction: glm::DVec3,
pub up: glm::DVec3,
pub fov: f64,
pub aperture: f64,
pub focal_distance: f64,
}
impl Default for Camera {
fn default() -> Self {
Self {
eye: glm::vec3(0.0, 0.0, 10.0),
direction: glm::vec3(0.0, 0.0, -1.0),
up: glm::vec3(0.0, 1.0, 0.0),
fov: std::f64::consts::FRAC_PI_6,
aperture: 0.0,
focal_distance: 0.0,
}
}
}
impl Camera {
pub fn look_at(eye: glm::DVec3, center: glm::DVec3, up: glm::DVec3, fov: f64) -> Self {
let direction = (center - eye).normalize();
let up = (up - up.dot(&direction) * direction).normalize();
Self {
eye,
direction,
up,
fov,
aperture: 0.0,
focal_distance: 0.0,
}
}
pub fn focus(mut self, focal_point: glm::DVec3, aperture: f64) -> Self {
self.focal_distance = (focal_point - self.eye).dot(&self.direction);
self.aperture = aperture;
self
}
pub fn cast_ray(&self, x: f64, y: f64, rng: &mut StdRng) -> Ray {
let d = (self.fov / 2.0).tan().recip();
let right = glm::cross(&self.direction, &self.up).normalize();
let mut origin = self.eye;
let mut new_dir = d * self.direction + x * right + y * self.up;
if self.aperture > 0.0 {
let focal_point = origin + new_dir.normalize() * self.focal_distance;
let [x, y]: [f64; 2] = rng.sample(UnitDisc);
origin += (x * right + y * self.up) * self.aperture;
new_dir = focal_point - origin;
}
Ray {
origin,
dir: new_dir.normalize(),
}
}
}