-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.rs
514 lines (470 loc) · 13.2 KB
/
main.rs
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use glam::DVec3;
use indicatif::ProgressIterator;
use itertools::Itertools;
use rand::prelude::*;
use std::{fs, io, ops::Range};
fn main() -> io::Result<()> {
let mut world = HittableList { objects: vec![] };
let material_ground = Material::Lambertian {
albedo: DVec3::new(0.8, 0.8, 0.0),
};
let material_center = Material::Lambertian {
albedo: DVec3::new(0.7, 0.3, 0.3),
};
let material_left = Material::Metal {
albedo: DVec3::new(0.8, 0.8, 0.8),
fuzz: 0.3,
};
let material_right = Material::Metal {
albedo: DVec3::new(0.8, 0.6, 0.2),
fuzz: 1.0,
};
world.add(Sphere {
center: DVec3::new(0.0, -100.5, -1.0),
radius: 100.0,
material: material_ground,
});
world.add(Sphere {
center: DVec3::new(0.0, 0.0, -1.0),
radius: 0.5,
material: material_center,
});
world.add(Sphere {
center: DVec3::new(-1.0, 0.0, -1.0),
radius: 0.5,
material: material_left,
});
world.add(Sphere {
center: DVec3::new(1.0, 0.0, -1.0),
radius: 0.5,
material: material_right,
});
let camera = Camera::new(400, 16.0 / 9.0);
camera.render_to_disk(world)?;
Ok(())
}
struct Camera {
image_width: u32,
image_height: u32,
max_value: u8,
aspect_ratio: f64,
center: DVec3,
pixel_delta_u: DVec3,
pixel_delta_v: DVec3,
// viewport_upper_left: DVec3,
pixel00_loc: DVec3,
samples_per_pixel: u32,
max_depth: u32,
}
impl Camera {
fn new(image_width: u32, aspect_ratio: f64) -> Self {
let max_value: u8 = 255;
let image_height: u32 =
(image_width as f64 / aspect_ratio) as u32;
let viewport_height: f64 = 2.0;
let viewport_width: f64 = viewport_height
* (image_width as f64 / image_height as f64);
let focal_length: f64 = 1.0;
let center: DVec3 = DVec3::ZERO;
// Calculate the vectors across the horizontal and down the vertical viewport edges.
let viewport_u: DVec3 =
DVec3::new(viewport_width, 0., 0.);
let viewport_v: DVec3 =
DVec3::new(0., -viewport_height, 0.);
// Calculate the horizontal and vertical delta vectors from pixel to pixel.
let pixel_delta_u: DVec3 =
viewport_u / image_width as f64;
let pixel_delta_v: DVec3 =
viewport_v / image_height as f64;
// Calculate the location of the upper left pixel.
let viewport_upper_left: DVec3 = center
- DVec3::new(0., 0., focal_length)
- viewport_u / 2.
- viewport_v / 2.;
let pixel00_loc: DVec3 = viewport_upper_left
+ 0.5 * (pixel_delta_u + pixel_delta_v);
Self {
image_width,
image_height,
max_value,
aspect_ratio,
center,
pixel_delta_u,
pixel_delta_v,
// viewport_upper_left,
pixel00_loc,
samples_per_pixel: 100,
max_depth: 50,
}
}
fn get_ray(&self, i: i32, j: i32) -> Ray {
// Get a randomly sampled camera ray for the pixel at location i,j.
let pixel_center = self.pixel00_loc
+ (i as f64 * self.pixel_delta_u)
+ (j as f64 * self.pixel_delta_v);
let pixel_sample =
pixel_center + self.pixel_sample_square();
let ray_origin = self.center;
let ray_direction = pixel_sample - ray_origin;
Ray {
origin: self.center,
direction: ray_direction,
}
}
fn pixel_sample_square(&self) -> DVec3 {
let mut rng = rand::thread_rng();
// Returns a random point in the square surrounding a pixel at the origin.
let px = -0.5 + rng.gen::<f64>();
let py = -0.5 + rng.gen::<f64>();
(px * self.pixel_delta_u)
+ (py * self.pixel_delta_v)
}
fn render_to_disk<T>(&self, world: T) -> io::Result<()>
where
T: Hittable,
{
let pixels = (0..self.image_height)
.cartesian_product(0..self.image_width)
.progress_count(
self.image_height as u64
* self.image_width as u64,
)
.map(|(y, x)| {
let scale_factor =
(self.samples_per_pixel as f64).recip();
let multisampled_pixel_color = (0..self
.samples_per_pixel)
.into_iter()
.map(|_| {
self.get_ray(x as i32, y as i32)
.color(
self.max_depth as i32,
&world,
)
})
.sum::<DVec3>()
* scale_factor;
// * 256.
let color = DVec3 {
x: linear_to_gamma(
multisampled_pixel_color.x,
),
y: linear_to_gamma(
multisampled_pixel_color.y,
),
z: linear_to_gamma(
multisampled_pixel_color.z,
),
}
.clamp(
DVec3::splat(0.),
DVec3::splat(0.999),
) * 256.;
format!(
"{} {} {}",
color.x, color.y, color.z
)
})
.join("\n");
fs::write(
"output.ppm",
format!(
"P3
{} {}
{}
{pixels}
",
self.image_width,
self.image_height,
self.max_value
),
)
}
}
fn linear_to_gamma(scalar: f64) -> f64 {
scalar.sqrt()
}
struct Ray {
origin: DVec3,
direction: DVec3,
}
impl Ray {
fn at(&self, t: f64) -> DVec3 {
self.origin + t * self.direction
}
fn color<T>(&self, depth: i32, world: &T) -> DVec3
where
T: Hittable,
{
if depth <= 0 {
return DVec3::new(0., 0., 0.);
}
if let Some(rec) =
world.hit(&self, (0.001)..f64::INFINITY)
{
if let Some(Scattered {
attenuation,
scattered,
}) = rec.material.scatter(self, rec.clone())
{
return attenuation
* scattered.color(depth - 1, world);
}
return DVec3::new(0., 0., 0.);
}
let unit_direction: DVec3 =
self.direction.normalize();
let a = 0.5 * (unit_direction.y + 1.0);
return (1.0 - a) * DVec3::new(1.0, 1.0, 1.0)
+ a * DVec3::new(0.5, 0.7, 1.0);
}
}
trait Hittable {
fn hit(
&self,
ray: &Ray,
interval: Range<f64>,
) -> Option<HitRecord>;
}
#[non_exhaustive]
#[derive(Clone)]
enum Material {
Lambertian { albedo: DVec3 },
Metal { albedo: DVec3, fuzz: f64 },
}
struct Scattered {
attenuation: DVec3,
scattered: Ray,
}
impl Material {
fn scatter(
&self,
r_in: &Ray,
hit_record: HitRecord,
) -> Option<Scattered> {
match self {
Material::Lambertian { albedo } => {
let mut scatter_direction = hit_record
.normal
+ random_unit_vector();
// Catch degenerate scatter direction
if scatter_direction.abs_diff_eq(
DVec3::new(0., 0., 0.),
1e-8,
) {
scatter_direction = hit_record.normal;
}
let scattered = Ray {
origin: hit_record.point,
direction: scatter_direction,
};
Some(Scattered {
attenuation: *albedo,
scattered,
})
}
Material::Metal { albedo, fuzz } => {
let reflected: DVec3 = reflect(
r_in.direction.normalize(),
hit_record.normal,
);
let scattered = Ray {
origin: hit_record.point,
direction: reflected
+ *fuzz * random_unit_vector(),
};
// absorb any scatter that is below the surface
if scattered
.direction
.dot(hit_record.normal)
> 0.
{
Some(Scattered {
attenuation: *albedo,
scattered,
})
} else {
None
}
}
_ => None,
}
}
}
#[derive(Clone)]
struct HitRecord {
point: DVec3,
normal: DVec3,
t: f64,
front_face: bool,
material: Material,
}
impl HitRecord {
fn with_face_normal(
material: Material,
point: DVec3,
outward_normal: DVec3,
t: f64,
ray: &Ray,
) -> Self {
let (front_face, normal) =
HitRecord::calc_face_normal(
ray,
&outward_normal,
);
HitRecord {
material,
point,
normal,
t,
front_face,
}
}
fn calc_face_normal(
ray: &Ray,
outward_normal: &DVec3,
) -> (bool, DVec3) {
// TODO: Why is outward_normal.is_normalized() false
// for some normals for which these two values are exactly the same:
// dbg!(
// outward_normal,
// outward_normal.normalize()
// );
// debug_assert!(
// !outward_normal.is_normalized(),
// "outward_normal must be normalized"
// );
let front_face =
ray.direction.dot(*outward_normal) < 0.;
let normal = if front_face {
*outward_normal
} else {
-*outward_normal
};
(front_face, normal)
}
// Unused
fn set_face_normal(
&mut self,
ray: &Ray,
outward_normal: &DVec3,
) {
let (front_face, normal) =
HitRecord::calc_face_normal(
ray,
outward_normal,
);
self.front_face = front_face;
self.normal = normal;
}
}
struct Sphere {
center: DVec3,
radius: f64,
material: Material,
}
impl Hittable for Sphere {
fn hit(
&self,
ray: &Ray,
interval: Range<f64>,
) -> Option<HitRecord> {
let oc = ray.origin - self.center;
let a = ray.direction.length_squared();
let half_b = oc.dot(ray.direction);
let c =
oc.length_squared() - self.radius * self.radius;
let discriminant = half_b * half_b - a * c;
if discriminant < 0. {
return None;
}
let sqrtd = discriminant.sqrt();
// Find the nearest root that lies in the acceptable range.
let mut root = (-half_b - sqrtd) / a;
if !interval.contains(&root) {
root = (-half_b + sqrtd) / a;
if !interval.contains(&root) {
return None;
}
}
let t = root;
let point = ray.at(t);
let outward_normal =
(point - self.center) / self.radius;
let rec = HitRecord::with_face_normal(
self.material.clone(),
point,
outward_normal,
t,
ray,
);
Some(rec)
}
}
struct HittableList {
objects: Vec<Box<dyn Hittable>>,
}
impl HittableList {
fn clear(&mut self) {
self.objects = vec![]
}
fn add<T>(&mut self, object: T)
where
T: Hittable + 'static,
{
// was push_back
self.objects.push(Box::new(object));
}
}
impl Hittable for HittableList {
fn hit(
&self,
ray: &Ray,
interval: Range<f64>,
) -> Option<HitRecord> {
let (_closest, hit_record) = self
.objects
.iter()
.fold((interval.end, None), |acc, item| {
if let Some(temp_rec) = item.hit(
ray,
interval.start..acc.0,
// acc.0,
) {
(temp_rec.t, Some(temp_rec))
} else {
acc
}
});
hit_record
}
}
fn random_in_unit_sphere() -> DVec3 {
let mut rng = rand::thread_rng();
loop {
let vec = DVec3::new(
rng.gen_range(-1.0..1.),
rng.gen_range(-1.0..1.),
rng.gen_range(-1.0..1.),
);
if vec.length_squared() < 1. {
break vec;
}
}
}
fn random_unit_vector() -> DVec3 {
return random_in_unit_sphere().normalize();
}
fn random_on_hemisphere(normal: &DVec3) -> DVec3 {
let on_unit_sphere = random_unit_vector();
if on_unit_sphere.dot(*normal) > 0.0
// In the same hemisphere as the normal
{
on_unit_sphere
} else {
-on_unit_sphere
}
}
fn reflect(v: DVec3, n: DVec3) -> DVec3 {
return v - 2. * v.dot(n) * n;
}