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
|
use crate::calculus::calculus::{Point3, Ray, Vec3};
use crate::global::{Color, DisplayBuffer, Pixel, CAMERA_CENTER, FOCAL_LENGTH, IMG_HEIGHT, IMG_WIDTH, VIEWPORT_HEIGHT, VIEWPORT_WIDTH};
fn ray_color(ray: &Ray) -> Color {
let t = hit_sphere(&Point3 {x: 0.0, y: 0.0, z: -1.0}, 0.5, ray);
if t > 0.0 {
let normal = ray
.at(t)
.sub(&Vec3 {x: 0.0, y: 0.0, z: -1.0})
.unit();
return Color::new(
normal.x + 1.0,
normal.y + 1.0,
normal.z + 1.0,
).mul_scalar(0.5);
}
let unit_direction = ray.direction.unit();
let a = 0.5 * (unit_direction.y + 1.0);
let color1 = Color::new(1.0, 1.0, 1.0).mul_scalar(1.0 - a);
let color2 = Color::new(0.5, 0.7, 1.0).mul_scalar(a);
color1.add(&color2)
}
fn hit_sphere(center: &Point3, radius: f32, ray: &Ray) -> f32 {
let oc = center.sub(&ray.origin);
let a = ray.direction.dot_prod(&ray.direction);
let b = -2.0 * ray.direction.dot_prod(&oc);
let c = oc.dot_prod(&oc) - radius * radius;
let discriminant = b * b - 4.0 * a * c;
if discriminant < 0.0 {
-1.0
} else {
(-b - discriminant.sqrt()) / (2.0 * a)
}
}
pub fn render(display_buffer: &mut DisplayBuffer) {
let viewport_hor_vector = Vec3{ x: VIEWPORT_WIDTH as f32, y: 0.0, z: 0.0 };
let viewport_ver_vector = Vec3 { x: 0.0, y: -1f32 * VIEWPORT_HEIGHT as f32, z: 0.0 };
let delta_pixel_u = viewport_hor_vector.scalar_mul(1.0 / IMG_WIDTH as f32);
let delta_pixel_v = viewport_ver_vector.scalar_mul(1.0 / IMG_HEIGHT as f32);
let viewport_upper_left = CAMERA_CENTER
.sub(&Vec3 { x: 0f32, y: 0f32, z: FOCAL_LENGTH})
.sub(&viewport_hor_vector.scalar_mul(0.5))
.sub(&viewport_ver_vector.scalar_mul(0.5));
let pixel_upper_left = viewport_upper_left.add(
&delta_pixel_u.add(&delta_pixel_u).scalar_mul(0.5)
);
(0..IMG_HEIGHT).for_each(|j| {
(0..IMG_WIDTH).for_each(|i| {
let pixel_center = pixel_upper_left
.add(&delta_pixel_u.scalar_mul(i as f32))
.add(&delta_pixel_v.scalar_mul(j as f32));
let ray_direction = pixel_center.sub(&CAMERA_CENTER);
let ray = Ray {
origin: &CAMERA_CENTER,
direction: &ray_direction,
};
let color = ray_color(&ray);
display_buffer[j][i] = Pixel::from_color(&color);
})
})
}
|