1
1
use crate :: ray:: Ray ;
2
2
use vec3D:: Vec3D ;
3
3
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
+
4
17
pub struct Camera {
5
18
pub origin : Vec3D ,
6
19
pub lower_left_corner : Vec3D ,
7
20
pub horizontal : Vec3D ,
8
21
pub vertical : Vec3D ,
22
+ pub lens_radius : f64 ,
23
+ u : Vec3D ,
24
+ v : Vec3D ,
9
25
}
10
26
11
27
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 {
13
29
let theta = vfov * std:: f64:: consts:: PI / 180.0 ;
14
30
let half_height = ( theta / 2.0 ) . tan ( ) ;
15
31
let half_width = aspect * half_height;
@@ -20,14 +36,19 @@ impl Camera {
20
36
let origin = look_from;
21
37
22
38
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 ,
26
42
origin,
43
+ lens_radius : aperture / 2.0 ,
44
+ u,
45
+ v,
27
46
}
28
47
}
29
48
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)
32
53
}
33
54
}
0 commit comments