Compare commits
1 Commits
master
...
7de0f07f56
| Author | SHA1 | Date | |
|---|---|---|---|
| 7de0f07f56 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,4 +1,2 @@
|
||||
**/target
|
||||
**/*.rs.bk
|
||||
**/zig-out
|
||||
**/zig-cache
|
||||
|
||||
@@ -5,5 +5,3 @@ Raytracers
|
||||
|
||||
Random collection of ray tracing experiments.
|
||||
|
||||
# TODO
|
||||
Implement http://www.kevinbeason.com/smallpt/
|
||||
|
||||
87
rtchallenge/Cargo.lock
generated
87
rtchallenge/Cargo.lock
generated
@@ -130,7 +130,7 @@ dependencies = [
|
||||
"ansi_term",
|
||||
"atty",
|
||||
"bitflags",
|
||||
"strsim 0.8.0",
|
||||
"strsim",
|
||||
"textwrap",
|
||||
"unicode-width",
|
||||
"vec_map",
|
||||
@@ -259,41 +259,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f2c43f534ea4b0b049015d00269734195e6d3f0f6635cb692251aca6f9f8b3c"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e91455b86830a1c21799d94524df0845183fa55bafd9aa137b01c7d1065fa36"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim 0.10.0",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29b5acf0dea37a7f66f7b25d2c5e93fd46f8f6968b1a5d7a3e02e97768afc95a"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deflate"
|
||||
version = "0.8.6"
|
||||
@@ -304,37 +269,6 @@ dependencies = [
|
||||
"byteorder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_builder"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d13202debe11181040ae9063d739fa32cfcaaebe2275fe387703460ae2365b30"
|
||||
dependencies = [
|
||||
"derive_builder_macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_builder_core"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "66e616858f6187ed828df7c64a6d71720d83767a7f19740b2d1b6fe6327b36e5"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_builder_macro"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "58a94ace95092c5acb1e97a7e846b310cfbd499652f72297da7493f618a98d73"
|
||||
dependencies = [
|
||||
"derive_builder_core",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.6.1"
|
||||
@@ -374,12 +308,6 @@ dependencies = [
|
||||
"backtrace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.3"
|
||||
@@ -421,12 +349,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ident_case"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.9.0"
|
||||
@@ -740,7 +662,6 @@ dependencies = [
|
||||
"anyhow",
|
||||
"core_affinity",
|
||||
"criterion",
|
||||
"derive_builder",
|
||||
"enum-utils",
|
||||
"num_cpus",
|
||||
"png",
|
||||
@@ -852,12 +773,6 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
|
||||
|
||||
[[package]]
|
||||
name = "structopt"
|
||||
version = "0.3.22"
|
||||
|
||||
@@ -8,13 +8,13 @@ edition = "2018"
|
||||
|
||||
[features]
|
||||
default = [ "float-as-double" ]
|
||||
disable-inverse-cache = []
|
||||
float-as-double = []
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.41"
|
||||
core_affinity = "0.5.10"
|
||||
criterion = "0.3.4"
|
||||
derive_builder = "0.10.2"
|
||||
enum-utils = "0.1.2"
|
||||
num_cpus = "1.13.0"
|
||||
png = "0.16.8"
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use rtchallenge::{
|
||||
camera::{Camera, RenderStrategy},
|
||||
float::consts::PI,
|
||||
lights::PointLightBuilder,
|
||||
materials::MaterialBuilder,
|
||||
matrices::Matrix4x4,
|
||||
shapes::{Geometry, ShapeBuilder},
|
||||
transformations::view_transform,
|
||||
tuples::Tuple,
|
||||
world::WorldBuilder,
|
||||
Float, WHITE,
|
||||
};
|
||||
|
||||
/// Experimenting with balls.
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "balls")]
|
||||
struct Opt {
|
||||
#[structopt(long, default_value = "rayon")]
|
||||
render_strategy: RenderStrategy,
|
||||
/// Number of samples per pixel. 0 renders from the center of the pixel, 1 or more samples N
|
||||
/// times randomly across the pixel.
|
||||
#[structopt(short, long, default_value = "0")]
|
||||
samples: usize,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let opt = Opt::from_args();
|
||||
let width = 2560;
|
||||
let height = 1440;
|
||||
|
||||
let light1 = PointLightBuilder::default()
|
||||
.position(Tuple::point(-5., 5., -5.))
|
||||
.intensity(WHITE)
|
||||
.build()?;
|
||||
let light2 = PointLightBuilder::default()
|
||||
.position(Tuple::point(5., 5., -5.))
|
||||
.intensity([0.2, 0.2, 0.6])
|
||||
.build()?;
|
||||
let light3 = PointLightBuilder::default()
|
||||
.position(Tuple::point(0., 2., -5.))
|
||||
.intensity([0.2, 0.2, 0.1])
|
||||
.build()?;
|
||||
|
||||
let ball_size = 0.5;
|
||||
let num_per_axis = 3;
|
||||
let center_to_center = 4. * ball_size;
|
||||
let from = Tuple::point(
|
||||
-5. * center_to_center,
|
||||
5. * center_to_center,
|
||||
-4. * center_to_center,
|
||||
);
|
||||
let to = Tuple::point(
|
||||
num_per_axis as Float * center_to_center / 2.,
|
||||
0., //num_per_axis as Float * center_to_center / 2.,
|
||||
num_per_axis as Float * center_to_center / 2.,
|
||||
);
|
||||
let up = Tuple::point(0., 1., 0.);
|
||||
let mut camera = Camera::new(width, height, PI / 6.);
|
||||
camera.set_transform(view_transform(from, to, up));
|
||||
camera.render_strategy = opt.render_strategy;
|
||||
camera.samples_per_pixel = opt.samples;
|
||||
|
||||
let floor = ShapeBuilder::default()
|
||||
.geometry(Geometry::Plane)
|
||||
.transform(Matrix4x4::translation(0., -ball_size, 0.))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.2, 0.2, 0.2])
|
||||
.specular(0.)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
let mut objects = vec![floor];
|
||||
|
||||
for z in 0..num_per_axis {
|
||||
for y in 0..num_per_axis {
|
||||
for x in 0..num_per_axis {
|
||||
objects.push(
|
||||
ShapeBuilder::default()
|
||||
.transform(
|
||||
Matrix4x4::translation(
|
||||
x as Float * center_to_center,
|
||||
y as Float * center_to_center,
|
||||
z as Float * center_to_center,
|
||||
) * Matrix4x4::scaling(ball_size, ball_size, ball_size),
|
||||
)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.1, 1., 0.5])
|
||||
.ambient(y as Float / 4.)
|
||||
.diffuse(x as Float / 4.)
|
||||
.specular(z as Float / 4.)
|
||||
.build()?,
|
||||
)
|
||||
.build()?,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let world = WorldBuilder::default()
|
||||
.lights(vec![light1, light2, light3])
|
||||
.objects(objects)
|
||||
.build()?;
|
||||
|
||||
let image = camera.render(&world);
|
||||
|
||||
let path = "/tmp/balls.png";
|
||||
println!("saving output to {}", path);
|
||||
image.write_to_file(path)?;
|
||||
println!("Render time {:.3} seconds", start.elapsed().as_secs_f32());
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use rtchallenge::prelude::*;
|
||||
|
||||
use rtchallenge::{
|
||||
camera::RenderStrategy,
|
||||
float::consts::PI,
|
||||
patterns::{test_pattern, BLACK_PAT, WHITE_PAT},
|
||||
WHITE,
|
||||
};
|
||||
|
||||
/// End of chapter 10 challenge.
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "eoc10")]
|
||||
struct Opt {
|
||||
/// Strategy for casting rays into image.
|
||||
#[structopt(long, default_value = "rayon")]
|
||||
render_strategy: RenderStrategy,
|
||||
/// Number of samples per pixel. 0 renders from the center of the pixel, 1 or more samples N
|
||||
/// times randomly across the pixel.
|
||||
#[structopt(short, long, default_value = "0")]
|
||||
samples: usize,
|
||||
/// Rendered image width in pixels.
|
||||
#[structopt(short, long, default_value = "2560")]
|
||||
width: usize,
|
||||
/// Rendered image height in pixels.
|
||||
#[structopt(short, long, default_value = "1440")]
|
||||
height: usize,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let opt = Opt::from_args();
|
||||
|
||||
let light1 = PointLightBuilder::default()
|
||||
.position(point(-5., 5., -5.))
|
||||
.intensity(WHITE)
|
||||
.build()?;
|
||||
let light2 = PointLightBuilder::default()
|
||||
.position(point(5., 5., -5.))
|
||||
.intensity([0.2, 0.2, 0.6])
|
||||
.build()?;
|
||||
let light3 = PointLightBuilder::default()
|
||||
.position(point(0., 2., -5.))
|
||||
.intensity([0.2, 0.2, 0.1])
|
||||
.build()?;
|
||||
|
||||
let from = point(2., 2., -10.);
|
||||
let to = point(2., 1., 0.);
|
||||
let up = point(0., 1., 0.);
|
||||
let camera = CameraBuilder::default()
|
||||
.hsize(opt.width)
|
||||
.vsize(opt.height)
|
||||
.field_of_view(PI / 4.)
|
||||
.transform(view_transform(from, to, up))
|
||||
.render_strategy(opt.render_strategy)
|
||||
.samples_per_pixel(opt.samples)
|
||||
.build()?;
|
||||
|
||||
let floor = plane()
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
checkers_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(translation(1., 0., 0.) * scaling(2., 2., 2.))
|
||||
.build()?,
|
||||
)
|
||||
.specular(0.)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
let sphere_size = scaling(0.5, 0.5, 0.5);
|
||||
|
||||
let x1y1 = sphere()
|
||||
.transform(translation(1., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
gradient_pattern([0., 0., 1.].into(), [1., 1., 0.].into())
|
||||
.transform(scaling(2., 1., 1.) * translation(-0.5, 0., 0.))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y1 = sphere()
|
||||
.transform(translation(2., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(stripe_pattern(WHITE_PAT, BLACK_PAT).build()?)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y1 = sphere()
|
||||
.transform(translation(3., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
stripe_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.2, 1., 1.))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.0)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x1y2 = sphere()
|
||||
.transform(translation(1., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(test_pattern().build()?)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y2 = sphere()
|
||||
.transform(translation(2., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
ring_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.2, 0.2, 0.2))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y2 = sphere()
|
||||
.transform(translation(3., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
checkers_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.5, 0.5, 0.5))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let world = WorldBuilder::default()
|
||||
.lights(vec![light1, light2, light3])
|
||||
.objects(vec![floor, x1y1, x2y1, x3y1, x1y2, x2y2, x3y2])
|
||||
.build()?;
|
||||
|
||||
let image = camera.render(&world);
|
||||
|
||||
let path = "/tmp/eoc10.png";
|
||||
println!("saving output to {}", path);
|
||||
image.write_to_file(path)?;
|
||||
println!("Render time {:.3} seconds", start.elapsed().as_secs_f32());
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use rtchallenge::prelude::*;
|
||||
|
||||
use rtchallenge::{
|
||||
camera::RenderStrategy,
|
||||
float::consts::PI,
|
||||
patterns::{test_pattern, BLACK_PAT, WHITE_PAT},
|
||||
WHITE,
|
||||
};
|
||||
|
||||
/// End of chapter 11 challenge.
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "eoc11")]
|
||||
struct Opt {
|
||||
/// Strategy for casting rays into image.
|
||||
#[structopt(long, default_value = "rayon")]
|
||||
render_strategy: RenderStrategy,
|
||||
/// Number of samples per pixel. 0 renders from the center of the pixel, 1 or more samples N
|
||||
/// times randomly across the pixel.
|
||||
#[structopt(short, long, default_value = "0")]
|
||||
samples: usize,
|
||||
/// Rendered image width in pixels.
|
||||
#[structopt(short, long, default_value = "2560")]
|
||||
width: usize,
|
||||
/// Rendered image height in pixels.
|
||||
#[structopt(short, long, default_value = "1440")]
|
||||
height: usize,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let opt = Opt::from_args();
|
||||
|
||||
let light1 = PointLightBuilder::default()
|
||||
.position(point(-5., 5., -5.))
|
||||
.intensity(WHITE)
|
||||
.build()?;
|
||||
let light2 = PointLightBuilder::default()
|
||||
.position(point(5., 5., -5.))
|
||||
.intensity([0.2, 0.2, 0.6])
|
||||
.build()?;
|
||||
let light3 = PointLightBuilder::default()
|
||||
.position(point(0., 2., -5.))
|
||||
.intensity([0.2, 0.2, 0.1])
|
||||
.build()?;
|
||||
|
||||
let from = point(2., 8., -10.);
|
||||
let to = point(2., 1., -1.);
|
||||
let up = point(0., 1., 0.);
|
||||
let camera = CameraBuilder::default()
|
||||
.hsize(opt.width)
|
||||
.vsize(opt.height)
|
||||
.field_of_view(PI / 6.)
|
||||
.transform(view_transform(from, to, up))
|
||||
.render_strategy(opt.render_strategy)
|
||||
.samples_per_pixel(opt.samples)
|
||||
.build()?;
|
||||
|
||||
let floor = plane()
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
checkers_pattern(
|
||||
ring_pattern([0.8, 0.8, 0.2].into(), [0.8, 0.2, 0.8].into())
|
||||
.transform(scaling(1. / 8., 1. / 8., 1. / 8.))
|
||||
.build()?,
|
||||
ring_pattern([0.2, 0.8, 0.2].into(), [0.8, 0.2, 0.2].into())
|
||||
.transform(scaling(1. / 4., 1. / 4., 1. / 4.))
|
||||
.build()?,
|
||||
)
|
||||
.transform(translation(0., 1., 0.) * scaling(2., 2., 2.))
|
||||
.build()?,
|
||||
)
|
||||
.specular(0.)
|
||||
.reflective(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
let sphere_size = scaling(0.5, 0.5, 0.5);
|
||||
|
||||
let x1y1 = sphere()
|
||||
.transform(translation(1., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
gradient_pattern([0., 0., 1.].into(), [1., 1., 0.].into())
|
||||
.transform(scaling(2., 1., 1.) * translation(-0.5, 0., 0.))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.reflective(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y1 = sphere()
|
||||
.transform(translation(2., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(stripe_pattern(WHITE_PAT, BLACK_PAT).build()?)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y1 = sphere()
|
||||
.transform(translation(3., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
stripe_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.2, 1., 1.))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.0)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x1y2 = sphere()
|
||||
.transform(translation(1., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(test_pattern().build()?)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y2 = sphere()
|
||||
.transform(translation(2., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
ring_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.2, 0.2, 0.2))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y2 = sphere()
|
||||
.transform(translation(3., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
checkers_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.5, 0.5, 0.5))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x1y2z1 = sphere()
|
||||
.transform(translation(1., 2., -1.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.8, 0.2, 0.2])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.transparency(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y2z1 = sphere()
|
||||
.transform(translation(2., 2., -1.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.8, 0.2, 0.2])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.transparency(0.9)
|
||||
.refractive_index(1.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y4z1 = sphere()
|
||||
.transform(translation(2., 4., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.2, 0.2, 0.8])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let world = WorldBuilder::default()
|
||||
.lights(vec![light1, light2, light3])
|
||||
.objects(vec![
|
||||
floor, x1y1, x2y1, x3y1, x1y2, x2y2, x3y2, x1y2z1, x2y2z1, x2y4z1,
|
||||
])
|
||||
.build()?;
|
||||
|
||||
let image = camera.render(&world);
|
||||
|
||||
let path = "/tmp/eoc11.png";
|
||||
println!("saving output to {}", path);
|
||||
image.write_to_file(path)?;
|
||||
println!("Render time {:.3} seconds", start.elapsed().as_secs_f32());
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use rtchallenge::prelude::*;
|
||||
|
||||
use rtchallenge::{
|
||||
camera::RenderStrategy,
|
||||
float::consts::PI,
|
||||
patterns::{test_pattern, BLACK_PAT, WHITE_PAT},
|
||||
WHITE,
|
||||
};
|
||||
|
||||
/// End of chapter 12 challenge.
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "eoc12")]
|
||||
struct Opt {
|
||||
/// Strategy for casting rays into image.
|
||||
#[structopt(long, default_value = "rayon")]
|
||||
render_strategy: RenderStrategy,
|
||||
/// Number of samples per pixel. 0 renders from the center of the pixel, 1 or more samples N
|
||||
/// times randomly across the pixel.
|
||||
#[structopt(short, long, default_value = "0")]
|
||||
samples: usize,
|
||||
/// Rendered image width in pixels.
|
||||
#[structopt(short, long, default_value = "2560")]
|
||||
width: usize,
|
||||
/// Rendered image height in pixels.
|
||||
#[structopt(short, long, default_value = "1440")]
|
||||
height: usize,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let opt = Opt::from_args();
|
||||
|
||||
let light1 = PointLightBuilder::default()
|
||||
.position(point(-5., 5., -5.))
|
||||
.intensity(WHITE)
|
||||
.build()?;
|
||||
let light2 = PointLightBuilder::default()
|
||||
.position(point(5., 5., -5.))
|
||||
.intensity([0.2, 0.2, 0.6])
|
||||
.build()?;
|
||||
let light3 = PointLightBuilder::default()
|
||||
.position(point(0., 2., -5.))
|
||||
.intensity([0.2, 0.2, 0.1])
|
||||
.build()?;
|
||||
|
||||
let from = point(2., 8., -10.);
|
||||
let to = point(2., 1., -1.);
|
||||
let up = point(0., 1., 0.);
|
||||
let camera = CameraBuilder::default()
|
||||
.hsize(opt.width)
|
||||
.vsize(opt.height)
|
||||
.field_of_view(PI / 6.)
|
||||
.transform(view_transform(from, to, up))
|
||||
.render_strategy(opt.render_strategy)
|
||||
.samples_per_pixel(opt.samples)
|
||||
.build()?;
|
||||
|
||||
let floor = plane()
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
checkers_pattern(
|
||||
ring_pattern([0.8, 0.8, 0.2].into(), [0.8, 0.2, 0.8].into())
|
||||
.transform(scaling(1. / 8., 1. / 8., 1. / 8.))
|
||||
.build()?,
|
||||
ring_pattern([0.2, 0.8, 0.2].into(), [0.8, 0.2, 0.2].into())
|
||||
.transform(scaling(1. / 4., 1. / 4., 1. / 4.))
|
||||
.build()?,
|
||||
)
|
||||
.transform(translation(0., 1., 0.) * scaling(2., 2., 2.))
|
||||
.build()?,
|
||||
)
|
||||
.specular(0.)
|
||||
.reflective(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
let sphere_size = scaling(0.5, 0.5, 0.5);
|
||||
|
||||
let x1y1 = sphere()
|
||||
.transform(translation(1., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
gradient_pattern([0., 0., 1.].into(), [1., 1., 0.].into())
|
||||
.transform(scaling(2., 1., 1.) * translation(-0.5, 0., 0.))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.reflective(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y1 = sphere()
|
||||
.transform(translation(2., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(stripe_pattern(WHITE_PAT, BLACK_PAT).build()?)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y1 = sphere()
|
||||
.transform(translation(3., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
stripe_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.2, 1., 1.))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.0)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x1y2 = sphere()
|
||||
.transform(translation(1., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(test_pattern().build()?)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y2 = sphere()
|
||||
.transform(translation(2., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
ring_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.2, 0.2, 0.2))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y2 = sphere()
|
||||
.transform(translation(3., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
checkers_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.5, 0.5, 0.5))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x1y2z1 = sphere()
|
||||
.transform(translation(1., 2., -1.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.8, 0.2, 0.2])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.transparency(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y2z1 = sphere()
|
||||
.transform(translation(2., 2., -1.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.8, 0.2, 0.2])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.transparency(0.9)
|
||||
.refractive_index(1.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y2z1 = cube()
|
||||
.transform(
|
||||
translation(3., 2., -1.) * (sphere_size * scaling(0.5, 0.5, 0.5)) * rotation_y(PI / 4.),
|
||||
)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.8, 0.8, 0.2])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.reflective(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y4z1 = sphere()
|
||||
.transform(translation(2., 4., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.2, 0.2, 0.8])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let world = WorldBuilder::default()
|
||||
.lights(vec![light1, light2, light3])
|
||||
.objects(vec![
|
||||
floor, x1y1, x2y1, x3y1, x1y2, x2y2, x3y2, x1y2z1, x2y2z1, x2y4z1, x3y2z1,
|
||||
])
|
||||
.build()?;
|
||||
|
||||
let image = camera.render(&world);
|
||||
|
||||
let path = "/tmp/eoc12.png";
|
||||
println!("saving output to {}", path);
|
||||
image.write_to_file(path)?;
|
||||
println!("Render time {:.3} seconds", start.elapsed().as_secs_f32());
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use rtchallenge::prelude::*;
|
||||
|
||||
use rtchallenge::{
|
||||
camera::RenderStrategy,
|
||||
float::consts::PI,
|
||||
patterns::{test_pattern, BLACK_PAT, WHITE_PAT},
|
||||
WHITE,
|
||||
};
|
||||
|
||||
/// End of chapter 14 challenge.
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "eoc14")]
|
||||
struct Opt {
|
||||
/// Strategy for casting rays into image.
|
||||
#[structopt(long, default_value = "rayon")]
|
||||
render_strategy: RenderStrategy,
|
||||
/// Number of samples per pixel. 0 renders from the center of the pixel, 1 or more samples N
|
||||
/// times randomly across the pixel.
|
||||
#[structopt(short, long, default_value = "0")]
|
||||
samples: usize,
|
||||
/// Rendered image width in pixels.
|
||||
#[structopt(short, long, default_value = "2560")]
|
||||
width: usize,
|
||||
/// Rendered image height in pixels.
|
||||
#[structopt(short, long, default_value = "1440")]
|
||||
height: usize,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let opt = Opt::from_args();
|
||||
|
||||
let light1 = PointLightBuilder::default()
|
||||
.position(point(-5., 5., -5.))
|
||||
.intensity(WHITE)
|
||||
.build()?;
|
||||
let light2 = PointLightBuilder::default()
|
||||
.position(point(5., 5., -5.))
|
||||
.intensity([0.2, 0.2, 0.6])
|
||||
.build()?;
|
||||
let light3 = PointLightBuilder::default()
|
||||
.position(point(0., 2., -5.))
|
||||
.intensity([0.2, 0.2, 0.1])
|
||||
.build()?;
|
||||
|
||||
let from = point(2., 8., -10.);
|
||||
let to = point(2., 2., -1.);
|
||||
let up = point(0., 1., 0.);
|
||||
let camera = CameraBuilder::default()
|
||||
.hsize(opt.width)
|
||||
.vsize(opt.height)
|
||||
.field_of_view(PI / 12.)
|
||||
.transform(view_transform(from, to, up))
|
||||
.render_strategy(opt.render_strategy)
|
||||
.samples_per_pixel(opt.samples)
|
||||
.build()?;
|
||||
|
||||
let floor = plane()
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
checkers_pattern(
|
||||
ring_pattern([0.8, 0.8, 0.2].into(), [0.8, 0.2, 0.8].into())
|
||||
.transform(scaling(1. / 8., 1. / 8., 1. / 8.))
|
||||
.build()?,
|
||||
ring_pattern([0.2, 0.8, 0.2].into(), [0.8, 0.2, 0.2].into())
|
||||
.transform(scaling(1. / 4., 1. / 4., 1. / 4.))
|
||||
.build()?,
|
||||
)
|
||||
.transform(translation(0., 1., 0.) * scaling(2., 2., 2.))
|
||||
.build()?,
|
||||
)
|
||||
.specular(0.)
|
||||
.reflective(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
let sphere_size = scaling(0.5, 0.5, 0.5);
|
||||
|
||||
let x1y1 = sphere()
|
||||
.transform(translation(1., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
gradient_pattern([0., 0., 1.].into(), [1., 1., 0.].into())
|
||||
.transform(scaling(2., 1., 1.) * translation(-0.5, 0., 0.))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.reflective(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y1 = sphere()
|
||||
.transform(translation(2., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(stripe_pattern(WHITE_PAT, BLACK_PAT).build()?)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y1 = sphere()
|
||||
.transform(translation(3., 1., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
stripe_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.2, 1., 1.))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.0)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x1y2 = sphere()
|
||||
.transform(translation(1., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(test_pattern().build()?)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y2 = sphere()
|
||||
.transform(translation(2., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
ring_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.2, 0.2, 0.2))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y2 = sphere()
|
||||
.transform(translation(3., 2., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(
|
||||
checkers_pattern(WHITE_PAT, BLACK_PAT)
|
||||
.transform(scaling(0.5, 0.5, 0.5))
|
||||
.build()?,
|
||||
)
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x1y2z1 = sphere()
|
||||
.transform(translation(1., 2., -1.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.8, 0.2, 0.2])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.transparency(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y2z1 = sphere()
|
||||
.transform(translation(2., 2., -1.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.8, 0.2, 0.2])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.transparency(0.9)
|
||||
.refractive_index(1.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x3y2z1 = cube()
|
||||
.transform(
|
||||
translation(3., 2., -1.) * (sphere_size * scaling(0.5, 0.5, 0.5)) * rotation_y(PI / 4.),
|
||||
)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.8, 0.8, 0.2])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.reflective(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let x2y4z1 = sphere()
|
||||
.transform(translation(2., 4., 0.) * sphere_size)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.2, 0.2, 0.8])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let world = WorldBuilder::default()
|
||||
.lights(vec![light1, light2, light3])
|
||||
.objects(vec![
|
||||
floor, x1y1, x2y1, x3y1, x1y2, x2y2, x3y2, x1y2z1, x2y2z1, x2y4z1, x3y2z1,
|
||||
])
|
||||
.build()?;
|
||||
|
||||
let image = camera.render(&world);
|
||||
|
||||
let path = "/tmp/eoc14.png";
|
||||
println!("saving output to {}", path);
|
||||
image.write_to_file(path)?;
|
||||
println!("Render time {:.3} seconds", start.elapsed().as_secs_f32());
|
||||
Ok(())
|
||||
}
|
||||
@@ -21,13 +21,13 @@ fn main() -> Result<()> {
|
||||
let pixel_size = wall_size / w as Float;
|
||||
let half = wall_size / 2.;
|
||||
let mut shape = Shape::sphere();
|
||||
shape.material = Material {
|
||||
color: Color::new(1., 0.2, 1.).into(),
|
||||
shape.set_material(Material {
|
||||
color: Color::new(1., 0.2, 1.),
|
||||
specular: 0.5,
|
||||
diffuse: 0.7,
|
||||
shininess: 30.,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
let light_position = Tuple::point(-10., 10., -10.);
|
||||
let light_color = WHITE;
|
||||
let light = PointLight::new(light_position, light_color);
|
||||
@@ -45,8 +45,7 @@ fn main() -> Result<()> {
|
||||
let normal = hit.object.normal_at(point);
|
||||
let eye = -r.direction;
|
||||
let color = lighting(
|
||||
&hit.object.material,
|
||||
&hit.object,
|
||||
&hit.object.material(),
|
||||
&light,
|
||||
point,
|
||||
eye,
|
||||
|
||||
@@ -41,11 +41,11 @@ fn main() -> Result<()> {
|
||||
|
||||
let mut floor = Shape::sphere();
|
||||
floor.set_transform(Matrix4x4::scaling(10., 0.01, 10.));
|
||||
floor.material = Material {
|
||||
color: Color::new(1., 0.9, 0.9).into(),
|
||||
floor.set_material(Material {
|
||||
color: Color::new(1., 0.9, 0.9),
|
||||
specular: 0.,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
|
||||
let mut left_wall = Shape::sphere();
|
||||
left_wall.set_transform(
|
||||
@@ -54,7 +54,7 @@ fn main() -> Result<()> {
|
||||
* Matrix4x4::rotation_x(PI / 2.)
|
||||
* Matrix4x4::scaling(10., 0.01, 10.),
|
||||
);
|
||||
left_wall.material = floor.material.clone();
|
||||
left_wall.set_material(floor.material().clone());
|
||||
|
||||
let mut right_wall = Shape::sphere();
|
||||
right_wall.set_transform(
|
||||
@@ -63,36 +63,36 @@ fn main() -> Result<()> {
|
||||
* Matrix4x4::rotation_x(PI / 2.)
|
||||
* Matrix4x4::scaling(10., 0.01, 10.),
|
||||
);
|
||||
right_wall.material = floor.material.clone();
|
||||
right_wall.set_material(floor.material().clone());
|
||||
|
||||
let mut middle = Shape::sphere();
|
||||
middle.set_transform(Matrix4x4::translation(-0.5, 1., 0.5));
|
||||
middle.material = Material {
|
||||
color: Color::new(0.1, 1., 0.5).into(),
|
||||
middle.set_material(Material {
|
||||
color: Color::new(0.1, 1., 0.5),
|
||||
diffuse: 0.7,
|
||||
specular: 0.3,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
|
||||
let mut right = Shape::sphere();
|
||||
right.set_transform(Matrix4x4::translation(1.5, 0.5, -0.5) * Matrix4x4::scaling(0.5, 0.5, 0.5));
|
||||
right.material = Material {
|
||||
color: Color::new(0.5, 1., 0.1).into(),
|
||||
right.set_material(Material {
|
||||
color: Color::new(0.5, 1., 0.1),
|
||||
diffuse: 0.7,
|
||||
specular: 0.3,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
|
||||
let mut left = Shape::sphere();
|
||||
left.set_transform(
|
||||
Matrix4x4::translation(-1.5, 0.33, -0.75) * Matrix4x4::scaling(0.33, 0.33, 0.33),
|
||||
);
|
||||
left.material = Material {
|
||||
color: Color::new(1., 0.8, 0.1).into(),
|
||||
left.set_material(Material {
|
||||
color: Color::new(1., 0.8, 0.1),
|
||||
diffuse: 0.7,
|
||||
specular: 0.3,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
|
||||
let mut world = World::default();
|
||||
world.lights = vec![light];
|
||||
|
||||
@@ -53,11 +53,11 @@ fn main() -> Result<()> {
|
||||
|
||||
let mut floor = Shape::sphere();
|
||||
floor.set_transform(Matrix4x4::scaling(10., 0.01, 10.));
|
||||
floor.material = Material {
|
||||
color: Color::new(1., 0.9, 0.9).into(),
|
||||
floor.set_material(Material {
|
||||
color: Color::new(1., 0.9, 0.9),
|
||||
specular: 0.,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
|
||||
let mut left_wall = Shape::sphere();
|
||||
left_wall.set_transform(
|
||||
@@ -66,7 +66,7 @@ fn main() -> Result<()> {
|
||||
* Matrix4x4::rotation_x(PI / 2.)
|
||||
* Matrix4x4::scaling(10., 0.01, 10.),
|
||||
);
|
||||
left_wall.material = floor.material.clone();
|
||||
left_wall.set_material(floor.material().clone());
|
||||
|
||||
let mut right_wall = Shape::sphere();
|
||||
right_wall.set_transform(
|
||||
@@ -75,36 +75,36 @@ fn main() -> Result<()> {
|
||||
* Matrix4x4::rotation_x(PI / 2.)
|
||||
* Matrix4x4::scaling(10., 0.00001, 10.),
|
||||
);
|
||||
right_wall.material = floor.material.clone();
|
||||
right_wall.set_material(floor.material().clone());
|
||||
|
||||
let mut middle = Shape::sphere();
|
||||
middle.set_transform(Matrix4x4::translation(-0.5, 1., 0.5));
|
||||
middle.material = Material {
|
||||
color: Color::new(0.1, 1., 0.5).into(),
|
||||
middle.set_material(Material {
|
||||
color: Color::new(0.1, 1., 0.5),
|
||||
diffuse: 0.7,
|
||||
specular: 0.3,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
|
||||
let mut right = Shape::sphere();
|
||||
right.set_transform(Matrix4x4::translation(1.5, 0.5, -0.5) * Matrix4x4::scaling(0.5, 0.5, 0.5));
|
||||
right.material = Material {
|
||||
color: Color::new(1., 1., 1.).into(),
|
||||
right.set_material(Material {
|
||||
color: Color::new(1., 1., 1.),
|
||||
diffuse: 0.7,
|
||||
specular: 0.0,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
|
||||
let mut left = Shape::sphere();
|
||||
left.set_transform(
|
||||
Matrix4x4::translation(-1.5, 0.33, -0.75) * Matrix4x4::scaling(0.33, 0.33, 0.33),
|
||||
);
|
||||
left.material = Material {
|
||||
color: Color::new(1., 0.8, 0.1).into(),
|
||||
left.set_material(Material {
|
||||
color: Color::new(1., 0.8, 0.1),
|
||||
diffuse: 0.7,
|
||||
specular: 0.3,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
|
||||
let mut world = World::default();
|
||||
world.lights = vec![light1, light2, light3];
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use rtchallenge::prelude::*;
|
||||
|
||||
use rtchallenge::{camera::RenderStrategy, float::consts::PI, WHITE};
|
||||
|
||||
/// End of chapter 9 challenge.
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "eoc9")]
|
||||
struct Opt {
|
||||
/// Strategy for casting rays into image.
|
||||
#[structopt(long, default_value = "rayon")]
|
||||
render_strategy: RenderStrategy,
|
||||
/// Number of samples per pixel. 0 renders from the center of the pixel, 1 or more samples N
|
||||
/// times randomly across the pixel.
|
||||
#[structopt(short, long, default_value = "0")]
|
||||
samples: usize,
|
||||
/// Rendered image width in pixels.
|
||||
#[structopt(short, long, default_value = "2560")]
|
||||
width: usize,
|
||||
/// Rendered image height in pixels.
|
||||
#[structopt(short, long, default_value = "1440")]
|
||||
height: usize,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let opt = Opt::from_args();
|
||||
|
||||
let light1 = PointLightBuilder::default()
|
||||
.position(point(-5., 5., -5.))
|
||||
.intensity(WHITE)
|
||||
.build()?;
|
||||
let light2 = PointLightBuilder::default()
|
||||
.position(point(5., 5., -5.))
|
||||
.intensity([0.2, 0.2, 0.6])
|
||||
.build()?;
|
||||
let light3 = PointLightBuilder::default()
|
||||
.position(point(0., 2., -5.))
|
||||
.intensity([0.2, 0.2, 0.1])
|
||||
.build()?;
|
||||
|
||||
let from = point(0., 1.5, -5.);
|
||||
let to = point(0., 1., 0.);
|
||||
let up = point(0., 1., 0.);
|
||||
let camera = CameraBuilder::default()
|
||||
.hsize(opt.width)
|
||||
.vsize(opt.height)
|
||||
.field_of_view(PI / 4.)
|
||||
.transform(view_transform(from, to, up))
|
||||
.render_strategy(opt.render_strategy)
|
||||
.samples_per_pixel(opt.samples)
|
||||
.build()?;
|
||||
|
||||
let floor = plane()
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([1., 0.2, 0.2])
|
||||
.specular(0.)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let ceiling = plane()
|
||||
.transform(translation(0., 6., 0.) * rotation_x(PI))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.6, 0.6, 0.8])
|
||||
.specular(0.2)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let middle = sphere()
|
||||
.transform(translation(-0.5, 0.5, 0.5))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.1, 1., 0.5])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let right = sphere()
|
||||
.transform(translation(1.5, 0.5, -0.5) * scaling(0.5, 0.5, 0.5))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([1., 1., 1.])
|
||||
.diffuse(0.7)
|
||||
.specular(0.0)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let left = sphere()
|
||||
.transform(translation(-1.5, 0.33, -0.75) * scaling(0.33, 0.33, 0.33))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([1., 0.8, 0.1])
|
||||
.diffuse(0.7)
|
||||
.specular(0.3)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let world = WorldBuilder::default()
|
||||
.lights(vec![light1, light2, light3])
|
||||
.objects(vec![floor, ceiling, middle, right, left])
|
||||
.build()?;
|
||||
|
||||
let image = camera.render(&world);
|
||||
|
||||
let path = "/tmp/eoc9.png";
|
||||
println!("saving output to {}", path);
|
||||
image.write_to_file(path)?;
|
||||
println!("Render time {:.3} seconds", start.elapsed().as_secs_f32());
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use rtchallenge::{
|
||||
camera::{Camera, RenderStrategy},
|
||||
float::consts::PI,
|
||||
lights::PointLight,
|
||||
materials::Material,
|
||||
matrices::Matrix4x4,
|
||||
shapes::Shape,
|
||||
transformations::view_transform,
|
||||
tuples::{Color, Tuple},
|
||||
world::World,
|
||||
WHITE,
|
||||
};
|
||||
|
||||
/// End of chapter 9 challenge.
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "eoc9")]
|
||||
struct Opt {
|
||||
/// Strategy for casting rays into image.
|
||||
#[structopt(long, default_value = "rayon")]
|
||||
render_strategy: RenderStrategy,
|
||||
/// Number of samples per pixel. 0 renders from the center of the pixel, 1 or more samples N
|
||||
/// times randomly across the pixel.
|
||||
#[structopt(short, long, default_value = "0")]
|
||||
samples: usize,
|
||||
/// Rendered image width in pixels.
|
||||
#[structopt(short, long, default_value = "2560")]
|
||||
width: usize,
|
||||
/// Rendered image height in pixels.
|
||||
#[structopt(short, long, default_value = "1440")]
|
||||
height: usize,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let opt = Opt::from_args();
|
||||
|
||||
let light_position = Tuple::point(-5., 5., -5.);
|
||||
let light_color = WHITE;
|
||||
let light1 = PointLight::new(light_position, light_color);
|
||||
let light_position = Tuple::point(5., 5., -5.);
|
||||
let light_color = Color::new(0.2, 0.2, 0.6);
|
||||
let light2 = PointLight::new(light_position, light_color);
|
||||
let light_position = Tuple::point(0., 2., -5.);
|
||||
let light_color = Color::new(0.2, 0.2, 0.1);
|
||||
let light3 = PointLight::new(light_position, light_color);
|
||||
|
||||
let mut camera = Camera::new(opt.width, opt.height, PI / 4.);
|
||||
let from = Tuple::point(0., 1.5, -5.);
|
||||
let to = Tuple::point(0., 1., 0.);
|
||||
let up = Tuple::point(0., 1., 0.);
|
||||
camera.set_transform(view_transform(from, to, up));
|
||||
camera.render_strategy = opt.render_strategy;
|
||||
camera.samples_per_pixel = opt.samples;
|
||||
|
||||
let mut floor = Shape::plane();
|
||||
floor.material = Material {
|
||||
color: Color::new(1., 0.2, 0.2).into(),
|
||||
specular: 0.,
|
||||
..Material::default()
|
||||
};
|
||||
let mut ceiling = Shape::plane();
|
||||
ceiling.set_transform(Matrix4x4::translation(0., 6., 0.) * Matrix4x4::rotation_x(PI));
|
||||
ceiling.material = Material {
|
||||
color: Color::new(0.6, 0.6, 0.8).into(),
|
||||
specular: 0.2,
|
||||
..Material::default()
|
||||
};
|
||||
|
||||
let mut middle = Shape::sphere();
|
||||
middle.set_transform(Matrix4x4::translation(-0.5, 0.5, 0.5));
|
||||
middle.material = Material {
|
||||
color: Color::new(0.1, 1., 0.5).into(),
|
||||
diffuse: 0.7,
|
||||
specular: 0.3,
|
||||
..Material::default()
|
||||
};
|
||||
|
||||
let mut right = Shape::sphere();
|
||||
right.set_transform(Matrix4x4::translation(1.5, 0.5, -0.5) * Matrix4x4::scaling(0.5, 0.5, 0.5));
|
||||
right.material = Material {
|
||||
color: Color::new(1., 1., 1.).into(),
|
||||
diffuse: 0.7,
|
||||
specular: 0.0,
|
||||
..Material::default()
|
||||
};
|
||||
|
||||
let mut left = Shape::sphere();
|
||||
left.set_transform(
|
||||
Matrix4x4::translation(-1.5, 0.33, -0.75) * Matrix4x4::scaling(0.33, 0.33, 0.33),
|
||||
);
|
||||
left.material = Material {
|
||||
color: Color::new(1., 0.8, 0.1).into(),
|
||||
diffuse: 0.7,
|
||||
specular: 0.3,
|
||||
..Material::default()
|
||||
};
|
||||
|
||||
let mut world = World::default();
|
||||
world.lights = vec![light1, light2, light3];
|
||||
world.objects = vec![floor, ceiling, middle, right, left];
|
||||
|
||||
let image = camera.render(&world);
|
||||
|
||||
let path = "/tmp/eoc9.png";
|
||||
println!("saving output to {}", path);
|
||||
image.write_to_file(path)?;
|
||||
println!("Render time {:.3} seconds", start.elapsed().as_secs_f32());
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use rtchallenge::prelude::*;
|
||||
|
||||
use rtchallenge::{
|
||||
camera::RenderStrategy,
|
||||
float::consts::PI,
|
||||
patterns::{BLACK_PAT, WHITE_PAT},
|
||||
WHITE,
|
||||
};
|
||||
|
||||
/// Experiment with transparency.
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "glass")]
|
||||
struct Opt {
|
||||
/// Strategy for casting rays into image.
|
||||
#[structopt(long, default_value = "rayon")]
|
||||
render_strategy: RenderStrategy,
|
||||
/// Number of samples per pixel. 0 renders from the center of the pixel, 1 or more samples N
|
||||
/// times randomly across the pixel.
|
||||
#[structopt(short, long, default_value = "0")]
|
||||
samples: usize,
|
||||
/// Rendered image width in pixels.
|
||||
#[structopt(short, long, default_value = "2560")]
|
||||
width: usize,
|
||||
/// Rendered image height in pixels.
|
||||
#[structopt(short, long, default_value = "1440")]
|
||||
height: usize,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let opt = Opt::from_args();
|
||||
|
||||
let light1 = PointLightBuilder::default()
|
||||
.position(point(-5., 5., -5.))
|
||||
.intensity(WHITE)
|
||||
.build()?;
|
||||
let light2 = PointLightBuilder::default()
|
||||
.position(point(5., 5., -5.))
|
||||
.intensity([0.2, 0.2, 0.6])
|
||||
.build()?;
|
||||
let light3 = PointLightBuilder::default()
|
||||
.position(point(0., 2., -5.))
|
||||
.intensity([0.2, 0.2, 0.1])
|
||||
.build()?;
|
||||
|
||||
let from = point(0., 0., -10.);
|
||||
let to = point(0., 0., 0.);
|
||||
let up = point(0., 1., 0.);
|
||||
let camera = CameraBuilder::default()
|
||||
.hsize(opt.width)
|
||||
.vsize(opt.height)
|
||||
.field_of_view(PI / 4.)
|
||||
.transform(view_transform(from, to, up))
|
||||
.render_strategy(opt.render_strategy)
|
||||
.samples_per_pixel(opt.samples)
|
||||
.build()?;
|
||||
|
||||
let floor = plane()
|
||||
.transform(rotation_x(PI / 2.))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color(checkers_pattern(BLACK_PAT, WHITE_PAT).build()?)
|
||||
.reflective(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
let ceiling = plane()
|
||||
.transform(translation(0., 0., -20.) * rotation_x(PI / 2.))
|
||||
.material(MaterialBuilder::default().color([0.2, 0.2, 0.8]).build()?)
|
||||
.build()?;
|
||||
|
||||
let mut objects = Vec::new();
|
||||
for x in 0..5 {
|
||||
for y in 0..5 {
|
||||
let trans = y as Float / 5.;
|
||||
let index = 1. + x as Float / 5.;
|
||||
dbg!(x, y, trans, index);
|
||||
objects.push(
|
||||
sphere()
|
||||
.transform(
|
||||
translation(x as Float - 2., y as Float - 2., -2.) * scaling(0.5, 0.5, 0.5),
|
||||
)
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([0.5, 0.5, 0.5])
|
||||
.transparency(trans)
|
||||
.refractive_index(index)
|
||||
.build()?,
|
||||
)
|
||||
.build()?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
objects.push(floor);
|
||||
objects.push(ceiling);
|
||||
|
||||
let world = WorldBuilder::default()
|
||||
.lights(vec![light1, light2, light3])
|
||||
.objects(objects)
|
||||
.build()?;
|
||||
|
||||
let image = camera.render(&world);
|
||||
|
||||
let path = "/tmp/glass.png";
|
||||
println!("saving output to {}", path);
|
||||
image.write_to_file(path)?;
|
||||
println!("Render time {:.3} seconds", start.elapsed().as_secs_f32());
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,2 +1 @@
|
||||
imports_granularity = "Crate"
|
||||
format_code_in_doc_comments = true
|
||||
|
||||
@@ -2,12 +2,11 @@ use std::{
|
||||
str::FromStr,
|
||||
sync::{
|
||||
mpsc::{sync_channel, Receiver, SyncSender},
|
||||
Arc, Mutex,
|
||||
{Arc, Mutex},
|
||||
},
|
||||
thread,
|
||||
};
|
||||
|
||||
use derive_builder::Builder;
|
||||
use rand::Rng;
|
||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
||||
use serde::Deserialize;
|
||||
@@ -22,8 +21,6 @@ use crate::{
|
||||
Float, BLACK,
|
||||
};
|
||||
|
||||
const MAX_DEPTH_RECURSION: usize = 10;
|
||||
|
||||
#[derive(Copy, Clone, StructOpt, Debug, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum RenderStrategy {
|
||||
@@ -31,82 +28,28 @@ pub enum RenderStrategy {
|
||||
Rayon,
|
||||
WorkerPool,
|
||||
}
|
||||
|
||||
impl Default for RenderStrategy {
|
||||
fn default() -> RenderStrategy {
|
||||
RenderStrategy::Rayon
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for RenderStrategy {
|
||||
type Err = serde_json::error::Error;
|
||||
fn from_str(s: &str) -> Result<RenderStrategy, serde_json::error::Error> {
|
||||
serde_json::from_str(&format!("\"{}\"", s))
|
||||
Ok(serde_json::from_str(&format!("\"{}\"", s))?)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Builder, Clone, Debug, Default)]
|
||||
#[builder(setter(skip), build_fn(skip))]
|
||||
#[derive(Clone)]
|
||||
pub struct Camera {
|
||||
#[builder(setter(skip = "false"))]
|
||||
hsize: usize,
|
||||
#[builder(setter(skip = "false"))]
|
||||
vsize: usize,
|
||||
#[builder(setter(skip = "false"))]
|
||||
field_of_view: Float,
|
||||
#[builder(setter(skip = "false"))]
|
||||
transform: Matrix4x4,
|
||||
inverse_transform: Matrix4x4,
|
||||
pixel_size: Float,
|
||||
half_width: Float,
|
||||
half_height: Float,
|
||||
#[builder(setter(skip = "false"))]
|
||||
pub render_strategy: RenderStrategy,
|
||||
/// 0 renders from the center of the pixel, 1 or higher is random sampling of the pixel.
|
||||
#[builder(setter(skip = "false"))]
|
||||
pub samples_per_pixel: usize,
|
||||
}
|
||||
|
||||
impl CameraBuilder {
|
||||
pub fn build(&self) -> Result<Camera, CameraBuilderError> {
|
||||
let hsize = match self.hsize {
|
||||
Some(ref value) => Clone::clone(value),
|
||||
None => {
|
||||
return Err(Into::into(::derive_builder::UninitializedFieldError::from(
|
||||
"hsize",
|
||||
)))
|
||||
}
|
||||
};
|
||||
let vsize = match self.vsize {
|
||||
Some(ref value) => Clone::clone(value),
|
||||
None => {
|
||||
return Err(Into::into(::derive_builder::UninitializedFieldError::from(
|
||||
"vsize",
|
||||
)))
|
||||
}
|
||||
};
|
||||
let field_of_view = match self.field_of_view {
|
||||
Some(ref value) => Clone::clone(value),
|
||||
None => {
|
||||
return Err(Into::into(::derive_builder::UninitializedFieldError::from(
|
||||
"field_of_view",
|
||||
)))
|
||||
}
|
||||
};
|
||||
let mut c = Camera::new(hsize, vsize, field_of_view);
|
||||
if let Some(transform) = self.transform {
|
||||
c.set_transform(transform);
|
||||
}
|
||||
if let Some(render_strategy) = self.render_strategy {
|
||||
c.render_strategy = render_strategy;
|
||||
}
|
||||
if let Some(samples_per_pixel) = self.samples_per_pixel {
|
||||
c.samples_per_pixel = samples_per_pixel;
|
||||
}
|
||||
Ok(c)
|
||||
}
|
||||
}
|
||||
|
||||
enum Request {
|
||||
Line { width: usize, y: usize },
|
||||
}
|
||||
@@ -118,6 +61,27 @@ enum Response {
|
||||
impl Camera {
|
||||
/// Create a camera with a canvas of pixel hsize (height) and vsize (width)
|
||||
/// with the given field of view (in radians).
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{camera::Camera, float::consts::PI, matrices::Matrix4x4, EPSILON};
|
||||
///
|
||||
/// let hsize = 160;
|
||||
/// let vsize = 120;
|
||||
/// let field_of_view = PI / 2.;
|
||||
/// let c = Camera::new(hsize, vsize, field_of_view);
|
||||
/// assert_eq!(c.hsize(), 160);
|
||||
/// assert_eq!(c.vsize(), 120);
|
||||
/// assert_eq!(c.transform(), Matrix4x4::identity());
|
||||
///
|
||||
/// // Pixel size for a horizontal canvas.
|
||||
/// let c = Camera::new(200, 150, PI / 2.);
|
||||
/// assert!((c.pixel_size() - 0.010).abs() < EPSILON);
|
||||
///
|
||||
/// // Pixel size for a horizontal canvas.
|
||||
/// let c = Camera::new(150, 200, PI / 2.);
|
||||
/// assert!((c.pixel_size() - 0.010).abs() < EPSILON);
|
||||
/// ```
|
||||
pub fn new(hsize: usize, vsize: usize, field_of_view: Float) -> Camera {
|
||||
let half_view = (field_of_view / 2.).tan();
|
||||
let aspect = hsize as Float / vsize as Float;
|
||||
@@ -187,17 +151,47 @@ impl Camera {
|
||||
|
||||
/// Calculate ray that starts at the camera and passes through the (x,y)
|
||||
/// pixel on the canvas.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// camera::Camera, float::consts::PI, matrices::Matrix4x4, tuples::Tuple, Float,
|
||||
/// };
|
||||
///
|
||||
/// // Constructing a ray through the center of the canvas.
|
||||
/// let c = Camera::new(201, 101, PI / 2.);
|
||||
/// let r = c.ray_for_pixel(100, 50);
|
||||
/// assert_eq!(r.origin, Tuple::point(0., 0., 0.));
|
||||
/// assert_eq!(r.direction, Tuple::vector(0., 0., -1.));
|
||||
///
|
||||
/// // Constructing a ray through the corner of the canvas.
|
||||
/// let c = Camera::new(201, 101, PI / 2.);
|
||||
/// let r = c.ray_for_pixel(0, 0);
|
||||
/// assert_eq!(r.origin, Tuple::point(0., 0., 0.));
|
||||
/// assert_eq!(r.direction, Tuple::vector(0.66519, 0.33259, -0.66851));
|
||||
///
|
||||
/// // Constructing a ray when the camera is transformed.
|
||||
/// let mut c = Camera::new(201, 101, PI / 2.);
|
||||
/// c.set_transform(Matrix4x4::rotation_y(PI / 4.) * Matrix4x4::translation(0., -2., 5.));
|
||||
/// let r = c.ray_for_pixel(100, 50);
|
||||
/// assert_eq!(r.origin, Tuple::point(0., 2., -5.));
|
||||
/// assert_eq!(
|
||||
/// r.direction,
|
||||
/// Tuple::vector((2. as Float).sqrt() / 2., 0., -(2. as Float).sqrt() / 2.)
|
||||
/// );
|
||||
/// ```
|
||||
#[cfg(not(feature = "disable-inverse-cache"))]
|
||||
pub fn ray_for_pixel(&self, px: usize, py: usize) -> Ray {
|
||||
// The offset from the edge of the canvas to the pixel's corner.
|
||||
let xoffset = (px as Float + 0.5) * self.pixel_size;
|
||||
let yoffset = (py as Float + 0.5) * self.pixel_size;
|
||||
|
||||
// The untransformed coordinates of the pixel in world space.
|
||||
// The untransformed coordinates of the pixle in world space.
|
||||
// (Remember that the camera looks toward -z, so +x is to the left.)
|
||||
let world_x = self.half_width - xoffset;
|
||||
let world_y = self.half_height - yoffset;
|
||||
|
||||
// Using the camera matrix, transform the canvas point and the origin,
|
||||
// Using the camera matrix, transofmrm the canvas point and the origin,
|
||||
// and then compute the ray's direction vector.
|
||||
// (Remember that the canvas is at z>=-1).
|
||||
let pixel = self.inverse_transform * Tuple::point(world_x, world_y, -1.);
|
||||
@@ -206,8 +200,48 @@ impl Camera {
|
||||
|
||||
Ray::new(origin, direction)
|
||||
}
|
||||
#[cfg(feature = "disable-inverse-cache")]
|
||||
pub fn ray_for_pixel(&self, px: usize, py: usize) -> Ray {
|
||||
// The offset from the edge of the canvas to the pixel's corner.
|
||||
let xoffset = (px as Float + 0.5) * self.pixel_size;
|
||||
let yoffset = (py as Float + 0.5) * self.pixel_size;
|
||||
|
||||
// The untransformed coordinates of the pixle in world space.
|
||||
// (Remember that the camera looks toward -z, so +x is to the left.)
|
||||
let world_x = self.half_width - xoffset;
|
||||
let world_y = self.half_height - yoffset;
|
||||
|
||||
// Using the camera matrix, transofmrm the canvas point and the origin,
|
||||
// and then compute the ray's direction vector.
|
||||
// (Remember that the canvas is at z>=-1).
|
||||
let pixel = self.transform.inverse() * Tuple::point(world_x, world_y, -1.);
|
||||
let origin = self.transform.inverse() * Tuple::point(0., 0., 0.);
|
||||
let direction = (pixel - origin).normalize();
|
||||
|
||||
Ray::new(origin, direction)
|
||||
}
|
||||
|
||||
/// Use camera to render an image of the given world.
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// camera::Camera,
|
||||
/// float::consts::PI,
|
||||
/// transformations::view_transform,
|
||||
/// tuples::{Color, Tuple},
|
||||
/// world::World,
|
||||
/// };
|
||||
///
|
||||
/// // Rendering a world with a camera.
|
||||
/// let w = World::test_world();
|
||||
/// let mut c = Camera::new(11, 11, PI / 2.);
|
||||
/// let from = Tuple::point(0., 0., -5.);
|
||||
/// let to = Tuple::point(0., 0., 0.);
|
||||
/// let up = Tuple::vector(0., 1., 0.);
|
||||
/// c.set_transform(view_transform(from, to, up));
|
||||
/// let image = c.render(&w);
|
||||
/// assert_eq!(image.get(5, 5), Color::new(0.38066, 0.47583, 0.2855));
|
||||
/// ```
|
||||
pub fn render(&self, w: &World) -> Canvas {
|
||||
use RenderStrategy::*;
|
||||
|
||||
@@ -327,12 +361,12 @@ impl Camera {
|
||||
let color = self
|
||||
.supersample_rays_for_pixel(x, y, self.samples_per_pixel)
|
||||
.iter()
|
||||
.map(|ray| w.color_at(ray, MAX_DEPTH_RECURSION))
|
||||
.map(|ray| w.color_at(&ray))
|
||||
.fold(BLACK, |acc, c| acc + c);
|
||||
color / self.samples_per_pixel as Float
|
||||
} else {
|
||||
let ray = self.ray_for_pixel(x, y);
|
||||
w.color_at(&ray, MAX_DEPTH_RECURSION)
|
||||
w.color_at(&ray)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -367,70 +401,3 @@ fn render_worker_task(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
float::consts::PI,
|
||||
matrices::Matrix4x4,
|
||||
transformations::view_transform,
|
||||
tuples::{point, vector},
|
||||
world::World,
|
||||
Float, EPSILON,
|
||||
};
|
||||
#[test]
|
||||
fn new() {
|
||||
let hsize = 160;
|
||||
let vsize = 120;
|
||||
let field_of_view = PI / 2.;
|
||||
let c = Camera::new(hsize, vsize, field_of_view);
|
||||
assert_eq!(c.hsize(), 160);
|
||||
assert_eq!(c.vsize(), 120);
|
||||
assert_eq!(c.transform(), Matrix4x4::identity());
|
||||
|
||||
// Pixel size for a horizontal canvas.
|
||||
let c = Camera::new(200, 150, PI / 2.);
|
||||
assert!((c.pixel_size() - 0.010).abs() < EPSILON);
|
||||
|
||||
// Pixel size for a horizontal canvas.
|
||||
let c = Camera::new(150, 200, PI / 2.);
|
||||
assert!((c.pixel_size() - 0.010).abs() < EPSILON);
|
||||
}
|
||||
#[test]
|
||||
fn ray_for_pixel() {
|
||||
// Constructing a ray through the center of the canvas.
|
||||
let c = Camera::new(201, 101, PI / 2.);
|
||||
let r = c.ray_for_pixel(100, 50);
|
||||
assert_eq!(r.origin, point(0., 0., 0.));
|
||||
assert_eq!(r.direction, vector(0., 0., -1.));
|
||||
|
||||
// Constructing a ray through the corner of the canvas.
|
||||
let c = Camera::new(201, 101, PI / 2.);
|
||||
let r = c.ray_for_pixel(0, 0);
|
||||
assert_eq!(r.origin, point(0., 0., 0.));
|
||||
assert_eq!(r.direction, vector(0.66519, 0.33259, -0.66851));
|
||||
|
||||
// Constructing a ray when the camera is transformed.
|
||||
let mut c = Camera::new(201, 101, PI / 2.);
|
||||
c.set_transform(Matrix4x4::rotation_y(PI / 4.) * Matrix4x4::translation(0., -2., 5.));
|
||||
let r = c.ray_for_pixel(100, 50);
|
||||
assert_eq!(r.origin, point(0., 2., -5.));
|
||||
assert_eq!(
|
||||
r.direction,
|
||||
vector((2. as Float).sqrt() / 2., 0., -(2. as Float).sqrt() / 2.)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn render() {
|
||||
// Rendering a world with a camera.
|
||||
let w = World::test_world();
|
||||
let mut c = Camera::new(11, 11, PI / 2.);
|
||||
let from = point(0., 0., -5.);
|
||||
let to = point(0., 0., 0.);
|
||||
let up = vector(0., 1., 0.);
|
||||
c.set_transform(view_transform(from, to, up));
|
||||
let image = c.render(&w);
|
||||
assert_eq!(image.get(5, 5), [0.38066, 0.47583, 0.2855].into());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use std::{fs::File, io::BufWriter, path::Path};
|
||||
use std::fs::File;
|
||||
use std::io::BufWriter;
|
||||
use std::path::Path;
|
||||
|
||||
use png;
|
||||
use thiserror::Error;
|
||||
@@ -46,7 +48,7 @@ impl Canvas {
|
||||
{
|
||||
let path = Path::new(path.as_ref());
|
||||
let file = File::create(path)?;
|
||||
let w = &mut BufWriter::new(file);
|
||||
let ref mut w = BufWriter::new(file);
|
||||
|
||||
let mut encoder = png::Encoder::new(w, self.width as u32, self.height as u32);
|
||||
encoder.set_color(png::ColorType::RGB);
|
||||
|
||||
@@ -3,50 +3,114 @@ use std::ops::Index;
|
||||
use crate::{
|
||||
rays::Ray,
|
||||
shapes::Shape,
|
||||
tuples::{dot, reflect, Tuple},
|
||||
tuples::{dot, Tuple},
|
||||
Float, EPSILON,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Intersection<'i> {
|
||||
pub t: Float,
|
||||
pub object: &'i Shape,
|
||||
}
|
||||
impl<'i> PartialEq for Intersection<'i> {
|
||||
fn eq(&self, rhs: &Intersection) -> bool {
|
||||
((self.t - rhs.t).abs() < EPSILON) && (self.object == rhs.object)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'i> Intersection<'i> {
|
||||
/// Create new `Intersection` at the given `t` that hits the given `object`.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{intersections::Intersection, shapes::Shape};
|
||||
///
|
||||
/// // An intersection ecapsulates t and object.
|
||||
/// let s = Shape::sphere();
|
||||
/// let i = Intersection::new(3.5, &s);
|
||||
/// assert_eq!(i.t, 3.5);
|
||||
/// assert_eq!(i.object, &s);
|
||||
/// ```
|
||||
pub fn new(t: Float, object: &Shape) -> Intersection {
|
||||
Intersection { t, object }
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggregates `Intersection`s.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// intersections::{Intersection, Intersections},
|
||||
/// rays::Ray,
|
||||
/// shapes::{intersect, Shape},
|
||||
/// tuples::Tuple,
|
||||
/// };
|
||||
///
|
||||
/// let s = Shape::sphere();
|
||||
/// let i1 = Intersection::new(1., &s);
|
||||
/// let i2 = Intersection::new(2., &s);
|
||||
/// let xs = Intersections::new(vec![i1, i2]);
|
||||
/// assert_eq!(xs.len(), 2);
|
||||
/// assert_eq!(xs[0].t, 1.);
|
||||
/// assert_eq!(xs[1].t, 2.);
|
||||
///
|
||||
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
|
||||
/// let xs = intersect(&s, &r);
|
||||
/// assert_eq!(xs.len(), 2);
|
||||
/// assert_eq!(xs[0].object, &s);
|
||||
/// assert_eq!(xs[1].object, &s);
|
||||
/// ```
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Intersections<'i>(Vec<Intersection<'i>>);
|
||||
|
||||
/// Create an [Intersections] from a single [Intersection] to aid in tests.
|
||||
impl<'i> From<Intersection<'i>> for Intersections<'i> {
|
||||
fn from(i: Intersection<'i>) -> Intersections<'i> {
|
||||
Intersections::new(vec![i])
|
||||
}
|
||||
}
|
||||
|
||||
impl<'i> Intersections<'i> {
|
||||
pub fn new(xs: Vec<Intersection<'i>>) -> Intersections {
|
||||
Intersections(xs)
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
/// Finds nearest hit for this collection of intersections.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// intersections::{Intersection, Intersections},
|
||||
/// rays::Ray,
|
||||
/// shapes::{intersect, Shape},
|
||||
/// tuples::Tuple,
|
||||
/// };
|
||||
///
|
||||
/// // The hit, when all intersections have positive t.
|
||||
/// let s = Shape::sphere();
|
||||
/// let i1 = Intersection::new(1., &s);
|
||||
/// let i2 = Intersection::new(2., &s);
|
||||
/// let xs = Intersections::new(vec![i2, i1.clone()]);
|
||||
/// let i = xs.hit();
|
||||
/// assert_eq!(i, Some(&i1));
|
||||
///
|
||||
/// // The hit, when some intersections have negative t.
|
||||
/// let s = Shape::sphere();
|
||||
/// let i1 = Intersection::new(-1., &s);
|
||||
/// let i2 = Intersection::new(1., &s);
|
||||
/// let xs = Intersections::new(vec![i2.clone(), i1]);
|
||||
/// let i = xs.hit();
|
||||
/// assert_eq!(i, Some(&i2));
|
||||
///
|
||||
/// // The hit, when all intersections have negative t.
|
||||
/// let s = Shape::sphere();
|
||||
/// let i1 = Intersection::new(-2., &s);
|
||||
/// let i2 = Intersection::new(-1., &s);
|
||||
/// let xs = Intersections::new(vec![i2, i1]);
|
||||
/// let i = xs.hit();
|
||||
/// assert_eq!(i, None);
|
||||
///
|
||||
/// // The hit is always the lowest nonnegative intersection.
|
||||
/// let s = Shape::sphere();
|
||||
/// let i1 = Intersection::new(5., &s);
|
||||
/// let i2 = Intersection::new(7., &s);
|
||||
/// let i3 = Intersection::new(-3., &s);
|
||||
/// let i4 = Intersection::new(2., &s);
|
||||
/// let xs = Intersections::new(vec![i1, i2, i3, i4.clone()]);
|
||||
/// let i = xs.hit();
|
||||
/// assert_eq!(i, Some(&i4));
|
||||
/// ```
|
||||
pub fn hit(&self) -> Option<&Intersection> {
|
||||
self.0.iter().filter(|i| i.t > 0.).min_by(|i1, i2| {
|
||||
i1.t.partial_cmp(&i2.t)
|
||||
@@ -76,358 +140,81 @@ pub struct PrecomputedData<'i> {
|
||||
pub t: Float,
|
||||
pub object: &'i Shape,
|
||||
pub point: Tuple,
|
||||
pub under_point: Tuple,
|
||||
pub over_point: Tuple,
|
||||
pub eyev: Tuple,
|
||||
pub normalv: Tuple,
|
||||
pub reflectv: Tuple,
|
||||
pub inside: bool,
|
||||
pub n1: Float,
|
||||
pub n2: Float,
|
||||
}
|
||||
|
||||
/// Precomputes data common to all intersections.
|
||||
pub fn prepare_computations<'i>(
|
||||
hit: &'i Intersection,
|
||||
r: &Ray,
|
||||
xs: &Intersections,
|
||||
) -> PrecomputedData<'i> {
|
||||
let point = r.position(hit.t);
|
||||
let normalv = hit.object.normal_at(point);
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// intersections::{prepare_computations, Intersection, Intersections},
|
||||
/// rays::Ray,
|
||||
/// matrices::Matrix4x4,
|
||||
/// shapes::{intersect, Shape},
|
||||
/// tuples::Tuple,
|
||||
/// EPSILON
|
||||
/// };
|
||||
///
|
||||
/// // Precomputing the state of an intersection.
|
||||
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
|
||||
/// let shape = Shape::sphere();
|
||||
/// let i = Intersection::new(4., &shape);
|
||||
/// let comps = prepare_computations(&i, &r);
|
||||
/// assert_eq!(comps.t, i.t);
|
||||
/// assert_eq!(comps.object, i.object);
|
||||
/// assert_eq!(comps.point, Tuple::point(0., 0., -1.));
|
||||
/// assert_eq!(comps.eyev, Tuple::vector(0., 0., -1.));
|
||||
/// assert_eq!(comps.normalv, Tuple::vector(0., 0., -1.));
|
||||
///
|
||||
/// // The hit, when an intersection occurs on the outside.
|
||||
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
|
||||
/// let shape = Shape::sphere();
|
||||
/// let i = Intersection::new(4., &shape);
|
||||
/// let comps = prepare_computations(&i, &r);
|
||||
/// assert_eq!(comps.inside, false);
|
||||
///
|
||||
/// // The hit, when an intersection occurs on the inside.
|
||||
/// let r = Ray::new(Tuple::point(0., 0., 0.), Tuple::vector(0., 0., 1.));
|
||||
/// let shape = Shape::sphere();
|
||||
/// let i = Intersection::new(1., &shape);
|
||||
/// let comps = prepare_computations(&i, &r);
|
||||
/// assert_eq!(comps.point, Tuple::point(0., 0., 1.));
|
||||
/// assert_eq!(comps.eyev, Tuple::vector(0., 0., -1.));
|
||||
/// assert_eq!(comps.inside, true);
|
||||
//// // Normal would have been (0, 0, 1), but is inverted when inside.
|
||||
/// assert_eq!(comps.normalv, Tuple::vector(0., 0., -1.));
|
||||
///
|
||||
/// // The hit should offset the point.
|
||||
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
|
||||
/// let mut shape = Shape::sphere();
|
||||
/// shape .set_transform(Matrix4x4::translation(0.,0.,1.));
|
||||
/// let i = Intersection::new(5., &shape);
|
||||
/// let comps = prepare_computations(&i, &r);
|
||||
/// assert!(comps.over_point.z< -EPSILON/2.);
|
||||
/// assert!(comps.point.z>comps.over_point.z);
|
||||
/// ```
|
||||
pub fn prepare_computations<'i>(i: &'i Intersection, r: &Ray) -> PrecomputedData<'i> {
|
||||
let point = r.position(i.t);
|
||||
let normalv = i.object.normal_at(point);
|
||||
let eyev = -r.direction;
|
||||
let (inside, normalv) = if dot(normalv, eyev) < 0. {
|
||||
(true, -normalv)
|
||||
} else {
|
||||
(false, normalv)
|
||||
};
|
||||
let reflectv = reflect(r.direction, normalv);
|
||||
|
||||
let mut n1 = -1.;
|
||||
let mut n2 = -1.;
|
||||
let mut containers: Vec<&Shape> = Vec::new();
|
||||
for i in xs.0.iter() {
|
||||
if hit == i {
|
||||
if containers.is_empty() {
|
||||
n1 = 1.;
|
||||
} else {
|
||||
n1 = containers.last().unwrap().material.refractive_index;
|
||||
}
|
||||
}
|
||||
|
||||
match containers.iter().position(|o| o == &i.object) {
|
||||
Some(idx) => {
|
||||
containers.remove(idx);
|
||||
}
|
||||
None => containers.push(i.object),
|
||||
}
|
||||
|
||||
if hit == i {
|
||||
if containers.is_empty() {
|
||||
n2 = 1.;
|
||||
} else {
|
||||
n2 = containers.last().unwrap().material.refractive_index;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let over_point = point + normalv * EPSILON;
|
||||
let under_point = point - normalv * EPSILON;
|
||||
PrecomputedData {
|
||||
t: hit.t,
|
||||
object: hit.object,
|
||||
t: i.t,
|
||||
object: i.object,
|
||||
point,
|
||||
over_point,
|
||||
under_point,
|
||||
normalv,
|
||||
reflectv,
|
||||
inside,
|
||||
eyev,
|
||||
n1,
|
||||
n2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute Schlick approximation to Fresnel's equations.
|
||||
pub fn schlick(comps: &PrecomputedData) -> Float {
|
||||
// Find the cosine of the angle between the eye and normal vectors.
|
||||
let mut cos = dot(comps.eyev, comps.normalv);
|
||||
// Total internal reflection can only occur if n1 > n2.
|
||||
if comps.n1 > comps.n2 {
|
||||
let n = comps.n1 / comps.n2;
|
||||
let sin2_t = n * n * (1. - cos * cos);
|
||||
if sin2_t > 1. {
|
||||
return 1.;
|
||||
}
|
||||
// Compute cosine of theta_t using trig identity.
|
||||
let cos_t = (1. - sin2_t).sqrt();
|
||||
// When n1 > n2 use cos(theta_t) instead.
|
||||
cos = cos_t;
|
||||
}
|
||||
|
||||
let r0 = (comps.n1 - comps.n2) / (comps.n1 + comps.n2);
|
||||
let r0 = r0 * r0;
|
||||
r0 + (1. - r0) * (1. - cos) * (1. - cos) * (1. - cos) * (1. - cos) * (1. - cos)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
intersections::{prepare_computations, schlick, Intersection, Intersections},
|
||||
materials::MaterialBuilder,
|
||||
matrices::{scaling, translation},
|
||||
rays::Ray,
|
||||
shapes::{glass_sphere, intersect, Shape},
|
||||
tuples::{point, vector},
|
||||
Float, EPSILON,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn intersection() {
|
||||
// An intersection ecapsulates t and object.
|
||||
let s = Shape::sphere();
|
||||
let i = Intersection::new(3.5, &s);
|
||||
assert_eq!(i.t, 3.5);
|
||||
assert_eq!(i.object, &s);
|
||||
}
|
||||
#[test]
|
||||
fn intersections() {
|
||||
let s = Shape::sphere();
|
||||
let i1 = Intersection::new(1., &s);
|
||||
let i2 = Intersection::new(2., &s);
|
||||
let xs = Intersections::new(vec![i1, i2]);
|
||||
assert_eq!(xs.len(), 2);
|
||||
assert_eq!(xs[0].t, 1.);
|
||||
assert_eq!(xs[1].t, 2.);
|
||||
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let xs = intersect(&s, &r);
|
||||
assert_eq!(xs.len(), 2);
|
||||
assert_eq!(xs[0].object, &s);
|
||||
assert_eq!(xs[1].object, &s);
|
||||
}
|
||||
|
||||
mod hit {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn when_all_intersections_have_positive_t() {
|
||||
let s = Shape::sphere();
|
||||
let i1 = Intersection::new(1., &s);
|
||||
let i2 = Intersection::new(2., &s);
|
||||
let xs = Intersections::new(vec![i2, i1.clone()]);
|
||||
let i = xs.hit();
|
||||
assert_eq!(i, Some(&i1));
|
||||
}
|
||||
#[test]
|
||||
fn when_some_intersections_have_negative_t() {
|
||||
let s = Shape::sphere();
|
||||
let i1 = Intersection::new(-1., &s);
|
||||
let i2 = Intersection::new(1., &s);
|
||||
let xs = Intersections::new(vec![i2.clone(), i1]);
|
||||
let i = xs.hit();
|
||||
assert_eq!(i, Some(&i2));
|
||||
}
|
||||
#[test]
|
||||
fn when_all_intersections_have_negative_t() {
|
||||
let s = Shape::sphere();
|
||||
let i1 = Intersection::new(-2., &s);
|
||||
let i2 = Intersection::new(-1., &s);
|
||||
let xs = Intersections::new(vec![i2, i1]);
|
||||
let i = xs.hit();
|
||||
assert_eq!(i, None);
|
||||
}
|
||||
#[test]
|
||||
fn always_the_lowest_nonnegative_intersection() {
|
||||
let s = Shape::sphere();
|
||||
let i1 = Intersection::new(5., &s);
|
||||
let i2 = Intersection::new(7., &s);
|
||||
let i3 = Intersection::new(-3., &s);
|
||||
let i4 = Intersection::new(2., &s);
|
||||
let xs = Intersections::new(vec![i1, i2, i3, i4.clone()]);
|
||||
let i = xs.hit();
|
||||
assert_eq!(i, Some(&i4));
|
||||
}
|
||||
}
|
||||
|
||||
mod prepare_computations {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn precomputing_the_state_of_intersection() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let shape = Shape::sphere();
|
||||
let xs = Intersections::from(Intersection::new(4., &shape));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
assert_eq!(comps.t, xs[0].t);
|
||||
assert_eq!(comps.object, xs[0].object);
|
||||
assert_eq!(comps.point, point(0., 0., -1.));
|
||||
assert_eq!(comps.eyev, vector(0., 0., -1.));
|
||||
assert_eq!(comps.normalv, vector(0., 0., -1.));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_when_intersection_occurs_outside() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// The hit, when an intersection occurs on the outside.
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let shape = Shape::sphere();
|
||||
let xs = Intersections::from(Intersection::new(4., &shape));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
assert_eq!(comps.inside, false);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_when_intersection_occurs_inside() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// The hit, when an intersection occurs on the inside.
|
||||
let r = Ray::new(point(0., 0., 0.), vector(0., 0., 1.));
|
||||
let shape = Shape::sphere();
|
||||
let xs = Intersections::from(Intersection::new(1., &shape));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
assert_eq!(comps.point, point(0., 0., 1.));
|
||||
assert_eq!(comps.eyev, vector(0., 0., -1.));
|
||||
assert_eq!(comps.inside, true);
|
||||
// Normal would have been (0, 0, 1), but is inverted when inside.
|
||||
assert_eq!(comps.normalv, vector(0., 0., -1.));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_should_offset_the_point() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// The hit should offset the point.
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let mut shape = Shape::sphere();
|
||||
shape.set_transform(translation(0., 0., 1.));
|
||||
let xs = Intersections::from(Intersection::new(5., &shape));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
assert!(comps.over_point.z < -EPSILON / 2.);
|
||||
assert!(comps.point.z > comps.over_point.z);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precomputing_the_reflection_vector() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Precomputing the reflection vector.
|
||||
let shape = Shape::plane();
|
||||
let r = Ray::new(
|
||||
point(0., 1., -1.),
|
||||
vector(0., -(2 as Float).sqrt() / 2., (2 as Float).sqrt() / 2.),
|
||||
);
|
||||
let xs = Intersections::from(Intersection::new((2 as Float).sqrt(), &shape));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
assert_eq!(
|
||||
comps.reflectv,
|
||||
vector(0., (2 as Float).sqrt() / 2., (2 as Float).sqrt() / 2.)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finding_n1_and_n2() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Finding n1 and n2 at various intersections.
|
||||
let a = glass_sphere()
|
||||
.transform(scaling(2., 2., 2.))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.transparency(1.)
|
||||
.refractive_index(1.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
let b = glass_sphere()
|
||||
.transform(translation(0., 0., -0.25))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.transparency(1.)
|
||||
.refractive_index(2.)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
let c = glass_sphere()
|
||||
.transform(translation(0., 0., 0.25))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.transparency(1.)
|
||||
.refractive_index(2.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
let r = Ray::new(point(0., 0., -4.), vector(0., 0., 1.));
|
||||
let xs = Intersections::new(vec![
|
||||
Intersection::new(2., &a),
|
||||
Intersection::new(2.75, &b),
|
||||
Intersection::new(3.25, &c),
|
||||
Intersection::new(4.75, &b),
|
||||
Intersection::new(5.25, &c),
|
||||
Intersection::new(6., &a),
|
||||
]);
|
||||
for (index, n1, n2) in &[
|
||||
(0, 1.0, 1.5),
|
||||
(1, 1.5, 2.0),
|
||||
(2, 2.0, 2.5),
|
||||
(3, 2.5, 2.5),
|
||||
(4, 2.5, 1.5),
|
||||
(5, 1.5, 1.0),
|
||||
] {
|
||||
let comps = prepare_computations(&xs[*index], &r, &xs);
|
||||
assert_eq!(comps.n1, *n1);
|
||||
assert_eq!(comps.n2, *n2);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_point_offset_below_surface() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// The under point is offset below the surface.
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let shape = glass_sphere().transform(translation(0., 0., 1.)).build()?;
|
||||
let xs = Intersections::from(Intersection::new(5., &shape));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
assert!(comps.under_point.z > EPSILON / 2.);
|
||||
assert!(comps.point.z < comps.under_point.z);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
mod schlick {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn under_total_reflection() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let shape = glass_sphere().build()?;
|
||||
let r = Ray::new(point(0., 0., (2 as Float).sqrt() / 2.), vector(0., 1., 0.));
|
||||
let xs = Intersections::new(vec![
|
||||
Intersection::new(-(2 as Float).sqrt() / 2., &shape),
|
||||
Intersection::new((2 as Float).sqrt() / 2., &shape),
|
||||
]);
|
||||
let comps = prepare_computations(&xs[1], &r, &xs);
|
||||
let reflectance = schlick(&comps);
|
||||
assert_eq!(reflectance, 1.);
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn perpendicular_viewing_angle() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let shape = glass_sphere().build()?;
|
||||
let r = Ray::new(point(0., 0., 0.), vector(0., 1., 0.));
|
||||
let xs = Intersections::new(vec![
|
||||
Intersection::new(-1., &shape),
|
||||
Intersection::new(1., &shape),
|
||||
]);
|
||||
let comps = prepare_computations(&xs[1], &r, &xs);
|
||||
let reflectance = schlick(&comps);
|
||||
assert!((reflectance - 0.04).abs() < EPSILON);
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn small_angle_n2_greater_n1() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let shape = glass_sphere().build()?;
|
||||
let r = Ray::new(point(0., 0.99, -2.), vector(0., 0., 1.));
|
||||
let xs = Intersections::new(vec![Intersection::new(1.8589, &shape)]);
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let reflectance = schlick(&comps);
|
||||
assert!((reflectance - 0.48873).abs() < EPSILON);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ pub mod intersections;
|
||||
pub mod lights;
|
||||
pub mod materials;
|
||||
pub mod matrices;
|
||||
pub mod patterns;
|
||||
pub mod rays;
|
||||
pub mod shapes;
|
||||
pub mod transformations;
|
||||
@@ -38,18 +37,3 @@ pub mod float {
|
||||
}
|
||||
|
||||
pub use float::Float;
|
||||
|
||||
pub mod prelude {
|
||||
pub use crate::{
|
||||
camera::{Camera, CameraBuilder},
|
||||
lights::{PointLight, PointLightBuilder},
|
||||
materials::{Material, MaterialBuilder},
|
||||
matrices::{identity, rotation_x, rotation_y, rotation_z, scaling, shearing, translation},
|
||||
patterns::{checkers_pattern, gradient_pattern, ring_pattern, stripe_pattern},
|
||||
shapes::{cube, plane, sphere, test_shape},
|
||||
transformations::view_transform,
|
||||
tuples::{point, vector, Color},
|
||||
world::{World, WorldBuilder},
|
||||
Float,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,39 +1,33 @@
|
||||
use derive_builder::Builder;
|
||||
|
||||
use crate::tuples::{Color, Tuple};
|
||||
|
||||
#[derive(Builder, Clone, Debug, Default, PartialEq)]
|
||||
#[builder(default)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PointLight {
|
||||
pub position: Tuple,
|
||||
#[builder(setter(into))]
|
||||
pub intensity: Color,
|
||||
}
|
||||
|
||||
impl PointLight {
|
||||
/// Creates a new `PositionLight` at the given `position` and with the given
|
||||
/// `intensity`.
|
||||
pub fn new<C>(position: Tuple, intensity: C) -> PointLight
|
||||
where
|
||||
C: Into<Color>,
|
||||
{
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// lights::PointLight,
|
||||
/// tuples::{Color, Tuple},
|
||||
/// WHITE,
|
||||
/// };
|
||||
///
|
||||
/// let intensity = WHITE;
|
||||
/// let position = Tuple::point(0., 0., 0.);
|
||||
/// let light = PointLight::new(position, intensity);
|
||||
/// assert_eq!(light.position, position);
|
||||
/// assert_eq!(light.intensity, intensity);
|
||||
/// ```
|
||||
pub fn new(position: Tuple, intensity: Color) -> PointLight {
|
||||
PointLight {
|
||||
position,
|
||||
intensity: intensity.into(),
|
||||
intensity,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{lights::PointLight, tuples::point, WHITE};
|
||||
|
||||
#[test]
|
||||
fn new() {
|
||||
let intensity = WHITE;
|
||||
let position = point(0., 0., 0.);
|
||||
let light = PointLight::new(position, intensity);
|
||||
assert_eq!(light.position, position);
|
||||
assert_eq!(light.intensity, intensity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,47 +1,108 @@
|
||||
use derive_builder::Builder;
|
||||
|
||||
use crate::{
|
||||
lights::PointLight,
|
||||
patterns::Pattern,
|
||||
shapes::Shape,
|
||||
tuples::{dot, reflect, Color, Tuple},
|
||||
tuples::Color,
|
||||
tuples::{dot, reflect, Tuple},
|
||||
Float, BLACK, WHITE,
|
||||
};
|
||||
|
||||
#[derive(Builder, Debug, PartialEq, Clone)]
|
||||
#[builder(default)]
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub struct Material {
|
||||
#[builder(setter(into))]
|
||||
pub color: Pattern,
|
||||
pub color: Color,
|
||||
pub ambient: Float,
|
||||
pub diffuse: Float,
|
||||
pub specular: Float,
|
||||
pub shininess: Float,
|
||||
pub reflective: Float,
|
||||
pub transparency: Float,
|
||||
pub refractive_index: Float,
|
||||
}
|
||||
|
||||
impl Default for Material {
|
||||
/// Creates the default material.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{materials::Material, tuples::Color, WHITE};
|
||||
///
|
||||
/// let m = Material::default();
|
||||
/// assert_eq!(
|
||||
/// m,
|
||||
/// Material {
|
||||
/// color: WHITE,
|
||||
/// ambient: 0.1,
|
||||
/// diffuse: 0.9,
|
||||
/// specular: 0.9,
|
||||
/// shininess: 200.,
|
||||
/// }
|
||||
/// );
|
||||
/// ```
|
||||
fn default() -> Material {
|
||||
Material {
|
||||
color: WHITE.into(),
|
||||
color: WHITE,
|
||||
ambient: 0.1,
|
||||
diffuse: 0.9,
|
||||
specular: 0.9,
|
||||
shininess: 200.,
|
||||
reflective: 0.0,
|
||||
transparency: 0.0,
|
||||
refractive_index: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute lighting contributions using the Phong reflection model.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// lights::PointLight,
|
||||
/// materials::{lighting, Material},
|
||||
/// tuples::{Color, Tuple},
|
||||
/// Float, WHITE,
|
||||
/// };
|
||||
///
|
||||
/// let in_shadow = false;
|
||||
/// let m = Material::default();
|
||||
/// let position = Tuple::point(0., 0., 0.);
|
||||
///
|
||||
/// // Lighting with the eye between the light and the surface.
|
||||
/// let eyev = Tuple::vector(0., 0., -1.);
|
||||
/// let normalv = Tuple::vector(0., 0., -1.);
|
||||
/// let light = PointLight::new(Tuple::point(0., 0., -10.), WHITE);
|
||||
/// let result = lighting(&m, &light, position, eyev, normalv, in_shadow);
|
||||
/// assert_eq!(result, Color::new(1.9, 1.9, 1.9));
|
||||
///
|
||||
/// // Lighting with the eye between the light and the surface, eye offset 45°.
|
||||
/// let eyev = Tuple::vector(0., (2. as Float).sqrt() / 2., -(2. as Float).sqrt() / 2.);
|
||||
/// let normalv = Tuple::vector(0., 0., -1.);
|
||||
/// let light = PointLight::new(Tuple::point(0., 0., -10.), WHITE);
|
||||
/// let result = lighting(&m, &light, position, eyev, normalv, in_shadow);
|
||||
/// assert_eq!(result, WHITE);
|
||||
///
|
||||
/// // Lighting with the eye opposite surface, light offset 45°.
|
||||
/// let eyev = Tuple::vector(0., 0., -1.);
|
||||
/// let normalv = Tuple::vector(0., 0., -1.);
|
||||
/// let light = PointLight::new(Tuple::point(0., 10., -10.), WHITE);
|
||||
/// let result = lighting(&m, &light, position, eyev, normalv, in_shadow);
|
||||
/// assert_eq!(result, Color::new(0.7364, 0.7364, 0.7364));
|
||||
///
|
||||
/// // Lighting with the eye in the path of the reflection vector.
|
||||
/// let eyev = Tuple::vector(0., -(2.0 as Float).sqrt() / 2., -(2.0 as Float).sqrt() / 2.);
|
||||
/// let normalv = Tuple::vector(0., 0., -1.);
|
||||
/// let light = PointLight::new(Tuple::point(0., 10., -10.), WHITE);
|
||||
/// let result = lighting(&m, &light, position, eyev, normalv, in_shadow);
|
||||
/// assert_eq!(result, Color::new(1.63639, 1.63639, 1.63639));
|
||||
///
|
||||
/// // Lighting with the light behind the surface.
|
||||
/// let eyev = Tuple::vector(0., 0., -1.);
|
||||
/// let normalv = Tuple::vector(0., 0., -1.);
|
||||
/// let light = PointLight::new(Tuple::point(0., 0., 10.), WHITE);
|
||||
/// let result = lighting(&m, &light, position, eyev, normalv, in_shadow);
|
||||
/// assert_eq!(result, Color::new(0.1, 0.1, 0.1));
|
||||
///
|
||||
/// // Lighting with the surface in shadow.
|
||||
/// let in_shadow = true;
|
||||
/// let eyev = Tuple::vector(0., 0., -1.);
|
||||
/// let normalv = Tuple::vector(0., 0., -1.);
|
||||
/// let light = PointLight::new(Tuple::point(0., 0., -10.), WHITE);
|
||||
/// let result = lighting(&m, &light, position, eyev, normalv, in_shadow);
|
||||
/// assert_eq!(result, Color::new(0.1, 0.1, 0.1));
|
||||
/// ```
|
||||
pub fn lighting(
|
||||
material: &Material,
|
||||
object: &Shape,
|
||||
light: &PointLight,
|
||||
point: Tuple,
|
||||
eyev: Tuple,
|
||||
@@ -49,8 +110,7 @@ pub fn lighting(
|
||||
in_shadow: bool,
|
||||
) -> Color {
|
||||
// Combine the surface color with the light's color.
|
||||
let color = material.color.pattern_at_object(object, point);
|
||||
let effective_color = color * light.intensity;
|
||||
let effective_color = material.color * light.intensity;
|
||||
// Find the direciton of the light source.
|
||||
let lightv = (light.position - point).normalize();
|
||||
// Compute the ambient distribution.
|
||||
@@ -84,153 +144,3 @@ pub fn lighting(
|
||||
ambient + diffuse + specular
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{materials::Material, WHITE};
|
||||
|
||||
#[test]
|
||||
fn default() {
|
||||
let m = Material::default();
|
||||
assert_eq!(
|
||||
m,
|
||||
Material {
|
||||
color: WHITE.into(),
|
||||
ambient: 0.1,
|
||||
diffuse: 0.9,
|
||||
specular: 0.9,
|
||||
shininess: 200.,
|
||||
reflective: 0.0,
|
||||
transparency: 0.0,
|
||||
refractive_index: 1.0,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
mod lighting {
|
||||
use crate::{
|
||||
lights::PointLight,
|
||||
materials::{lighting, Material},
|
||||
patterns::{Pattern, BLACK_PAT, WHITE_PAT},
|
||||
shapes::Shape,
|
||||
tuples::{point, vector, Color},
|
||||
Float, BLACK, WHITE,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn eye_between_light_and_surface() {
|
||||
let in_shadow = false;
|
||||
let m = Material::default();
|
||||
let position = point(0., 0., 0.);
|
||||
let object = Shape::sphere();
|
||||
|
||||
// Lighting with the eye between the light and the surface.
|
||||
let eyev = vector(0., 0., -1.);
|
||||
let normalv = vector(0., 0., -1.);
|
||||
let light = PointLight::new(point(0., 0., -10.), WHITE);
|
||||
let result = lighting(&m, &object, &light, position, eyev, normalv, in_shadow);
|
||||
assert_eq!(result, Color::new(1.9, 1.9, 1.9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eye_between_light_and_surface_offset_45() {
|
||||
// Lighting with the eye between the light and the surface, eye offset 45°.
|
||||
let in_shadow = false;
|
||||
let m = Material::default();
|
||||
let position = point(0., 0., 0.);
|
||||
let object = Shape::sphere();
|
||||
let eyev = vector(0., (2. as Float).sqrt() / 2., -(2. as Float).sqrt() / 2.);
|
||||
let normalv = vector(0., 0., -1.);
|
||||
let light = PointLight::new(point(0., 0., -10.), WHITE);
|
||||
let result = lighting(&m, &object, &light, position, eyev, normalv, in_shadow);
|
||||
assert_eq!(result, WHITE);
|
||||
}
|
||||
#[test]
|
||||
fn eye_opposite_surface_light_offset_45() {
|
||||
// Lighting with the eye opposite surface, light offset 45°.
|
||||
let in_shadow = false;
|
||||
let m = Material::default();
|
||||
let position = point(0., 0., 0.);
|
||||
let object = Shape::sphere();
|
||||
let eyev = vector(0., 0., -1.);
|
||||
let normalv = vector(0., 0., -1.);
|
||||
let light = PointLight::new(point(0., 10., -10.), WHITE);
|
||||
let result = lighting(&m, &object, &light, position, eyev, normalv, in_shadow);
|
||||
assert_eq!(result, Color::new(0.7364, 0.7364, 0.7364));
|
||||
}
|
||||
#[test]
|
||||
fn eye_in_path_of_reflection_vector() {
|
||||
// Lighting with the eye in the path of the reflection vector.
|
||||
let in_shadow = false;
|
||||
let m = Material::default();
|
||||
let position = point(0., 0., 0.);
|
||||
let object = Shape::sphere();
|
||||
let eyev = vector(0., -(2.0 as Float).sqrt() / 2., -(2.0 as Float).sqrt() / 2.);
|
||||
let normalv = vector(0., 0., -1.);
|
||||
let light = PointLight::new(point(0., 10., -10.), WHITE);
|
||||
let result = lighting(&m, &object, &light, position, eyev, normalv, in_shadow);
|
||||
assert_eq!(result, Color::new(1.63639, 1.63639, 1.63639));
|
||||
}
|
||||
#[test]
|
||||
fn light_behind_surface() {
|
||||
// Lighting with the light behind the surface.
|
||||
let in_shadow = false;
|
||||
let m = Material::default();
|
||||
let position = point(0., 0., 0.);
|
||||
let object = Shape::sphere();
|
||||
let eyev = vector(0., 0., -1.);
|
||||
let normalv = vector(0., 0., -1.);
|
||||
let light = PointLight::new(point(0., 0., 10.), WHITE);
|
||||
let result = lighting(&m, &object, &light, position, eyev, normalv, in_shadow);
|
||||
assert_eq!(result, Color::new(0.1, 0.1, 0.1));
|
||||
}
|
||||
#[test]
|
||||
fn surface_in_shadow() {
|
||||
// Lighting with the surface in shadow.
|
||||
let m = Material::default();
|
||||
let position = point(0., 0., 0.);
|
||||
let object = Shape::sphere();
|
||||
let in_shadow = true;
|
||||
let eyev = vector(0., 0., -1.);
|
||||
let normalv = vector(0., 0., -1.);
|
||||
let light = PointLight::new(point(0., 0., -10.), WHITE);
|
||||
let result = lighting(&m, &object, &light, position, eyev, normalv, in_shadow);
|
||||
assert_eq!(result, Color::new(0.1, 0.1, 0.1));
|
||||
}
|
||||
#[test]
|
||||
fn pattern_applied() {
|
||||
// Lighting with a pattern applied.
|
||||
let object = Shape::sphere();
|
||||
let m = Material {
|
||||
color: Pattern::stripe(WHITE_PAT, BLACK_PAT),
|
||||
ambient: 1.,
|
||||
diffuse: 0.,
|
||||
specular: 0.,
|
||||
..Material::default()
|
||||
};
|
||||
let eyev = vector(0., 0., -1.);
|
||||
let normalv = vector(0., 0., -1.);
|
||||
let light = PointLight::new(point(0., 0., -10.), WHITE);
|
||||
let c1 = lighting(
|
||||
&m,
|
||||
&object,
|
||||
&light,
|
||||
point(0.9, 0., 0.),
|
||||
eyev,
|
||||
normalv,
|
||||
false,
|
||||
);
|
||||
let c2 = lighting(
|
||||
&m,
|
||||
&object,
|
||||
&light,
|
||||
point(1.1, 0., 0.),
|
||||
eyev,
|
||||
normalv,
|
||||
false,
|
||||
);
|
||||
assert_eq!(c1, WHITE);
|
||||
assert_eq!(c2, BLACK);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +1,8 @@
|
||||
use std::{
|
||||
fmt,
|
||||
ops::{Index, IndexMut, Mul, Sub},
|
||||
};
|
||||
use std::fmt;
|
||||
use std::ops::{Index, IndexMut, Mul, Sub};
|
||||
|
||||
use crate::{tuples::Tuple, Float, EPSILON};
|
||||
|
||||
/// Short hand for creating a Matrix4x4 set to the identity matrix.
|
||||
pub fn identity() -> Matrix4x4 {
|
||||
Matrix4x4::identity()
|
||||
}
|
||||
/// Short hand for creating a Matrix4x4 for rotating around the X-axis.
|
||||
pub fn rotation_x(radians: Float) -> Matrix4x4 {
|
||||
Matrix4x4::rotation_x(radians)
|
||||
}
|
||||
/// Short hand for creating a Matrix4x4 for rotating around the Y-axis.
|
||||
pub fn rotation_y(radians: Float) -> Matrix4x4 {
|
||||
Matrix4x4::rotation_y(radians)
|
||||
}
|
||||
/// Short hand for creating a Matrix4x4 for rotating around the Z-axis.
|
||||
pub fn rotation_z(radians: Float) -> Matrix4x4 {
|
||||
Matrix4x4::rotation_z(radians)
|
||||
}
|
||||
/// Short hand for creating a Matrix4x4 that scales in the given x,y,z axis.
|
||||
pub fn scaling(x: Float, y: Float, z: Float) -> Matrix4x4 {
|
||||
Matrix4x4::scaling(x, y, z)
|
||||
}
|
||||
/// Short hand for creating a Matrix4x4 that shears across the given axis pairs.
|
||||
pub fn shearing(xy: Float, xz: Float, yx: Float, yz: Float, zx: Float, zy: Float) -> Matrix4x4 {
|
||||
Matrix4x4::shearing(xy, xz, yx, yz, zx, zy)
|
||||
}
|
||||
/// Short hand for creating a Matrix4x4 that translations along the given x,y,z axis.
|
||||
pub fn translation(x: Float, y: Float, z: Float) -> Matrix4x4 {
|
||||
Matrix4x4::translation(x, y, z)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Matrix2x2 {
|
||||
m: [[Float; 2]; 2],
|
||||
@@ -45,6 +14,16 @@ impl Matrix2x2 {
|
||||
}
|
||||
|
||||
/// Calculate the determinant of a 2x2.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix2x2;
|
||||
///
|
||||
/// let a = Matrix2x2::new([1., 5.], [-3., 2.]);
|
||||
///
|
||||
/// assert_eq!(a.determinant(), 17.);
|
||||
/// ```
|
||||
pub fn determinant(&self) -> Float {
|
||||
let m = self;
|
||||
m[(0, 0)] * m[(1, 1)] - m[(0, 1)] * m[(1, 0)]
|
||||
@@ -82,6 +61,16 @@ impl Matrix3x3 {
|
||||
Matrix3x3 { m: [r0, r1, r2] }
|
||||
}
|
||||
/// submatrix extracts a 2x2 matrix ignoring the 0-based `row` and `col` given.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::{Matrix2x2, Matrix3x3};
|
||||
///
|
||||
/// assert_eq!(
|
||||
/// Matrix3x3::new([1., 5., 0.], [-3., 2., 7.], [0., 6., -3.],).submatrix(0, 2),
|
||||
/// Matrix2x2::new([-3., 2.], [0., 6.])
|
||||
/// );
|
||||
/// ```
|
||||
pub fn submatrix(&self, row: usize, col: usize) -> Matrix2x2 {
|
||||
assert!(row < 3);
|
||||
assert!(col < 3);
|
||||
@@ -102,17 +91,49 @@ impl Matrix3x3 {
|
||||
}
|
||||
|
||||
/// Compute minor of a 3x3 matrix.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix3x3;
|
||||
///
|
||||
/// let a = Matrix3x3::new([3., 5., 0.], [2., -1., -7.], [6., -1., 5.]);
|
||||
/// let b = a.submatrix(1, 0);
|
||||
/// assert_eq!(b.determinant(), 25.0);
|
||||
/// assert_eq!(b.determinant(), a.minor(1, 0));
|
||||
/// ```
|
||||
pub fn minor(&self, row: usize, col: usize) -> Float {
|
||||
self.submatrix(row, col).determinant()
|
||||
}
|
||||
|
||||
/// Compute cofactor of a 3x3 matrix.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix3x3;
|
||||
///
|
||||
/// let a = Matrix3x3::new([3., 5., 0.], [2., -1., -7.], [6., -1., 5.]);
|
||||
/// assert_eq!(a.minor(0, 0), -12.);
|
||||
/// assert_eq!(a.cofactor(0, 0), -12.);
|
||||
/// assert_eq!(a.minor(1, 0), 25.);
|
||||
/// assert_eq!(a.cofactor(1, 0), -25.);
|
||||
/// ```
|
||||
pub fn cofactor(&self, row: usize, col: usize) -> Float {
|
||||
let negate = if (row + col) % 2 == 0 { 1. } else { -1. };
|
||||
self.submatrix(row, col).determinant() * negate
|
||||
}
|
||||
|
||||
/// Compute determinant of a 3x3 matrix.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix3x3;
|
||||
///
|
||||
/// let a = Matrix3x3::new([1., 2., 6.], [-5., 8., -4.], [2., 6., 4.]);
|
||||
/// assert_eq!(a.cofactor(0, 0), 56.);
|
||||
/// assert_eq!(a.cofactor(0, 1), 12.);
|
||||
/// assert_eq!(a.cofactor(0, 2), -46.);
|
||||
/// assert_eq!(a.determinant(), -196.);
|
||||
/// ```
|
||||
pub fn determinant(&self) -> Float {
|
||||
(0..3).map(|i| self.cofactor(0, i) * self[(0, i)]).sum()
|
||||
}
|
||||
@@ -142,6 +163,34 @@ impl PartialEq for Matrix3x3 {
|
||||
|
||||
/// Matrix4x4 represents a 4x4 matrix in row-major form. So, element `m[i][j]` corresponds to m<sub>i,j</sub>
|
||||
/// where `i` is the row number and `j` is the column number.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{float::consts::PI, matrices::Matrix4x4, tuples::Tuple};
|
||||
///
|
||||
/// // Individual transformations are applied in sequence.
|
||||
/// let p = Tuple::point(1., 0., 1.);
|
||||
/// let a = Matrix4x4::rotation_x(PI / 2.);
|
||||
/// let b = Matrix4x4::scaling(5., 5., 5.);
|
||||
/// let c = Matrix4x4::translation(10., 5., 7.);
|
||||
/// // Apply rotation first.
|
||||
/// let p2 = a * p;
|
||||
/// assert_eq!(p2, Tuple::point(1., -1., 0.));
|
||||
/// // Then apply scaling.
|
||||
/// let p3 = b * p2;
|
||||
/// assert_eq!(p3, Tuple::point(5., -5., 0.));
|
||||
/// // Then apply translation.
|
||||
/// let p4 = c * p3;
|
||||
/// assert_eq!(p4, Tuple::point(15., 0., 7.));
|
||||
///
|
||||
/// // Chained transformations must be applied in reverse order.
|
||||
/// let p = Tuple::point(1., 0., 1.);
|
||||
/// let a = Matrix4x4::rotation_x(PI / 2.);
|
||||
/// let b = Matrix4x4::scaling(5., 5., 5.);
|
||||
/// let c = Matrix4x4::translation(10., 5., 7.);
|
||||
/// let t = c * b * a;
|
||||
/// assert_eq!(t * p, Tuple::point(15., 0., 7.));
|
||||
/// ```
|
||||
#[derive(Copy, Clone, Default)]
|
||||
pub struct Matrix4x4 {
|
||||
m: [[Float; 4]; 4],
|
||||
@@ -162,7 +211,22 @@ impl From<[Float; 16]> for Matrix4x4 {
|
||||
|
||||
impl Matrix4x4 {
|
||||
/// Create a `Matrix4x4` containing the identity, all zeros with ones along the diagonal.
|
||||
pub const fn identity() -> Matrix4x4 {
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix4x4;
|
||||
///
|
||||
/// let a = Matrix4x4::new(
|
||||
/// [0., 1., 2., 3.],
|
||||
/// [1., 2., 4., 8.],
|
||||
/// [2., 4., 8., 16.],
|
||||
/// [4., 8., 16., 32.],
|
||||
/// );
|
||||
/// let i = Matrix4x4::identity();
|
||||
///
|
||||
/// assert_eq!(a * i, a);
|
||||
/// ```
|
||||
pub fn identity() -> Matrix4x4 {
|
||||
Matrix4x4::new(
|
||||
[1., 0., 0., 0.],
|
||||
[0., 1., 0., 0.],
|
||||
@@ -172,13 +236,29 @@ impl Matrix4x4 {
|
||||
}
|
||||
|
||||
/// Create a `Matrix4x4` with each of the given rows.
|
||||
pub const fn new(r0: [Float; 4], r1: [Float; 4], r2: [Float; 4], r3: [Float; 4]) -> Matrix4x4 {
|
||||
pub fn new(r0: [Float; 4], r1: [Float; 4], r2: [Float; 4], r3: [Float; 4]) -> Matrix4x4 {
|
||||
Matrix4x4 {
|
||||
m: [r0, r1, r2, r3],
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a 4x4 matrix representing a translation of x,y,z.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::{matrices::Matrix4x4, tuples::Tuple};
|
||||
///
|
||||
/// let transform = Matrix4x4::translation(5., -3., 2.);
|
||||
/// let p = Tuple::point(-3., 4., 5.);
|
||||
/// assert_eq!(transform * p, Tuple::point(2., 1., 7.));
|
||||
///
|
||||
/// let inv = transform.inverse();
|
||||
/// assert_eq!(inv * p, Tuple::point(-8., 7., 3.));
|
||||
///
|
||||
/// let v = Tuple::vector(-3., 4., 5.);
|
||||
/// assert_eq!(transform * v, v);
|
||||
/// ```
|
||||
pub fn translation(x: Float, y: Float, z: Float) -> Matrix4x4 {
|
||||
Matrix4x4::new(
|
||||
[1., 0., 0., x],
|
||||
@@ -189,6 +269,30 @@ impl Matrix4x4 {
|
||||
}
|
||||
|
||||
/// Creates a 4x4 matrix representing a scaling of x,y,z.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::{matrices::Matrix4x4, tuples::Tuple};
|
||||
///
|
||||
/// // A scaling matrix applied to a point.
|
||||
/// let transform = Matrix4x4::scaling(2., 3., 4.);
|
||||
/// let p = Tuple::point(-4., 6., 8.);
|
||||
/// assert_eq!(transform * p, Tuple::point(-8., 18., 32.));
|
||||
///
|
||||
/// // A scaling matrix applied to a vector.
|
||||
/// let v = Tuple::vector(-4., 6., 8.);
|
||||
/// assert_eq!(transform * v, Tuple::vector(-8., 18., 32.));
|
||||
///
|
||||
/// // Multiplying by the inverse of a scaling matrix.
|
||||
/// let inv = transform.inverse();
|
||||
/// assert_eq!(inv * v, Tuple::vector(-2., 2., 2.));
|
||||
///
|
||||
/// // Reflection is scaling by a negative value.
|
||||
/// let transform = Matrix4x4::scaling(-1., 1., 1.);
|
||||
/// let p = Tuple::point(2., 3., 4.);
|
||||
/// assert_eq!(transform * p, Tuple::point(-2., 3., 4.));
|
||||
/// ```
|
||||
pub fn scaling(x: Float, y: Float, z: Float) -> Matrix4x4 {
|
||||
Matrix4x4::new(
|
||||
[x, 0., 0., 0.],
|
||||
@@ -199,6 +303,23 @@ impl Matrix4x4 {
|
||||
}
|
||||
|
||||
/// Creates a 4x4 matrix representing a rotation around the x-axis.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::{float::consts::PI, matrices::Matrix4x4, tuples::Tuple, Float};
|
||||
///
|
||||
/// // A scaling matrix applied to a point.
|
||||
/// let p = Tuple::point(0., 1., 0.);
|
||||
/// let half_quarter = Matrix4x4::rotation_x(PI / 4.);
|
||||
/// let full_quarter = Matrix4x4::rotation_x(PI / 2.);
|
||||
///
|
||||
/// assert_eq!(
|
||||
/// half_quarter * p,
|
||||
/// Tuple::point(0., (2.0 as Float).sqrt() / 2., (2.0 as Float).sqrt() / 2.)
|
||||
/// );
|
||||
/// assert_eq!(full_quarter * p, Tuple::point(0., 0., 1.),);
|
||||
/// ```
|
||||
pub fn rotation_x(radians: Float) -> Matrix4x4 {
|
||||
let r = radians;
|
||||
Matrix4x4::new(
|
||||
@@ -210,6 +331,23 @@ impl Matrix4x4 {
|
||||
}
|
||||
|
||||
/// Creates a 4x4 matrix representing a rotation around the y-axis.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::{float::consts::PI, matrices::Matrix4x4, tuples::Tuple, Float};
|
||||
///
|
||||
/// // A scaling matrix applied to a point.
|
||||
/// let p = Tuple::point(0., 0., 1.);
|
||||
/// let half_quarter = Matrix4x4::rotation_y(PI / 4.);
|
||||
/// let full_quarter = Matrix4x4::rotation_y(PI / 2.);
|
||||
///
|
||||
/// assert_eq!(
|
||||
/// half_quarter * p,
|
||||
/// Tuple::point((2.0 as Float).sqrt() / 2., 0., (2.0 as Float).sqrt() / 2.)
|
||||
/// );
|
||||
/// assert_eq!(full_quarter * p, Tuple::point(1., 0., 0.,),);
|
||||
/// ```
|
||||
pub fn rotation_y(radians: Float) -> Matrix4x4 {
|
||||
let r = radians;
|
||||
Matrix4x4::new(
|
||||
@@ -221,6 +359,23 @@ impl Matrix4x4 {
|
||||
}
|
||||
|
||||
/// Creates a 4x4 matrix representing a rotation around the z-axis.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::{float::consts::PI, matrices::Matrix4x4, tuples::Tuple, Float};
|
||||
///
|
||||
/// // A scaling matrix applied to a point.
|
||||
/// let p = Tuple::point(0., 1., 0.);
|
||||
/// let half_quarter = Matrix4x4::rotation_z(PI / 4.);
|
||||
/// let full_quarter = Matrix4x4::rotation_z(PI / 2.);
|
||||
///
|
||||
/// assert_eq!(
|
||||
/// half_quarter * p,
|
||||
/// Tuple::point(-(2.0 as Float).sqrt() / 2., (2.0 as Float).sqrt() / 2., 0.)
|
||||
/// );
|
||||
/// assert_eq!(full_quarter * p, Tuple::point(-1., 0., 0.,),);
|
||||
/// ```
|
||||
pub fn rotation_z(radians: Float) -> Matrix4x4 {
|
||||
let r = radians;
|
||||
Matrix4x4::new(
|
||||
@@ -232,6 +387,26 @@ impl Matrix4x4 {
|
||||
}
|
||||
|
||||
/// Transpose self, returning a new matrix that has been reflected across the diagonal.
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix4x4;
|
||||
///
|
||||
/// let m = Matrix4x4::new(
|
||||
/// [2., 0., 0., 0.],
|
||||
/// [3., 1., 0., 0.],
|
||||
/// [4., 0., 1., 0.],
|
||||
/// [5., 6., 7., 1.],
|
||||
/// );
|
||||
/// let m_t = Matrix4x4::new(
|
||||
/// [2., 3., 4., 5.],
|
||||
/// [0., 1., 0., 6.],
|
||||
/// [0., 0., 1., 7.],
|
||||
/// [0., 0., 0., 1.],
|
||||
/// );
|
||||
/// assert_eq!(m.transpose(), m_t);
|
||||
///
|
||||
/// assert_eq!(Matrix4x4::identity(), Matrix4x4::identity().transpose());
|
||||
pub fn transpose(&self) -> Matrix4x4 {
|
||||
let m = self.m;
|
||||
Matrix4x4 {
|
||||
@@ -245,6 +420,40 @@ impl Matrix4x4 {
|
||||
}
|
||||
/// Create a transform matrix that will shear (skew) points.
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::{matrices::Matrix4x4, tuples::Tuple};
|
||||
///
|
||||
/// // A shearing transform moves x in proportion to y.
|
||||
/// let transform = Matrix4x4::shearing(1.,0.,0.,0.,0.,0.);
|
||||
/// let p = Tuple::point(2.,3.,4.);
|
||||
/// assert_eq!(transform * p, Tuple::point(5.,3.,4.));
|
||||
///
|
||||
/// // A shearing transform moves x in proportion to z.
|
||||
/// let transform = Matrix4x4::shearing(0.,1.,0.,0.,0.,0.);
|
||||
/// let p = Tuple::point(2.,3.,4.);
|
||||
/// assert_eq!(transform * p, Tuple::point(6.,3.,4.));
|
||||
///
|
||||
/// // A shearing transform moves y in proportion to x.
|
||||
/// let transform = Matrix4x4::shearing(0.,0.,1.,0.,0.,0.);
|
||||
/// let p = Tuple::point(2.,3.,4.);
|
||||
/// assert_eq!(transform * p, Tuple::point(2.,5.,4.));
|
||||
///
|
||||
/// // A shearing transform moves y in proportion to z.
|
||||
/// let transform = Matrix4x4::shearing(0.,0.,0.,1.,0.,0.);
|
||||
/// let p = Tuple::point(2.,3.,4.);
|
||||
/// assert_eq!(transform * p, Tuple::point(2.,7.,4.));
|
||||
///
|
||||
/// // A shearing transform moves z in proportion to x.
|
||||
/// let transform = Matrix4x4::shearing(0.,0.,0.,0.,1.,0.);
|
||||
/// let p = Tuple::point(2.,3.,4.);
|
||||
/// assert_eq!(transform * p, Tuple::point(2.,3.,6.));
|
||||
///
|
||||
/// // A shearing transform moves z in proportion to y.
|
||||
/// let transform = Matrix4x4::shearing(0.,0.,0.,0.,0.,1.);
|
||||
/// let p = Tuple::point(2.,3.,4.);
|
||||
/// assert_eq!(transform * p, Tuple::point(2.,3.,7.));
|
||||
|
||||
pub fn shearing(xy: Float, xz: Float, yx: Float, yz: Float, zx: Float, zy: Float) -> Matrix4x4 {
|
||||
Matrix4x4::new(
|
||||
[1., xy, xz, 0.],
|
||||
@@ -257,6 +466,24 @@ impl Matrix4x4 {
|
||||
/// Returns a new matrix that is the inverse of self. If self is A, inverse returns A<sup>-1</sup>, where
|
||||
/// AA<sup>-1</sup> = I.
|
||||
/// This implementation uses a numerically stable Gauss–Jordan elimination routine to compute the inverse.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix4x4;
|
||||
///
|
||||
/// let i = Matrix4x4::identity();
|
||||
/// assert_eq!(i.inverse_rtiow() * i, i);
|
||||
///
|
||||
/// let m = Matrix4x4::new(
|
||||
/// [2., 0., 0., 0.],
|
||||
/// [0., 3., 0., 0.],
|
||||
/// [0., 0., 4., 0.],
|
||||
/// [0., 0., 0., 1.],
|
||||
/// );
|
||||
/// assert_eq!(m.inverse_rtiow() * m, i);
|
||||
/// assert_eq!(m * m.inverse_rtiow(), i);
|
||||
/// ```
|
||||
pub fn inverse_rtiow(&self) -> Matrix4x4 {
|
||||
// TODO(wathiede): how come the C++ version doesn't need to deal with non-invertable
|
||||
// matrix.
|
||||
@@ -331,6 +558,22 @@ impl Matrix4x4 {
|
||||
Matrix4x4 { m: minv }
|
||||
}
|
||||
/// submatrix extracts a 3x3 matrix ignoring the 0-based `row` and `col` given.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::{Matrix3x3, Matrix4x4};
|
||||
///
|
||||
/// assert_eq!(
|
||||
/// Matrix4x4::new(
|
||||
/// [-6., 1., 1., 6.],
|
||||
/// [-8., 5., 8., 6.],
|
||||
/// [-1., 0., 8., 2.],
|
||||
/// [-7., 1., -1., 1.],
|
||||
/// )
|
||||
/// .submatrix(2, 1),
|
||||
/// Matrix3x3::new([-6., 1., 6.], [-8., 8., 6.], [-7., -1., 1.],)
|
||||
/// );
|
||||
/// ```
|
||||
pub fn submatrix(&self, row: usize, col: usize) -> Matrix3x3 {
|
||||
assert!(row < 4);
|
||||
assert!(col < 4);
|
||||
@@ -364,16 +607,133 @@ impl Matrix4x4 {
|
||||
self.submatrix(row, col).determinant() * negate
|
||||
}
|
||||
/// Compute determinant of a 4x4 matrix.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix4x4;
|
||||
///
|
||||
/// let a = Matrix4x4::new(
|
||||
/// [-2., -8., 3., 5.],
|
||||
/// [-3., 1., 7., 3.],
|
||||
/// [1., 2., -9., 6.],
|
||||
/// [-6., 7., 7., -9.],
|
||||
/// );
|
||||
/// assert_eq!(a.cofactor(0, 0), 690.);
|
||||
/// assert_eq!(a.cofactor(0, 1), 447.);
|
||||
/// assert_eq!(a.cofactor(0, 2), 210.);
|
||||
/// assert_eq!(a.cofactor(0, 3), 51.);
|
||||
/// assert_eq!(a.determinant(), -4071.);
|
||||
/// ```
|
||||
pub fn determinant(&self) -> Float {
|
||||
(0..4).map(|i| self.cofactor(0, i) * self[(0, i)]).sum()
|
||||
}
|
||||
|
||||
/// Compute invertibility of matrix (i.e. non-zero determinant.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix4x4;
|
||||
///
|
||||
/// let a = Matrix4x4::new(
|
||||
/// [6., 4., 4., 4.],
|
||||
/// [5., 5., 7., 6.],
|
||||
/// [4., -9., 3., -7.],
|
||||
/// [9., 1., 7., -6.],
|
||||
/// );
|
||||
/// assert_eq!(a.determinant(), -2120.);
|
||||
/// assert_eq!(a.invertable(), true);
|
||||
///
|
||||
/// let a = Matrix4x4::new(
|
||||
/// [-4., 2., -2., -3.],
|
||||
/// [9., 6., 2., 6.],
|
||||
/// [0., -5., 1., -5.],
|
||||
/// [0., 0., 0., 0.],
|
||||
/// );
|
||||
/// assert_eq!(a.determinant(), 0.);
|
||||
/// assert_eq!(a.invertable(), false);
|
||||
/// ```
|
||||
pub fn invertable(&self) -> bool {
|
||||
self.determinant() != 0.
|
||||
}
|
||||
|
||||
/// Compute the inverse of a 4x4 matrix.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix4x4;
|
||||
///
|
||||
/// let a = Matrix4x4::new(
|
||||
/// [-5., 2., 6., -8.],
|
||||
/// [1., -5., 1., 8.],
|
||||
/// [7., 7., -6., -7.],
|
||||
/// [1., -3., 7., 4.],
|
||||
/// );
|
||||
/// let b = a.inverse();
|
||||
///
|
||||
/// assert_eq!(a.determinant(), 532.);
|
||||
/// assert_eq!(a.cofactor(2, 3), -160.);
|
||||
/// assert_eq!(b[(3, 2)], -160. / 532.);
|
||||
/// assert_eq!(a.cofactor(3, 2), 105.);
|
||||
/// assert_eq!(b[(2, 3)], 105. / 532.);
|
||||
/// assert_eq!(
|
||||
/// b,
|
||||
/// Matrix4x4::new(
|
||||
/// [0.21804512, 0.45112783, 0.24060151, -0.04511278],
|
||||
/// [-0.8082707, -1.456767, -0.44360903, 0.5206767],
|
||||
/// [-0.078947365, -0.2236842, -0.05263158, 0.19736843],
|
||||
/// [-0.52255636, -0.81390977, -0.30075186, 0.30639097]
|
||||
/// )
|
||||
/// );
|
||||
///
|
||||
/// // Second test case
|
||||
/// assert_eq!(
|
||||
/// Matrix4x4::new(
|
||||
/// [8., -5., 9., 2.],
|
||||
/// [7., 5., 6., 1.],
|
||||
/// [-6., 0., 9., 6.],
|
||||
/// [-3., 0., -9., -4.],
|
||||
/// )
|
||||
/// .inverse(),
|
||||
/// Matrix4x4::new(
|
||||
/// [-0.15384616, -0.15384616, -0.2820513, -0.53846157],
|
||||
/// [-0.07692308, 0.12307692, 0.025641026, 0.03076923],
|
||||
/// [0.35897437, 0.35897437, 0.43589744, 0.9230769],
|
||||
/// [-0.6923077, -0.6923077, -0.7692308, -1.9230769]
|
||||
/// ),
|
||||
/// );
|
||||
///
|
||||
/// // Third test case
|
||||
/// assert_eq!(
|
||||
/// Matrix4x4::new(
|
||||
/// [9., 3., 0., 9.],
|
||||
/// [-5., -2., -6., -3.],
|
||||
/// [-4., 9., 6., 4.],
|
||||
/// [-7., 6., 6., 2.],
|
||||
/// )
|
||||
/// .inverse(),
|
||||
/// Matrix4x4::new(
|
||||
/// [-0.04074074, -0.07777778, 0.14444445, -0.22222222],
|
||||
/// [-0.07777778, 0.033333335, 0.36666667, -0.33333334],
|
||||
/// [-0.029012345, -0.14629629, -0.10925926, 0.12962963],
|
||||
/// [0.17777778, 0.06666667, -0.26666668, 0.33333334]
|
||||
/// ),
|
||||
/// );
|
||||
///
|
||||
/// let a = Matrix4x4::new(
|
||||
/// [3., -9., 7., 3.],
|
||||
/// [3., -8., 2., -9.],
|
||||
/// [-4., 4., 4., 1.],
|
||||
/// [-6., 5., -1., 1.],
|
||||
/// );
|
||||
/// let b = Matrix4x4::new(
|
||||
/// [8., 2., 2., 2.],
|
||||
/// [3., -1., 7., 0.],
|
||||
/// [7., 0., 5., 4.],
|
||||
/// [6., -2., 0., 5.],
|
||||
/// );
|
||||
/// let c = a * b;
|
||||
/// assert_eq!(c * b.inverse(), a);
|
||||
/// ```
|
||||
pub fn inverse(&self) -> Matrix4x4 {
|
||||
self.inverse_rtc()
|
||||
}
|
||||
@@ -416,6 +776,17 @@ impl Mul<Matrix4x4> for Matrix4x4 {
|
||||
type Output = Matrix4x4;
|
||||
|
||||
/// Implement matrix multiplication for `Matrix4x4`.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix4x4;
|
||||
///
|
||||
/// let i = Matrix4x4::identity();
|
||||
/// let m1 = Matrix4x4::identity();
|
||||
/// let m2 = Matrix4x4::identity();
|
||||
///
|
||||
/// assert_eq!(m1 * m2, i);
|
||||
/// ```
|
||||
fn mul(self, m2: Matrix4x4) -> Matrix4x4 {
|
||||
let m1 = self;
|
||||
let mut r: Matrix4x4 = Default::default();
|
||||
@@ -435,6 +806,22 @@ impl Mul<Tuple> for Matrix4x4 {
|
||||
type Output = Tuple;
|
||||
|
||||
/// Implement matrix multiplication for `Matrix4x4` * `Tuple`.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::matrices::Matrix4x4;
|
||||
/// use rtchallenge::tuples::Tuple;
|
||||
///
|
||||
/// let a = Matrix4x4::new(
|
||||
/// [1., 2., 3., 4.],
|
||||
/// [2., 4., 4., 2.],
|
||||
/// [8., 6., 4., 1.],
|
||||
/// [0., 0., 0., 1.],
|
||||
/// );
|
||||
/// let b = Tuple::new(1., 2., 3., 1.);
|
||||
///
|
||||
/// assert_eq!(a * b, Tuple::new(18., 24., 33., 1.));
|
||||
/// ```
|
||||
fn mul(self, t: Tuple) -> Tuple {
|
||||
let m = self;
|
||||
Tuple {
|
||||
@@ -494,235 +881,6 @@ impl IndexMut<(usize, usize)> for Matrix4x4 {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use crate::{
|
||||
float::consts::PI,
|
||||
tuples::{point, vector},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn example4x4() {
|
||||
// Individual transformations are applied in sequence.
|
||||
let p = point(1., 0., 1.);
|
||||
let a = Matrix4x4::rotation_x(PI / 2.);
|
||||
let b = Matrix4x4::scaling(5., 5., 5.);
|
||||
let c = Matrix4x4::translation(10., 5., 7.);
|
||||
// Apply rotation first.
|
||||
let p2 = a * p;
|
||||
assert_eq!(p2, point(1., -1., 0.));
|
||||
// Then apply scaling.
|
||||
let p3 = b * p2;
|
||||
assert_eq!(p3, point(5., -5., 0.));
|
||||
// Then apply translation.
|
||||
let p4 = c * p3;
|
||||
assert_eq!(p4, point(15., 0., 7.));
|
||||
|
||||
// Chained transformations must be applied in reverse order.
|
||||
let p = point(1., 0., 1.);
|
||||
let a = Matrix4x4::rotation_x(PI / 2.);
|
||||
let b = Matrix4x4::scaling(5., 5., 5.);
|
||||
let c = Matrix4x4::translation(10., 5., 7.);
|
||||
let t = c * b * a;
|
||||
assert_eq!(t * p, point(15., 0., 7.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translation() {
|
||||
let transform = Matrix4x4::translation(5., -3., 2.);
|
||||
let p = point(-3., 4., 5.);
|
||||
assert_eq!(transform * p, point(2., 1., 7.));
|
||||
|
||||
let inv = transform.inverse();
|
||||
assert_eq!(inv * p, point(-8., 7., 3.));
|
||||
|
||||
let v = vector(-3., 4., 5.);
|
||||
assert_eq!(transform * v, v);
|
||||
}
|
||||
#[test]
|
||||
fn scaling() {
|
||||
// A scaling matrix applied to a point.
|
||||
let transform = Matrix4x4::scaling(2., 3., 4.);
|
||||
let p = point(-4., 6., 8.);
|
||||
assert_eq!(transform * p, point(-8., 18., 32.));
|
||||
|
||||
// A scaling matrix applied to a vector.
|
||||
let v = vector(-4., 6., 8.);
|
||||
assert_eq!(transform * v, vector(-8., 18., 32.));
|
||||
|
||||
// Multiplying by the inverse of a scaling matrix.
|
||||
let inv = transform.inverse();
|
||||
assert_eq!(inv * v, vector(-2., 2., 2.));
|
||||
|
||||
// Reflection is scaling by a negative value.
|
||||
let transform = Matrix4x4::scaling(-1., 1., 1.);
|
||||
let p = point(2., 3., 4.);
|
||||
assert_eq!(transform * p, point(-2., 3., 4.));
|
||||
}
|
||||
#[test]
|
||||
fn rotation_x() {
|
||||
// A scaling matrix applied to a point.
|
||||
let p = point(0., 1., 0.);
|
||||
let half_quarter = Matrix4x4::rotation_x(PI / 4.);
|
||||
let full_quarter = Matrix4x4::rotation_x(PI / 2.);
|
||||
|
||||
assert_eq!(
|
||||
half_quarter * p,
|
||||
point(0., (2.0 as Float).sqrt() / 2., (2.0 as Float).sqrt() / 2.)
|
||||
);
|
||||
assert_eq!(full_quarter * p, point(0., 0., 1.),);
|
||||
}
|
||||
#[test]
|
||||
fn rotation_y() {
|
||||
// A scaling matrix applied to a point.
|
||||
let p = point(0., 0., 1.);
|
||||
let half_quarter = Matrix4x4::rotation_y(PI / 4.);
|
||||
let full_quarter = Matrix4x4::rotation_y(PI / 2.);
|
||||
|
||||
assert_eq!(
|
||||
half_quarter * p,
|
||||
point((2.0 as Float).sqrt() / 2., 0., (2.0 as Float).sqrt() / 2.)
|
||||
);
|
||||
assert_eq!(full_quarter * p, point(1., 0., 0.,),);
|
||||
}
|
||||
#[test]
|
||||
fn rotation_z() {
|
||||
// A scaling matrix applied to a point.
|
||||
let p = point(0., 1., 0.);
|
||||
let half_quarter = Matrix4x4::rotation_z(PI / 4.);
|
||||
let full_quarter = Matrix4x4::rotation_z(PI / 2.);
|
||||
|
||||
assert_eq!(
|
||||
half_quarter * p,
|
||||
point(-(2.0 as Float).sqrt() / 2., (2.0 as Float).sqrt() / 2., 0.)
|
||||
);
|
||||
assert_eq!(full_quarter * p, point(-1., 0., 0.,),);
|
||||
}
|
||||
#[test]
|
||||
fn transpose() {
|
||||
let m = Matrix4x4::new(
|
||||
[2., 0., 0., 0.],
|
||||
[3., 1., 0., 0.],
|
||||
[4., 0., 1., 0.],
|
||||
[5., 6., 7., 1.],
|
||||
);
|
||||
let m_t = Matrix4x4::new(
|
||||
[2., 3., 4., 5.],
|
||||
[0., 1., 0., 6.],
|
||||
[0., 0., 1., 7.],
|
||||
[0., 0., 0., 1.],
|
||||
);
|
||||
assert_eq!(m.transpose(), m_t);
|
||||
|
||||
assert_eq!(Matrix4x4::identity(), Matrix4x4::identity().transpose());
|
||||
}
|
||||
#[test]
|
||||
fn shearing() {
|
||||
// A shearing transform moves x in proportion to y.
|
||||
let transform = Matrix4x4::shearing(1., 0., 0., 0., 0., 0.);
|
||||
let p = point(2., 3., 4.);
|
||||
assert_eq!(transform * p, point(5., 3., 4.));
|
||||
|
||||
// A shearing transform moves x in proportion to z.
|
||||
let transform = Matrix4x4::shearing(0., 1., 0., 0., 0., 0.);
|
||||
let p = point(2., 3., 4.);
|
||||
assert_eq!(transform * p, point(6., 3., 4.));
|
||||
|
||||
// A shearing transform moves y in proportion to x.
|
||||
let transform = Matrix4x4::shearing(0., 0., 1., 0., 0., 0.);
|
||||
let p = point(2., 3., 4.);
|
||||
assert_eq!(transform * p, point(2., 5., 4.));
|
||||
|
||||
// A shearing transform moves y in proportion to z.
|
||||
let transform = Matrix4x4::shearing(0., 0., 0., 1., 0., 0.);
|
||||
let p = point(2., 3., 4.);
|
||||
assert_eq!(transform * p, point(2., 7., 4.));
|
||||
|
||||
// A shearing transform moves z in proportion to x.
|
||||
let transform = Matrix4x4::shearing(0., 0., 0., 0., 1., 0.);
|
||||
let p = point(2., 3., 4.);
|
||||
assert_eq!(transform * p, point(2., 3., 6.));
|
||||
|
||||
// A shearing transform moves z in proportion to y.
|
||||
let transform = Matrix4x4::shearing(0., 0., 0., 0., 0., 1.);
|
||||
let p = point(2., 3., 4.);
|
||||
assert_eq!(transform * p, point(2., 3., 7.));
|
||||
}
|
||||
#[test]
|
||||
fn inverse_rtiow() {
|
||||
let i = Matrix4x4::identity();
|
||||
assert_eq!(i.inverse_rtiow() * i, i);
|
||||
|
||||
let m = Matrix4x4::new(
|
||||
[2., 0., 0., 0.],
|
||||
[0., 3., 0., 0.],
|
||||
[0., 0., 4., 0.],
|
||||
[0., 0., 0., 1.],
|
||||
);
|
||||
assert_eq!(m.inverse_rtiow() * m, i);
|
||||
assert_eq!(m * m.inverse_rtiow(), i);
|
||||
}
|
||||
#[test]
|
||||
fn determinant_2x2() {
|
||||
let a = Matrix2x2::new([1., 5.], [-3., 2.]);
|
||||
|
||||
assert_eq!(a.determinant(), 17.);
|
||||
}
|
||||
#[test]
|
||||
fn determinant_3x3() {
|
||||
let a = Matrix3x3::new([1., 2., 6.], [-5., 8., -4.], [2., 6., 4.]);
|
||||
assert_eq!(a.cofactor(0, 0), 56.);
|
||||
assert_eq!(a.cofactor(0, 1), 12.);
|
||||
assert_eq!(a.cofactor(0, 2), -46.);
|
||||
assert_eq!(a.determinant(), -196.);
|
||||
}
|
||||
#[test]
|
||||
fn determinant_4x4() {
|
||||
let a = Matrix4x4::new(
|
||||
[-2., -8., 3., 5.],
|
||||
[-3., 1., 7., 3.],
|
||||
[1., 2., -9., 6.],
|
||||
[-6., 7., 7., -9.],
|
||||
);
|
||||
assert_eq!(a.cofactor(0, 0), 690.);
|
||||
assert_eq!(a.cofactor(0, 1), 447.);
|
||||
assert_eq!(a.cofactor(0, 2), 210.);
|
||||
assert_eq!(a.cofactor(0, 3), 51.);
|
||||
assert_eq!(a.determinant(), -4071.);
|
||||
}
|
||||
#[test]
|
||||
fn submatrix_3x3() {
|
||||
assert_eq!(
|
||||
Matrix3x3::new([1., 5., 0.], [-3., 2., 7.], [0., 6., -3.],).submatrix(0, 2),
|
||||
Matrix2x2::new([-3., 2.], [0., 6.])
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn submatrix_4x4() {
|
||||
assert_eq!(
|
||||
Matrix4x4::new(
|
||||
[-6., 1., 1., 6.],
|
||||
[-8., 5., 8., 6.],
|
||||
[-1., 0., 8., 2.],
|
||||
[-7., 1., -1., 1.],
|
||||
)
|
||||
.submatrix(2, 1),
|
||||
Matrix3x3::new([-6., 1., 6.], [-8., 8., 6.], [-7., -1., 1.],)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn minor_3x3() {
|
||||
let a = Matrix3x3::new([3., 5., 0.], [2., -1., -7.], [6., -1., 5.]);
|
||||
let b = a.submatrix(1, 0);
|
||||
assert_eq!(b.determinant(), 25.0);
|
||||
assert_eq!(b.determinant(), a.minor(1, 0));
|
||||
}
|
||||
#[test]
|
||||
fn cofactor_3x3() {
|
||||
let a = Matrix3x3::new([3., 5., 0.], [2., -1., -7.], [6., -1., 5.]);
|
||||
assert_eq!(a.minor(0, 0), -12.);
|
||||
assert_eq!(a.cofactor(0, 0), -12.);
|
||||
assert_eq!(a.minor(1, 0), 25.);
|
||||
assert_eq!(a.cofactor(1, 0), -25.);
|
||||
}
|
||||
#[test]
|
||||
fn construct2x2() {
|
||||
let m = Matrix2x2::new([-3., 5.], [1., -2.]);
|
||||
@@ -741,100 +899,6 @@ mod tests {
|
||||
assert_eq!(m[(2, 2)], 1.);
|
||||
}
|
||||
#[test]
|
||||
fn invertable() {
|
||||
let a = Matrix4x4::new(
|
||||
[6., 4., 4., 4.],
|
||||
[5., 5., 7., 6.],
|
||||
[4., -9., 3., -7.],
|
||||
[9., 1., 7., -6.],
|
||||
);
|
||||
assert_eq!(a.determinant(), -2120.);
|
||||
assert_eq!(a.invertable(), true);
|
||||
|
||||
let a = Matrix4x4::new(
|
||||
[-4., 2., -2., -3.],
|
||||
[9., 6., 2., 6.],
|
||||
[0., -5., 1., -5.],
|
||||
[0., 0., 0., 0.],
|
||||
);
|
||||
assert_eq!(a.determinant(), 0.);
|
||||
assert_eq!(a.invertable(), false);
|
||||
}
|
||||
#[test]
|
||||
fn inverse() {
|
||||
let a = Matrix4x4::new(
|
||||
[-5., 2., 6., -8.],
|
||||
[1., -5., 1., 8.],
|
||||
[7., 7., -6., -7.],
|
||||
[1., -3., 7., 4.],
|
||||
);
|
||||
let b = a.inverse();
|
||||
|
||||
assert_eq!(a.determinant(), 532.);
|
||||
assert_eq!(a.cofactor(2, 3), -160.);
|
||||
assert_eq!(b[(3, 2)], -160. / 532.);
|
||||
assert_eq!(a.cofactor(3, 2), 105.);
|
||||
assert_eq!(b[(2, 3)], 105. / 532.);
|
||||
assert_eq!(
|
||||
b,
|
||||
Matrix4x4::new(
|
||||
[0.21804512, 0.45112783, 0.24060151, -0.04511278],
|
||||
[-0.8082707, -1.456767, -0.44360903, 0.5206767],
|
||||
[-0.078947365, -0.2236842, -0.05263158, 0.19736843],
|
||||
[-0.52255636, -0.81390977, -0.30075186, 0.30639097]
|
||||
)
|
||||
);
|
||||
|
||||
// Second test case
|
||||
assert_eq!(
|
||||
Matrix4x4::new(
|
||||
[8., -5., 9., 2.],
|
||||
[7., 5., 6., 1.],
|
||||
[-6., 0., 9., 6.],
|
||||
[-3., 0., -9., -4.],
|
||||
)
|
||||
.inverse(),
|
||||
Matrix4x4::new(
|
||||
[-0.15384616, -0.15384616, -0.2820513, -0.53846157],
|
||||
[-0.07692308, 0.12307692, 0.025641026, 0.03076923],
|
||||
[0.35897437, 0.35897437, 0.43589744, 0.9230769],
|
||||
[-0.6923077, -0.6923077, -0.7692308, -1.9230769]
|
||||
),
|
||||
);
|
||||
|
||||
// Third test case
|
||||
assert_eq!(
|
||||
Matrix4x4::new(
|
||||
[9., 3., 0., 9.],
|
||||
[-5., -2., -6., -3.],
|
||||
[-4., 9., 6., 4.],
|
||||
[-7., 6., 6., 2.],
|
||||
)
|
||||
.inverse(),
|
||||
Matrix4x4::new(
|
||||
[-0.04074074, -0.07777778, 0.14444445, -0.22222222],
|
||||
[-0.07777778, 0.033333335, 0.36666667, -0.33333334],
|
||||
[-0.029012345, -0.14629629, -0.10925926, 0.12962963],
|
||||
[0.17777778, 0.06666667, -0.26666668, 0.33333334]
|
||||
),
|
||||
);
|
||||
|
||||
let a = Matrix4x4::new(
|
||||
[3., -9., 7., 3.],
|
||||
[3., -8., 2., -9.],
|
||||
[-4., 4., 4., 1.],
|
||||
[-6., 5., -1., 1.],
|
||||
);
|
||||
let b = Matrix4x4::new(
|
||||
[8., 2., 2., 2.],
|
||||
[3., -1., 7., 0.],
|
||||
[7., 0., 5., 4.],
|
||||
[6., -2., 0., 5.],
|
||||
);
|
||||
let c = a * b;
|
||||
assert_eq!(c * b.inverse(), a);
|
||||
}
|
||||
#[test]
|
||||
fn construct4x4() {
|
||||
let m = Matrix4x4::new(
|
||||
[1., 2., 3., 4.],
|
||||
@@ -907,16 +971,4 @@ mod tests {
|
||||
)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn mul4x4_tuple() {
|
||||
let a = Matrix4x4::new(
|
||||
[1., 2., 3., 4.],
|
||||
[2., 4., 4., 2.],
|
||||
[8., 6., 4., 1.],
|
||||
[0., 0., 0., 1.],
|
||||
);
|
||||
let b = Tuple::new(1., 2., 3., 1.);
|
||||
|
||||
assert_eq!(a * b, Tuple::new(18., 24., 33., 1.));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,444 +0,0 @@
|
||||
use derive_builder::Builder;
|
||||
|
||||
use crate::{
|
||||
matrices::Matrix4x4,
|
||||
shapes::Shape,
|
||||
tuples::{Color, Tuple},
|
||||
BLACK, WHITE,
|
||||
};
|
||||
|
||||
pub const BLACK_PAT: Pattern = Pattern {
|
||||
color: ColorMapper::Constant(BLACK),
|
||||
transform: Matrix4x4::identity(),
|
||||
inverse_transform: Matrix4x4::identity(),
|
||||
};
|
||||
pub const WHITE_PAT: Pattern = Pattern {
|
||||
color: ColorMapper::Constant(WHITE),
|
||||
transform: Matrix4x4::identity(),
|
||||
inverse_transform: Matrix4x4::identity(),
|
||||
};
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum ColorMapper {
|
||||
/// TestPattern the color returned is the pattern space point after going through world->object and object->pattern space translation.
|
||||
TestPattern,
|
||||
/// Solid color, the same sampled every where.
|
||||
Constant(Color),
|
||||
/// Pattern that alternates between the given patterns along each unit of the X-axis. The
|
||||
/// strip extends infinitely in the positive and negative Y and Z axes.
|
||||
Stripe { a: Box<Pattern>, b: Box<Pattern> },
|
||||
/// Linear blend between `a` and `b` along the X-axis.
|
||||
Gradient { a: Box<Pattern>, b: Box<Pattern> },
|
||||
/// Bullseye pattern in the XZ plane.
|
||||
Ring { a: Box<Pattern>, b: Box<Pattern> },
|
||||
/// Traditional ray tracer tile floor pattern.
|
||||
Checkers { a: Box<Pattern>, b: Box<Pattern> },
|
||||
}
|
||||
|
||||
impl From<Color> for ColorMapper {
|
||||
fn from(c: Color) -> ColorMapper {
|
||||
ColorMapper::Constant(c)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Color> for Box<Pattern> {
|
||||
fn from(c: Color) -> Box<Pattern> {
|
||||
Box::new(Pattern {
|
||||
color: ColorMapper::Constant(c),
|
||||
..Pattern::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Builder, Debug, PartialEq, Clone)]
|
||||
#[builder(default, pattern = "immutable")]
|
||||
pub struct Pattern {
|
||||
pub color: ColorMapper,
|
||||
transform: Matrix4x4,
|
||||
#[builder(private, default = "self.default_inverse_transform()?")]
|
||||
inverse_transform: Matrix4x4,
|
||||
}
|
||||
|
||||
impl PatternBuilder {
|
||||
fn default_inverse_transform(&self) -> Result<Matrix4x4, String> {
|
||||
Ok(self.transform.unwrap_or(Matrix4x4::identity()).inverse())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Pattern {
|
||||
fn default() -> Pattern {
|
||||
Pattern {
|
||||
color: ColorMapper::Constant(WHITE),
|
||||
transform: Matrix4x4::identity(),
|
||||
inverse_transform: Matrix4x4::identity(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [Pattern] with a color type of [ColorMapper::Constant] from the given [Color]
|
||||
impl<C> From<C> for Pattern
|
||||
where
|
||||
C: Into<Color>,
|
||||
{
|
||||
fn from(c: C) -> Self {
|
||||
Pattern {
|
||||
color: ColorMapper::Constant(c.into()),
|
||||
..Pattern::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builder for creating a material pattern used for testing. The color returned is the pattern space point
|
||||
/// after going through world->object and object->pattern space translation.
|
||||
pub fn test_pattern() -> PatternBuilder {
|
||||
PatternBuilder::default().color(ColorMapper::TestPattern)
|
||||
}
|
||||
|
||||
/// Builder for creating a material pattern that alternates between the given colors along each unit of the
|
||||
/// X-axis. The strip extends infinitely in the positive and negative Y and Z axes.
|
||||
pub fn stripe_pattern(a: Pattern, b: Pattern) -> PatternBuilder {
|
||||
PatternBuilder::default().color(ColorMapper::Stripe {
|
||||
a: a.into(),
|
||||
b: b.into(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Builder for creating a material pattern that gradually blends between the given colors along
|
||||
/// the X-axis.
|
||||
pub fn gradient_pattern(a: Pattern, b: Pattern) -> PatternBuilder {
|
||||
PatternBuilder::default().color(ColorMapper::Gradient {
|
||||
a: a.into(),
|
||||
b: b.into(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Builder for creating a material pattern that alternates between the given colors in a ring
|
||||
/// shape in the XZ plane.
|
||||
pub fn ring_pattern(a: Pattern, b: Pattern) -> PatternBuilder {
|
||||
PatternBuilder::default().color(ColorMapper::Ring {
|
||||
a: a.into(),
|
||||
b: b.into(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Builder for creating a material pattern that alternates between the given colors along the X, Y
|
||||
/// and Z pattern. Creates traditional ray tracer tile floor pattern.
|
||||
pub fn checkers_pattern(a: Pattern, b: Pattern) -> PatternBuilder {
|
||||
PatternBuilder::default().color(ColorMapper::Checkers {
|
||||
a: a.into(),
|
||||
b: b.into(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Generic implementation for mapping points to colors according to the given [ColorMapper].
|
||||
impl Pattern {
|
||||
/// Create a pattern used for testing. The color returned is the pattern space point
|
||||
/// after going through world->object and object->pattern space translation.
|
||||
pub fn test() -> Pattern {
|
||||
Pattern {
|
||||
color: ColorMapper::TestPattern,
|
||||
..Pattern::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a pattern that alternates between the given Patterns along each unit of the
|
||||
/// X-axis. The strip extends infinitely in the positive and negative Y and Z axes.
|
||||
pub fn stripe(a: Pattern, b: Pattern) -> Pattern {
|
||||
Pattern {
|
||||
color: ColorMapper::Stripe {
|
||||
a: a.into(),
|
||||
b: b.into(),
|
||||
},
|
||||
..Pattern::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a pattern that gradually blends between the given Patterns along the X-axis.
|
||||
pub fn gradient(a: Pattern, b: Pattern) -> Pattern {
|
||||
Pattern {
|
||||
color: ColorMapper::Gradient {
|
||||
a: a.into(),
|
||||
b: b.into(),
|
||||
},
|
||||
..Pattern::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a pattern that alternates between the given Patterns in a ring in the XZ plane.
|
||||
pub fn ring(a: Pattern, b: Pattern) -> Pattern {
|
||||
Pattern {
|
||||
color: ColorMapper::Ring {
|
||||
a: a.into(),
|
||||
b: b.into(),
|
||||
},
|
||||
..Pattern::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a pattern that alternates between the given Patterns along the X, Y and Z axis.
|
||||
pub fn checkers(a: Pattern, b: Pattern) -> Pattern {
|
||||
Pattern {
|
||||
color: ColorMapper::Checkers {
|
||||
a: a.into(),
|
||||
b: b.into(),
|
||||
},
|
||||
..Pattern::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Sample the color at the given point in untranslated object space.
|
||||
pub fn pattern_at(&self, object_point: Tuple) -> Color {
|
||||
let point = self.inverse_transform * object_point;
|
||||
match &self.color {
|
||||
ColorMapper::TestPattern => [point.x, point.y, point.z].into(),
|
||||
ColorMapper::Constant(c) => *c,
|
||||
ColorMapper::Stripe { a, b } => {
|
||||
let x = point.x.floor();
|
||||
if x % 2. == 0. {
|
||||
a.pattern_at(point)
|
||||
} else {
|
||||
b.pattern_at(point)
|
||||
}
|
||||
}
|
||||
ColorMapper::Gradient { a, b } => {
|
||||
let a = a.pattern_at(point);
|
||||
let b = b.pattern_at(point);
|
||||
let distance = b - a;
|
||||
let fraction = point.x - point.x.floor();
|
||||
a + distance * fraction
|
||||
}
|
||||
ColorMapper::Ring { a, b } => {
|
||||
let a = a.pattern_at(point);
|
||||
let b = b.pattern_at(point);
|
||||
let px = point.x;
|
||||
let pz = point.z;
|
||||
if (px * px + pz * pz).sqrt().floor() % 2. == 0. {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
ColorMapper::Checkers { a, b } => {
|
||||
let a = a.pattern_at(point);
|
||||
let b = b.pattern_at(point);
|
||||
let d = point.x.floor() + point.y.floor() + point.z.floor();
|
||||
if d % 2. == 0. {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Sample the color at the given world point on the given object.
|
||||
/// This function respects the object and the pattern's transform matrix.
|
||||
pub fn pattern_at_object(&self, object: &Shape, world_point: Tuple) -> Color {
|
||||
let object_point = object.inverse_transform() * world_point;
|
||||
self.pattern_at(object_point)
|
||||
}
|
||||
pub fn transform(&self) -> Matrix4x4 {
|
||||
self.transform
|
||||
}
|
||||
|
||||
pub fn inverse_transform(&self) -> Matrix4x4 {
|
||||
self.inverse_transform
|
||||
}
|
||||
|
||||
pub fn set_transform(&mut self, t: Matrix4x4) {
|
||||
self.transform = t;
|
||||
self.inverse_transform = t.inverse();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
matrices::identity,
|
||||
patterns::{ColorMapper, Pattern, BLACK_PAT, WHITE_PAT},
|
||||
BLACK, WHITE,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_create() {
|
||||
let pattern = Pattern::test();
|
||||
assert_eq!(pattern.transform(), identity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stripe_create() {
|
||||
let pattern = Pattern::stripe(BLACK_PAT, WHITE_PAT);
|
||||
assert_eq!(
|
||||
pattern.color,
|
||||
ColorMapper::Stripe {
|
||||
a: BLACK.into(),
|
||||
b: WHITE.into(),
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn gradient_create() {
|
||||
println!("SHOE ME SOMETHING");
|
||||
println!("* * * 1");
|
||||
let pattern = Pattern::gradient(BLACK_PAT, WHITE_PAT);
|
||||
println!("* * * 2");
|
||||
assert_eq!(
|
||||
pattern.color,
|
||||
ColorMapper::Gradient {
|
||||
a: BLACK.into(),
|
||||
b: WHITE.into(),
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn ring_create() {
|
||||
let pattern = Pattern::ring(BLACK_PAT, WHITE_PAT);
|
||||
assert_eq!(
|
||||
pattern.color,
|
||||
ColorMapper::Ring {
|
||||
a: BLACK.into(),
|
||||
b: WHITE.into()
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn checkers_create() {
|
||||
let pattern = Pattern::checkers(BLACK_PAT, WHITE_PAT);
|
||||
assert_eq!(
|
||||
pattern.color,
|
||||
ColorMapper::Checkers {
|
||||
a: BLACK.into(),
|
||||
b: WHITE.into()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
mod pattern_at {
|
||||
use super::*;
|
||||
use crate::tuples::point;
|
||||
|
||||
#[test]
|
||||
fn test_returns_coordinates() {
|
||||
// A test returns the pattern space coordinates of the point.
|
||||
let pattern = Pattern::test();
|
||||
let p = point(1., 2., 3.);
|
||||
assert_eq!(pattern.pattern_at(p), [p.x, p.y, p.z].into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stripe_alternates_between_two_colors() {
|
||||
// A stripe alternates between two colors.
|
||||
let pattern = Pattern::stripe(WHITE_PAT, BLACK_PAT);
|
||||
for (p, want) in &[
|
||||
// A stripe pattern is constant in y.
|
||||
(point(0., 0., 0.), WHITE),
|
||||
(point(0., 1., 0.), WHITE),
|
||||
(point(0., 2., 0.), WHITE),
|
||||
// A stripe pattern is constant in z.
|
||||
(point(0., 0., 0.), WHITE),
|
||||
(point(0., 0., 1.), WHITE),
|
||||
(point(0., 0., 2.), WHITE),
|
||||
// A stripe pattern alternates in z.
|
||||
(point(0., 0., 0.), WHITE),
|
||||
(point(0.9, 0., 0.), WHITE),
|
||||
(point(1., 0., 0.), BLACK),
|
||||
(point(-0.1, 0., 0.), BLACK),
|
||||
(point(-1., 0., 0.), BLACK),
|
||||
(point(-1.1, 0., 0.), WHITE),
|
||||
] {
|
||||
assert_eq!(pattern.pattern_at(*p), *want, "{:?}", p);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_linearly_interpolates_between_colors() {
|
||||
// A gradient linearly interpolates between two colors.
|
||||
let pattern = Pattern::gradient(WHITE_PAT, BLACK_PAT);
|
||||
assert_eq!(pattern.pattern_at(point(0., 0., 0.)), WHITE);
|
||||
assert_eq!(
|
||||
pattern.pattern_at(point(0.25, 0., 0.)),
|
||||
[0.75, 0.75, 0.75].into()
|
||||
);
|
||||
assert_eq!(
|
||||
pattern.pattern_at(point(0.5, 0., 0.)),
|
||||
[0.5, 0.5, 0.5].into()
|
||||
);
|
||||
assert_eq!(
|
||||
pattern.pattern_at(point(0.75, 0., 0.)),
|
||||
[0.25, 0.25, 0.25].into()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_extend_in_x_and_z() {
|
||||
// A ring should extend both in x and z.
|
||||
let pattern = Pattern::ring(WHITE_PAT, BLACK_PAT);
|
||||
assert_eq!(pattern.pattern_at(point(0., 0., 0.)), WHITE);
|
||||
assert_eq!(pattern.pattern_at(point(1., 0., 0.)), BLACK);
|
||||
assert_eq!(pattern.pattern_at(point(0., 0., 1.)), BLACK);
|
||||
// 0.708 is slight more than 2.sqrt()/2.
|
||||
assert_eq!(pattern.pattern_at(point(0.708, 0., 0.708)), BLACK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkers_repeat_along_x_axis() {
|
||||
// Checkers should repeat along X-axis.
|
||||
let pattern = Pattern::checkers(WHITE_PAT, BLACK_PAT);
|
||||
assert_eq!(pattern.pattern_at(point(0., 0., 0.)), WHITE);
|
||||
assert_eq!(pattern.pattern_at(point(0.99, 0., 0.)), WHITE);
|
||||
assert_eq!(pattern.pattern_at(point(1.01, 0., 0.)), BLACK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkers_repeat_along_y_axis() {
|
||||
// Checkers should repeat along Y-axis.
|
||||
let pattern = Pattern::checkers(WHITE_PAT, BLACK_PAT);
|
||||
assert_eq!(pattern.pattern_at(point(0., 0., 0.)), WHITE);
|
||||
assert_eq!(pattern.pattern_at(point(0., 0.99, 0.)), WHITE);
|
||||
assert_eq!(pattern.pattern_at(point(0., 1.01, 0.)), BLACK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkers_repeat_along_z_axis() {
|
||||
// Checkers should repeat along Z-axis.
|
||||
let pattern = Pattern::checkers(WHITE_PAT, BLACK_PAT);
|
||||
assert_eq!(pattern.pattern_at(point(0., 0., 0.)), WHITE);
|
||||
assert_eq!(pattern.pattern_at(point(0., 0., 0.99)), WHITE);
|
||||
assert_eq!(pattern.pattern_at(point(0., 0., 1.01)), BLACK);
|
||||
}
|
||||
}
|
||||
|
||||
mod pattern_at_object {
|
||||
use std::error::Error;
|
||||
|
||||
use crate::{
|
||||
matrices::scaling,
|
||||
patterns::{stripe_pattern, BLACK_PAT, WHITE_PAT},
|
||||
shapes::{Shape, ShapeBuilder},
|
||||
tuples::point,
|
||||
WHITE,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn stripes_with_an_object_transformation() -> Result<(), Box<dyn Error>> {
|
||||
// Stripes with an object transformation.
|
||||
let object = ShapeBuilder::sphere()
|
||||
.transform(scaling(2., 2., 2.))
|
||||
.build()?;
|
||||
let pattern = stripe_pattern(WHITE_PAT, BLACK_PAT).build()?;
|
||||
let c = pattern.pattern_at_object(&object, point(1.5, 0., 0.));
|
||||
assert_eq!(c, WHITE);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stripes_with_a_pattern_transformation() -> Result<(), Box<dyn Error>> {
|
||||
// Stripes with a pattern transformation.
|
||||
let object = Shape::sphere();
|
||||
let mut pattern = stripe_pattern(WHITE_PAT, BLACK_PAT).build()?;
|
||||
pattern.set_transform(scaling(2., 2., 2.));
|
||||
let c = pattern.pattern_at_object(&object, point(1.5, 0., 0.));
|
||||
assert_eq!(c, WHITE);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use crate::{matrices::Matrix4x4, tuples::Tuple, Float};
|
||||
|
||||
/// Rays have an origin and a direction. This datatype is the 'ray' in 'raytracer'.
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct Ray {
|
||||
pub origin: Tuple,
|
||||
pub direction: Tuple,
|
||||
@@ -10,6 +9,17 @@ pub struct Ray {
|
||||
impl Ray {
|
||||
/// Create a ray with the given origin point and direction vector.
|
||||
/// Will panic if origin not a point or direction not a vector.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{rays::Ray, tuples::Tuple};
|
||||
///
|
||||
/// let origin = Tuple::point(1., 2., 3.);
|
||||
/// let direction = Tuple::vector(4., 5., 6.);
|
||||
/// let r = Ray::new(origin, direction);
|
||||
/// assert_eq!(r.origin, origin);
|
||||
/// assert_eq!(r.direction, direction);
|
||||
/// ```
|
||||
pub fn new(origin: Tuple, direction: Tuple) -> Ray {
|
||||
assert!(origin.is_point(), "Ray origin must be a point");
|
||||
assert!(direction.is_vector(), "Ray direction must be a vector");
|
||||
@@ -17,11 +27,41 @@ impl Ray {
|
||||
}
|
||||
|
||||
/// Compute a point from the given distance along the `Ray`.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{rays::Ray, tuples::Tuple};
|
||||
///
|
||||
/// let r = Ray::new(Tuple::point(2., 3., 4.), Tuple::vector(1., 0., 0.));
|
||||
/// assert_eq!(r.position(0.), Tuple::point(2., 3., 4.));
|
||||
/// assert_eq!(r.position(1.), Tuple::point(3., 3., 4.));
|
||||
/// assert_eq!(r.position(-1.), Tuple::point(1., 3., 4.));
|
||||
/// assert_eq!(r.position(2.5), Tuple::point(4.5, 3., 4.));
|
||||
/// ```
|
||||
pub fn position(&self, t: Float) -> Tuple {
|
||||
self.origin + self.direction * t
|
||||
}
|
||||
|
||||
/// Apply Matrix4x4 transforms to Ray.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{matrices::Matrix4x4, rays::Ray, tuples::Tuple};
|
||||
///
|
||||
/// // Translating a ray
|
||||
/// let r = Ray::new(Tuple::point(1., 2., 3.), Tuple::vector(0., 1., 0.));
|
||||
/// let m = Matrix4x4::translation(3., 4., 5.);
|
||||
/// let r2 = r.transform(m);
|
||||
/// assert_eq!(r2.origin, Tuple::point(4., 6., 8.));
|
||||
/// assert_eq!(r2.direction, Tuple::vector(0., 1., 0.));
|
||||
///
|
||||
/// // Scaling a ray
|
||||
/// let r = Ray::new(Tuple::point(1., 2., 3.), Tuple::vector(0., 1., 0.));
|
||||
/// let m = Matrix4x4::scaling(2., 3., 4.);
|
||||
/// let r2 = r.transform(m);
|
||||
/// assert_eq!(r2.origin, Tuple::point(2., 6., 12.));
|
||||
/// assert_eq!(r2.direction, Tuple::vector(0., 3., 0.));
|
||||
/// ```
|
||||
pub fn transform(&self, m: Matrix4x4) -> Ray {
|
||||
Ray {
|
||||
origin: m * self.origin,
|
||||
@@ -29,46 +69,3 @@ impl Ray {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
matrices::Matrix4x4,
|
||||
rays::Ray,
|
||||
tuples::{point, vector},
|
||||
};
|
||||
#[test]
|
||||
fn create() {
|
||||
let origin = point(1., 2., 3.);
|
||||
let direction = vector(4., 5., 6.);
|
||||
let r = Ray::new(origin, direction);
|
||||
assert_eq!(r.origin, origin);
|
||||
assert_eq!(r.direction, direction);
|
||||
}
|
||||
#[test]
|
||||
fn position() {
|
||||
let r = Ray::new(point(2., 3., 4.), vector(1., 0., 0.));
|
||||
assert_eq!(r.position(0.), point(2., 3., 4.));
|
||||
assert_eq!(r.position(1.), point(3., 3., 4.));
|
||||
assert_eq!(r.position(-1.), point(1., 3., 4.));
|
||||
assert_eq!(r.position(2.5), point(4.5, 3., 4.));
|
||||
}
|
||||
#[test]
|
||||
fn transform_translating_ray() {
|
||||
// Translating a ray
|
||||
let r = Ray::new(point(1., 2., 3.), vector(0., 1., 0.));
|
||||
let m = Matrix4x4::translation(3., 4., 5.);
|
||||
let r2 = r.transform(m);
|
||||
assert_eq!(r2.origin, point(4., 6., 8.));
|
||||
assert_eq!(r2.direction, vector(0., 1., 0.));
|
||||
}
|
||||
#[test]
|
||||
fn transform_scaling_ray() {
|
||||
// Scaling a ray
|
||||
let r = Ray::new(point(1., 2., 3.), vector(0., 1., 0.));
|
||||
let m = Matrix4x4::scaling(2., 3., 4.);
|
||||
let r2 = r.transform(m);
|
||||
assert_eq!(r2.origin, point(2., 6., 12.));
|
||||
assert_eq!(r2.direction, vector(0., 3., 0.));
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,47 @@ use crate::{
|
||||
|
||||
/// Create a matrix representing a eye at `from` looking at `to`, with an `up`
|
||||
/// as the up vector.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{matrices::Matrix4x4, transformations::view_transform, tuples::Tuple};
|
||||
///
|
||||
/// // The transofrmation matrix for the default orientation.
|
||||
/// let from = Tuple::point(0., 0., 0.);
|
||||
/// let to = Tuple::point(0., 0., -1.);
|
||||
/// let up = Tuple::vector(0., 1., 0.);
|
||||
/// let t = view_transform(from, to, up);
|
||||
/// assert_eq!(t, Matrix4x4::identity());
|
||||
///
|
||||
/// // A view transformation matrix looking in positive z direction.
|
||||
/// let from = Tuple::point(0., 0., 0.);
|
||||
/// let to = Tuple::point(0., 0., 1.);
|
||||
/// let up = Tuple::vector(0., 1., 0.);
|
||||
/// let t = view_transform(from, to, up);
|
||||
/// assert_eq!(t, Matrix4x4::scaling(-1., 1., -1.));
|
||||
///
|
||||
/// // The view tranformation moves the world.
|
||||
/// let from = Tuple::point(0., 0., 8.);
|
||||
/// let to = Tuple::point(0., 0., 0.);
|
||||
/// let up = Tuple::vector(0., 1., 0.);
|
||||
/// let t = view_transform(from, to, up);
|
||||
/// assert_eq!(t, Matrix4x4::translation(0., 0., -8.));
|
||||
///
|
||||
/// // An arbitrary view transformation.
|
||||
/// let from = Tuple::point(1., 3., 2.);
|
||||
/// let to = Tuple::point(4., -2., 8.);
|
||||
/// let up = Tuple::vector(1., 1., 0.);
|
||||
/// let t = view_transform(from, to, up);
|
||||
/// assert_eq!(
|
||||
/// t,
|
||||
/// Matrix4x4::new(
|
||||
/// [-0.50709, 0.50709, 0.67612, -2.36643],
|
||||
/// [0.76772, 0.60609, 0.12122, -2.82843],
|
||||
/// [-0.35857, 0.59761, -0.71714, 0.],
|
||||
/// [0., 0., 0., 1.],
|
||||
/// )
|
||||
/// );
|
||||
/// ```
|
||||
pub fn view_transform(from: Tuple, to: Tuple, up: Tuple) -> Matrix4x4 {
|
||||
let forward = (to - from).normalize();
|
||||
let left = cross(forward, up.normalize());
|
||||
@@ -16,56 +57,3 @@ pub fn view_transform(from: Tuple, to: Tuple, up: Tuple) -> Matrix4x4 {
|
||||
[0., 0., 0., 1.],
|
||||
) * Matrix4x4::translation(-from.x, -from.y, -from.z)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
matrices::{identity, scaling, translation, Matrix4x4},
|
||||
transformations::view_transform,
|
||||
tuples::{point, vector},
|
||||
};
|
||||
#[test]
|
||||
fn default_orientation() {
|
||||
// The transformation matrix for the default orientation.
|
||||
let from = point(0., 0., 0.);
|
||||
let to = point(0., 0., -1.);
|
||||
let up = vector(0., 1., 0.);
|
||||
let t = view_transform(from, to, up);
|
||||
assert_eq!(t, identity());
|
||||
}
|
||||
#[test]
|
||||
fn looking_positive_z() {
|
||||
// A view transformation matrix looking in positive z direction.
|
||||
let from = point(0., 0., 0.);
|
||||
let to = point(0., 0., 1.);
|
||||
let up = vector(0., 1., 0.);
|
||||
let t = view_transform(from, to, up);
|
||||
assert_eq!(t, scaling(-1., 1., -1.));
|
||||
}
|
||||
#[test]
|
||||
fn transformation_moves_world() {
|
||||
// The view transformation moves the world.
|
||||
let from = point(0., 0., 8.);
|
||||
let to = point(0., 0., 0.);
|
||||
let up = vector(0., 1., 0.);
|
||||
let t = view_transform(from, to, up);
|
||||
assert_eq!(t, translation(0., 0., -8.));
|
||||
}
|
||||
#[test]
|
||||
fn arbitrary_view() {
|
||||
// An arbitrary view transformation.
|
||||
let from = point(1., 3., 2.);
|
||||
let to = point(4., -2., 8.);
|
||||
let up = vector(1., 1., 0.);
|
||||
let t = view_transform(from, to, up);
|
||||
assert_eq!(
|
||||
t,
|
||||
Matrix4x4::new(
|
||||
[-0.50709, 0.50709, 0.67612, -2.36643],
|
||||
[0.76772, 0.60609, 0.12122, -2.82843],
|
||||
[-0.35857, 0.59761, -0.71714, 0.],
|
||||
[0., 0., 0., 1.],
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,7 @@ use std::ops::{Add, Div, Mul, Neg, Sub};
|
||||
|
||||
use crate::{Float, EPSILON};
|
||||
|
||||
/// Short hand for creating a Tuple that represents a point, w=1.
|
||||
pub fn point(x: Float, y: Float, z: Float) -> Tuple {
|
||||
Tuple::point(x, y, z)
|
||||
}
|
||||
|
||||
/// Short hand for creating a Tuple that represents a vector, w=0.
|
||||
pub fn vector(x: Float, y: Float, z: Float) -> Tuple {
|
||||
Tuple::vector(x, y, z)
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Copy, Clone)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct Tuple {
|
||||
pub x: Float,
|
||||
pub y: Float,
|
||||
@@ -57,6 +47,26 @@ impl Tuple {
|
||||
}
|
||||
|
||||
/// Reflects vector v across normal n.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// tuples::{reflect, Tuple},
|
||||
/// Float,
|
||||
/// };
|
||||
///
|
||||
/// // Reflecting a vector approaching at 45°
|
||||
/// let v = Tuple::vector(1., -1., 0.);
|
||||
/// let n = Tuple::vector(0., 1., 0.);
|
||||
/// let r = reflect(v, n);
|
||||
/// assert_eq!(r, Tuple::vector(1., 1., 0.));
|
||||
///
|
||||
/// // Reflecting off a slanted surface.
|
||||
/// let v = Tuple::vector(0., -1., 0.);
|
||||
/// let n = Tuple::vector((2. as Float).sqrt() / 2., (2. as Float).sqrt() / 2., 0.);
|
||||
/// let r = reflect(v, n);
|
||||
/// assert_eq!(r, Tuple::vector(1., 0., 0.));
|
||||
/// ```
|
||||
pub fn reflect(v: Tuple, n: Tuple) -> Tuple {
|
||||
v - n * 2. * dot(v, n)
|
||||
}
|
||||
@@ -151,29 +161,17 @@ pub fn cross(a: Tuple, b: Tuple) -> Tuple {
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct Color {
|
||||
pub red: Float,
|
||||
pub green: Float,
|
||||
pub blue: Float,
|
||||
}
|
||||
|
||||
impl Color {
|
||||
pub const fn new(red: Float, green: Float, blue: Float) -> Color {
|
||||
Color { red, green, blue }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<[Float; 3]> for Color {
|
||||
fn from(rgb: [Float; 3]) -> Self {
|
||||
Color {
|
||||
red: rgb[0],
|
||||
green: rgb[1],
|
||||
blue: rgb[2],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Color {
|
||||
fn eq(&self, rhs: &Color) -> bool {
|
||||
((self.red - rhs.red).abs() < EPSILON)
|
||||
@@ -181,7 +179,6 @@ impl PartialEq for Color {
|
||||
&& ((self.blue - rhs.blue).abs() < EPSILON)
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for Color {
|
||||
type Output = Self;
|
||||
fn add(self, other: Self) -> Self {
|
||||
@@ -225,7 +222,6 @@ impl Mul<Color> for Float {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<Color> for Color {
|
||||
type Output = Color;
|
||||
fn mul(self, rhs: Color) -> Self::Output {
|
||||
@@ -247,7 +243,6 @@ impl Neg for Color {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for Color {
|
||||
type Output = Self;
|
||||
fn sub(self, other: Self) -> Self {
|
||||
@@ -261,7 +256,7 @@ impl Sub for Color {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{cross, dot, reflect, Color, Float, Tuple, EPSILON};
|
||||
use super::{cross, dot, Color, Float, Tuple, EPSILON};
|
||||
#[test]
|
||||
fn is_point() {
|
||||
// A tuple with w = 1 is a point
|
||||
@@ -420,20 +415,4 @@ mod tests {
|
||||
let c2 = Color::new(0.9, 1., 0.1);
|
||||
assert_eq!(c1 * c2, Color::new(1.0 * 0.9, 0.2 * 1., 0.4 * 0.1));
|
||||
}
|
||||
#[test]
|
||||
fn reflect_approaching_at_45() {
|
||||
// Reflecting a vector approaching at 45°
|
||||
let v = Tuple::vector(1., -1., 0.);
|
||||
let n = Tuple::vector(0., 1., 0.);
|
||||
let r = reflect(v, n);
|
||||
assert_eq!(r, Tuple::vector(1., 1., 0.));
|
||||
}
|
||||
#[test]
|
||||
fn reflect_slanted_surface() {
|
||||
// Reflecting off a slanted surface.
|
||||
let v = Tuple::vector(0., -1., 0.);
|
||||
let n = Tuple::vector((2. as Float).sqrt() / 2., (2. as Float).sqrt() / 2., 0.);
|
||||
let r = reflect(v, n);
|
||||
assert_eq!(r, Tuple::vector(1., 0., 0.));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,26 @@
|
||||
use derive_builder::Builder;
|
||||
|
||||
use crate::{
|
||||
intersections::{prepare_computations, schlick, Intersections, PrecomputedData},
|
||||
intersections::{prepare_computations, Intersections, PrecomputedData},
|
||||
lights::PointLight,
|
||||
materials::{lighting, Material},
|
||||
matrices::Matrix4x4,
|
||||
rays::Ray,
|
||||
shapes::{intersect, Shape},
|
||||
tuples::{dot, Color, Tuple},
|
||||
BLACK, WHITE,
|
||||
tuples::{Color, Tuple},
|
||||
Float, BLACK, WHITE,
|
||||
};
|
||||
|
||||
/// World holds all drawable objects and the light(s) that illuminate them.
|
||||
#[derive(Builder, Clone, Debug, Default)]
|
||||
#[builder(default)]
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::world::World;
|
||||
///
|
||||
/// let w = World::default();
|
||||
/// assert!(w.objects.is_empty());
|
||||
/// assert_eq!(w.lights.len(), 0);
|
||||
/// ```
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct World {
|
||||
pub lights: Vec<PointLight>,
|
||||
pub objects: Vec<Shape>,
|
||||
@@ -21,15 +28,24 @@ pub struct World {
|
||||
|
||||
impl World {
|
||||
/// Creates a world suitable for use across multiple tests in from the book.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::world::World;
|
||||
///
|
||||
/// let w = World::test_world();
|
||||
/// assert_eq!(w.objects.len(), 2);
|
||||
/// assert!(!w.lights.is_empty());
|
||||
/// ```
|
||||
pub fn test_world() -> World {
|
||||
let light = PointLight::new(Tuple::point(-10., 10., -10.), WHITE);
|
||||
let mut s1 = Shape::sphere();
|
||||
s1.material = Material {
|
||||
color: [0.8, 1., 0.6].into(),
|
||||
s1.set_material(Material {
|
||||
color: Color::new(0.8, 1., 0.6),
|
||||
diffuse: 0.7,
|
||||
specular: 0.2,
|
||||
..Material::default()
|
||||
};
|
||||
});
|
||||
let mut s2 = Shape::sphere();
|
||||
s2.set_transform(Matrix4x4::scaling(0.5, 0.5, 0.5));
|
||||
World {
|
||||
@@ -38,9 +54,28 @@ impl World {
|
||||
}
|
||||
}
|
||||
|
||||
/// Intersects the ray with this world.
|
||||
/// Intesects the ray with this world.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{rays::Ray, tuples::Tuple, world::World};
|
||||
///
|
||||
/// let w = World::test_world();
|
||||
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
|
||||
/// let xs = w.intersect(&r);
|
||||
/// assert_eq!(xs.len(), 4);
|
||||
/// assert_eq!(xs[0].t, 4.);
|
||||
/// assert_eq!(xs[1].t, 4.5);
|
||||
/// assert_eq!(xs[2].t, 5.5);
|
||||
/// assert_eq!(xs[3].t, 6.);
|
||||
/// ```
|
||||
pub fn intersect(&self, r: &Ray) -> Intersections {
|
||||
let mut xs: Vec<_> = self.objects.iter().flat_map(|o| intersect(o, r)).collect();
|
||||
let mut xs: Vec<_> = self
|
||||
.objects
|
||||
.iter()
|
||||
.map(|o| intersect(&o, &r))
|
||||
.flatten()
|
||||
.collect();
|
||||
xs.sort_by(|i1, i2| {
|
||||
i1.t.partial_cmp(&i2.t)
|
||||
.expect("an intersection has a t value that is NaN")
|
||||
@@ -49,46 +84,147 @@ impl World {
|
||||
}
|
||||
|
||||
/// Compute shaded value for given precomputation.
|
||||
pub fn shade_hit(&self, comps: &PrecomputedData, remaining: usize) -> Color {
|
||||
let surface = self
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// intersections::{prepare_computations, Intersection},
|
||||
/// lights::PointLight,
|
||||
/// matrices::Matrix4x4,
|
||||
/// rays::Ray,
|
||||
/// shapes::Shape,
|
||||
/// tuples::{Color, Tuple},
|
||||
/// world::World,
|
||||
/// WHITE,
|
||||
/// };
|
||||
///
|
||||
/// // Shading an intersection.
|
||||
/// let w = World::test_world();
|
||||
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
|
||||
/// let s = &w.objects[0];
|
||||
/// let i = Intersection::new(4., &s);
|
||||
/// let comps = prepare_computations(&i, &r);
|
||||
/// let c = w.shade_hit(&comps);
|
||||
/// assert_eq!(c, Color::new(0.38066, 0.47583, 0.2855));
|
||||
///
|
||||
/// // Shading an intersection from the inside.
|
||||
/// let mut w = World::test_world();
|
||||
/// w.lights = vec![PointLight::new(Tuple::point(0., 0.25, 0.), WHITE)];
|
||||
/// let r = Ray::new(Tuple::point(0., 0., 0.), Tuple::vector(0., 0., 1.));
|
||||
/// let s = &w.objects[1];
|
||||
/// let i = Intersection::new(0.5, &s);
|
||||
/// let comps = prepare_computations(&i, &r);
|
||||
/// let c = w.shade_hit(&comps);
|
||||
/// assert_eq!(c, Color::new(0.90498, 0.90498, 0.90498));
|
||||
///
|
||||
/// // Shading with an intersection in shadow.
|
||||
/// let mut w = World::default();
|
||||
/// w.lights = vec![PointLight::new(Tuple::point(0., 0., -10.), WHITE)];
|
||||
/// let s1 = Shape::sphere();
|
||||
/// let mut s2 = Shape::sphere();
|
||||
/// s2.set_transform(Matrix4x4::translation(0., 0., 10.));
|
||||
/// w.objects = vec![s1, s2.clone()];
|
||||
/// let r = Ray::new(Tuple::point(0., 0., 5.), Tuple::vector(0., 0., 1.));
|
||||
/// let i = Intersection::new(4., &s2);
|
||||
/// let comps = prepare_computations(&i, &r);
|
||||
/// let c = w.shade_hit(&comps);
|
||||
/// assert_eq!(c, Color::new(0.1, 0.1, 0.1));
|
||||
/// ```
|
||||
pub fn shade_hit(&self, comps: &PrecomputedData) -> Color {
|
||||
let c = self
|
||||
.lights
|
||||
.iter()
|
||||
.fold(Color::new(0., 0., 0.), |acc, light| {
|
||||
let shadowed = self.is_shadowed(comps.over_point, light);
|
||||
let surface = lighting(
|
||||
&comps.object.material,
|
||||
comps.object,
|
||||
acc + lighting(
|
||||
&comps.object.material(),
|
||||
light,
|
||||
comps.over_point,
|
||||
comps.eyev,
|
||||
comps.normalv,
|
||||
shadowed,
|
||||
);
|
||||
acc + surface
|
||||
)
|
||||
});
|
||||
let reflected = self.reflected_color(comps, remaining);
|
||||
let refracted = self.refracted_color(comps, remaining);
|
||||
let material = &comps.object.material;
|
||||
if material.reflective > 0. && material.transparency > 0. {
|
||||
let reflectance = schlick(comps);
|
||||
surface + reflected * reflectance + refracted * (1. - reflectance)
|
||||
} else {
|
||||
surface + reflected + refracted
|
||||
}
|
||||
c / self.lights.len() as Float
|
||||
}
|
||||
/// Compute color for given ray fired at the world.
|
||||
pub fn color_at(&self, r: &Ray, remaining: usize) -> Color {
|
||||
let xs = self.intersect(r);
|
||||
match xs.hit() {
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// intersections::{prepare_computations, Intersection},
|
||||
/// lights::PointLight,
|
||||
/// rays::Ray,
|
||||
/// shapes::Shape,
|
||||
/// tuples::{Color, Tuple},
|
||||
/// world::World,
|
||||
/// BLACK,
|
||||
/// };
|
||||
///
|
||||
/// // The color when a ray misses.
|
||||
/// let w = World::test_world();
|
||||
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 1., 0.));
|
||||
/// let c = w.color_at(&r);
|
||||
/// assert_eq!(c, BLACK);
|
||||
///
|
||||
/// // The color when a ray hits.
|
||||
/// let w = World::test_world();
|
||||
/// let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.));
|
||||
/// let c = w.color_at(&r);
|
||||
/// assert_eq!(c, Color::new(0.38066, 0.47583, 0.2855));
|
||||
///
|
||||
/// // The color with an intersection behind the ray.
|
||||
/// let w = {
|
||||
/// let mut w = World::test_world();
|
||||
/// let mut outer = &mut w.objects[0];
|
||||
/// let m = outer.material_mut().ambient = 1.;
|
||||
/// let inner = &mut w.objects[1];
|
||||
/// inner.material_mut().ambient = 1.;
|
||||
/// w
|
||||
/// };
|
||||
/// let inner = &w.objects[1];
|
||||
/// let r = Ray::new(Tuple::point(0., 0., 0.75), Tuple::vector(0., 0., -1.));
|
||||
/// let c = w.color_at(&r);
|
||||
/// assert_eq!(c, inner.material().color);
|
||||
/// ```
|
||||
pub fn color_at(&self, r: &Ray) -> Color {
|
||||
match self.intersect(r).hit() {
|
||||
Some(hit) => {
|
||||
let comps = prepare_computations(hit, r, &xs);
|
||||
self.shade_hit(&comps, remaining)
|
||||
let comps = prepare_computations(&hit, r);
|
||||
self.shade_hit(&comps)
|
||||
}
|
||||
None => BLACK,
|
||||
}
|
||||
}
|
||||
|
||||
/// Determine if point in world is in a shadow.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use rtchallenge::{
|
||||
/// tuples::{ Tuple},
|
||||
/// shapes::Shape,
|
||||
/// world::World,
|
||||
/// };
|
||||
///
|
||||
/// let w = World::test_world();
|
||||
/// let light = &w.lights[0];
|
||||
///
|
||||
/// // There is no shadow when nothing is collinear with point and light.
|
||||
/// let p = Tuple::point(0.,10.,0.);
|
||||
/// assert_eq!(w.is_shadowed(p,light), false);
|
||||
///
|
||||
/// // There shadow when an object is between the point and the light.
|
||||
/// let p = Tuple::point(10.,-10.,10.);
|
||||
/// assert_eq!(w.is_shadowed(p,light), true);
|
||||
///
|
||||
/// // There is no shadow when an object is behind the light.
|
||||
/// let p = Tuple::point(-20.,20.,-20.);
|
||||
/// assert_eq!(w.is_shadowed(p,light), false);
|
||||
///
|
||||
/// // There is no shadow when an object is behind the point.
|
||||
/// let p = Tuple::point(-2.,2.,-2.);
|
||||
/// assert_eq!(w.is_shadowed(p,light), false);
|
||||
pub fn is_shadowed(&self, point: Tuple, light: &PointLight) -> bool {
|
||||
let v = light.position - point;
|
||||
let distance = v.magnitude();
|
||||
@@ -101,455 +237,4 @@ impl World {
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Compute reflected color for the given precomputation.
|
||||
pub fn reflected_color(&self, comps: &PrecomputedData, remaining: usize) -> Color {
|
||||
if remaining == 0 {
|
||||
return BLACK;
|
||||
}
|
||||
if comps.object.material.reflective == 0. {
|
||||
return BLACK;
|
||||
}
|
||||
// Fire reflected ray to figure out color.
|
||||
let reflect_ray = Ray::new(comps.over_point, comps.reflectv);
|
||||
let color = self.color_at(&reflect_ray, remaining - 1);
|
||||
color * comps.object.material.reflective
|
||||
}
|
||||
|
||||
/// Compute refracted color for the given precomputation.
|
||||
pub fn refracted_color(&self, comps: &PrecomputedData, remaining: usize) -> Color {
|
||||
if remaining == 0 {
|
||||
return BLACK;
|
||||
}
|
||||
if comps.object.material.transparency == 0. {
|
||||
return BLACK;
|
||||
}
|
||||
// Find the ratio of the first index of refraction to the secon
|
||||
// (This is inverted from the definition of Snell's Law.)
|
||||
let n_ratio = comps.n1 / comps.n2;
|
||||
|
||||
// cos(theta_i) is the same as the dot product of the two vectors
|
||||
// TODO(wathiede): is cosine faster than doc productings?
|
||||
let cos_i = dot(comps.eyev, comps.normalv);
|
||||
|
||||
// Find the sin(theta_t)^2 via trigonometric identity.
|
||||
let sin2_t = n_ratio * n_ratio * (1. - cos_i * cos_i);
|
||||
|
||||
if sin2_t > 1. {
|
||||
// Total internal reflection.
|
||||
return BLACK;
|
||||
}
|
||||
// Find cos(theta_t) via trigonometric identity.
|
||||
let cos_t = (1. - sin2_t).sqrt();
|
||||
// Compute the direction of the refracted ray.
|
||||
let direction = comps.normalv * (n_ratio * cos_i - cos_t) - comps.eyev * n_ratio;
|
||||
// Create the refracted ray.
|
||||
let refract_ray = Ray::new(comps.under_point, direction);
|
||||
// Find he color of the refracted ray, making sure to multiply by the transparency value to
|
||||
// account for any opacity.
|
||||
self.color_at(&refract_ray, remaining - 1) * comps.object.material.transparency
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
float::consts::SQRT_2,
|
||||
intersections::{prepare_computations, Intersection, Intersections},
|
||||
lights::PointLight,
|
||||
materials::MaterialBuilder,
|
||||
matrices::translation,
|
||||
patterns::test_pattern,
|
||||
rays::Ray,
|
||||
shapes::{plane, sphere, Shape, ShapeBuilder},
|
||||
tuples::{point, vector},
|
||||
world::{World, WorldBuilder},
|
||||
Float, BLACK, WHITE,
|
||||
};
|
||||
|
||||
mod intersect {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn intersection_with_test_world() {
|
||||
let w = World::test_world();
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let xs = w.intersect(&r);
|
||||
assert_eq!(xs.len(), 4);
|
||||
assert_eq!(xs[0].t, 4.);
|
||||
assert_eq!(xs[1].t, 4.5);
|
||||
assert_eq!(xs[2].t, 5.5);
|
||||
assert_eq!(xs[3].t, 6.);
|
||||
}
|
||||
}
|
||||
mod world {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn default_world() {
|
||||
let w = World::default();
|
||||
assert!(w.objects.is_empty());
|
||||
assert_eq!(w.lights.len(), 0);
|
||||
}
|
||||
#[test]
|
||||
fn test_world() {
|
||||
let w = World::test_world();
|
||||
assert_eq!(w.objects.len(), 2);
|
||||
assert!(!w.lights.is_empty());
|
||||
}
|
||||
}
|
||||
mod shade_hit {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shading_an_intersection() {
|
||||
// Shading an intersection.
|
||||
let w = World::test_world();
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let s = &w.objects[0];
|
||||
let xs = Intersections::from(Intersection::new(4., &s));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let c = w.shade_hit(&comps, 1);
|
||||
assert_eq!(c, [0.38066, 0.47583, 0.2855].into());
|
||||
}
|
||||
#[test]
|
||||
fn shading_an_intersection_from_inside() {
|
||||
// Shading an intersection from the inside.
|
||||
let mut w = World::test_world();
|
||||
w.lights = vec![PointLight::new(point(0., 0.25, 0.), WHITE)];
|
||||
let r = Ray::new(point(0., 0., 0.), vector(0., 0., 1.));
|
||||
let s = &w.objects[1];
|
||||
let xs = Intersections::from(Intersection::new(0.5, &s));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let c = w.shade_hit(&comps, 1);
|
||||
assert_eq!(c, [0.90498, 0.90498, 0.90498].into());
|
||||
}
|
||||
#[test]
|
||||
fn shading_an_intersection_in_shadow() {
|
||||
// Shading with an intersection in shadow.
|
||||
let mut w = World::default();
|
||||
w.lights = vec![PointLight::new(point(0., 0., -10.), WHITE)];
|
||||
let s1 = Shape::sphere();
|
||||
let mut s2 = Shape::sphere();
|
||||
s2.set_transform(translation(0., 0., 10.));
|
||||
w.objects = vec![s1, s2.clone()];
|
||||
let r = Ray::new(point(0., 0., 5.), vector(0., 0., 1.));
|
||||
let xs = Intersections::from(Intersection::new(4., &s2));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let c = w.shade_hit(&comps, 1);
|
||||
assert_eq!(c, [0.1, 0.1, 0.1].into());
|
||||
}
|
||||
#[test]
|
||||
fn shading_with_a_reflective_material() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Shading with a reflective material.
|
||||
let mut w = World::test_world();
|
||||
let shape = ShapeBuilder::plane()
|
||||
.material(MaterialBuilder::default().reflective(0.5).build()?)
|
||||
.transform(translation(0., -1., 0.))
|
||||
.build()?;
|
||||
w.objects.push(shape.clone());
|
||||
let r = Ray::new(
|
||||
point(0., 0., -3.),
|
||||
vector(0., -(2 as Float).sqrt() / 2., (2 as Float).sqrt() / 2.),
|
||||
);
|
||||
let xs = Intersections::from(Intersection::new((2 as Float).sqrt(), &shape));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let c = w.shade_hit(&comps, 1);
|
||||
assert_eq!(c, [0.87676, 0.92434, 0.82917].into());
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn shading_with_a_transparent_material() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// shade_hit() with a transparent material.
|
||||
let mut w = World::test_world();
|
||||
let floor = plane()
|
||||
.transform(translation(0., -1., 0.))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.transparency(0.5)
|
||||
.refractive_index(1.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
w.objects.push(floor.clone());
|
||||
let ball = sphere()
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([1., 0., 0.])
|
||||
.ambient(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.transform(translation(0., -3.5, -0.5))
|
||||
.build()?;
|
||||
w.objects.push(ball);
|
||||
let r = Ray::new(
|
||||
point(0., 0., -3.),
|
||||
vector(0., -(2 as Float).sqrt() / 2., (2 as Float).sqrt() / 2.),
|
||||
);
|
||||
let xs = Intersections::new(vec![Intersection::new((2 as Float).sqrt(), &floor)]);
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let c = w.shade_hit(&comps, 5);
|
||||
assert_eq!(c, [0.93642, 0.68642, 0.68643].into());
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn reflective_transparent_material() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut w = World::test_world();
|
||||
let floor = plane()
|
||||
.transform(translation(0., -1., 0.))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.reflective(0.5)
|
||||
.transparency(0.5)
|
||||
.refractive_index(1.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
w.objects.push(floor.clone());
|
||||
let ball = sphere()
|
||||
.transform(translation(0., -3.5, -0.5))
|
||||
.material(
|
||||
MaterialBuilder::default()
|
||||
.color([1., 0., 0.])
|
||||
.ambient(0.5)
|
||||
.build()?,
|
||||
)
|
||||
.build()?;
|
||||
w.objects.push(ball);
|
||||
let r = Ray::new(point(0., 0., -3.), vector(0., -SQRT_2 / 2., SQRT_2 / 2.));
|
||||
let xs = Intersections::new(vec![Intersection::new(SQRT_2, &floor)]);
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let color = w.shade_hit(&comps, 5);
|
||||
assert_eq!(color, [0.93391, 0.69643, 0.69243].into());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
mod color_at {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn color_when_ray_misses() {
|
||||
// The color when a ray misses.
|
||||
let w = World::test_world();
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 1., 0.));
|
||||
let c = w.color_at(&r, 1);
|
||||
assert_eq!(c, BLACK);
|
||||
}
|
||||
#[test]
|
||||
fn color_when_ray_hits() {
|
||||
// The color when a ray hits.
|
||||
let w = World::test_world();
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let c = w.color_at(&r, 1);
|
||||
assert_eq!(c, [0.38066, 0.47583, 0.2855].into());
|
||||
}
|
||||
#[test]
|
||||
fn color_with_an_intersection_behind_ray() {
|
||||
// The color with an intersection behind the ray.
|
||||
let w = {
|
||||
let mut w = World::test_world();
|
||||
let mut outer = &mut w.objects[0];
|
||||
outer.material.ambient = 1.;
|
||||
let inner = &mut w.objects[1];
|
||||
inner.material.ambient = 1.;
|
||||
w
|
||||
};
|
||||
let r = Ray::new(point(0., 0., 0.75), vector(0., 0., -1.));
|
||||
let c = w.color_at(&r, 1);
|
||||
// inner.material.color is WHITE
|
||||
assert_eq!(c, WHITE);
|
||||
}
|
||||
#[test]
|
||||
fn ensure_mutually_reflective_surfaces_terminate() -> Result<(), Box<dyn std::error::Error>>
|
||||
{
|
||||
// Ensure mutually reflective surfaces don't infinitely recurse.
|
||||
let lower = ShapeBuilder::plane()
|
||||
.material(MaterialBuilder::default().reflective(1.).build()?)
|
||||
.transform(translation(0., -1., 0.))
|
||||
.build()?;
|
||||
let upper = ShapeBuilder::plane()
|
||||
.material(MaterialBuilder::default().reflective(1.).build()?)
|
||||
.transform(translation(0., 1., 0.))
|
||||
.build()?;
|
||||
let w = WorldBuilder::default()
|
||||
.lights(vec![PointLight::new(point(0., 0., 0.), WHITE)])
|
||||
.objects(vec![lower, upper])
|
||||
.build()?;
|
||||
let r = Ray::new(point(0., 0., 0.), vector(0., 1., 0.));
|
||||
// This should complete without stack overflow.
|
||||
w.color_at(&r, 1);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
mod is_shadowed {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_shadow_when_nothing_collinear_with_point_and_light() {
|
||||
// There is no shadow when nothing is collinear with point and light.
|
||||
let w = World::test_world();
|
||||
let light = &w.lights[0];
|
||||
|
||||
let p = point(0., 10., 0.);
|
||||
assert_eq!(w.is_shadowed(p, light), false);
|
||||
}
|
||||
#[test]
|
||||
fn shadow_when_object_between_point_and_light() {
|
||||
// The shadow when an object is between the point and the light.
|
||||
let w = World::test_world();
|
||||
let light = &w.lights[0];
|
||||
|
||||
let p = point(10., -10., 10.);
|
||||
assert_eq!(w.is_shadowed(p, light), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_shadow_when_object_behind_light() {
|
||||
// There is no shadow when an object is behind the light.
|
||||
let w = World::test_world();
|
||||
let light = &w.lights[0];
|
||||
|
||||
let p = point(-20., 20., -20.);
|
||||
assert_eq!(w.is_shadowed(p, light), false);
|
||||
}
|
||||
#[test]
|
||||
fn no_shadow_when_object_behind_point() {
|
||||
// There is no shadow when an object is behind the point.
|
||||
let w = World::test_world();
|
||||
let light = &w.lights[0];
|
||||
|
||||
let p = point(-2., 2., -2.);
|
||||
assert_eq!(w.is_shadowed(p, light), false);
|
||||
}
|
||||
}
|
||||
|
||||
mod reflected_color {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reflected_color_for_nonreflective_material() {
|
||||
// The reflected color for a nonreflective material.
|
||||
let r = Ray::new(point(0., 0., 0.), vector(0., 0., 1.));
|
||||
let mut w = World::test_world();
|
||||
w.objects[1].material.ambient = 1.;
|
||||
let xs = Intersections::from(Intersection::new(1., &w.objects[1]));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let c = w.reflected_color(&comps, 1);
|
||||
assert_eq!(c, BLACK);
|
||||
}
|
||||
#[test]
|
||||
fn reflected_color_for_reflective_material() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// The reflected color for a reflective material.
|
||||
let mut w = World::test_world();
|
||||
let shape = ShapeBuilder::plane()
|
||||
.material(MaterialBuilder::default().reflective(0.5).build()?)
|
||||
.transform(translation(0., -1., 0.))
|
||||
.build()?;
|
||||
w.objects.push(shape.clone());
|
||||
let r = Ray::new(
|
||||
point(0., 0., -3.),
|
||||
vector(0., -(2 as Float).sqrt() / 2., (2 as Float).sqrt() / 2.),
|
||||
);
|
||||
let xs = Intersections::from(Intersection::new((2 as Float).sqrt(), &shape));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let c = w.reflected_color(&comps, 1);
|
||||
assert_eq!(c, [0.19033, 0.23791, 0.14274].into());
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn reflected_color_at_maximum_recursion_depth() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// The reflected color at the maximum recursion depth.
|
||||
let mut w = World::test_world();
|
||||
let shape = ShapeBuilder::plane()
|
||||
.material(MaterialBuilder::default().reflective(0.5).build()?)
|
||||
.transform(translation(0., -1., 0.))
|
||||
.build()?;
|
||||
w.objects.push(shape.clone());
|
||||
let r = Ray::new(
|
||||
point(0., 0., -3.),
|
||||
vector(0., -(2 as Float).sqrt() / 2., (2 as Float).sqrt() / 2.),
|
||||
);
|
||||
let xs = Intersections::from(Intersection::new((2 as Float).sqrt(), &shape));
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let _ = w.reflected_color(&comps, 0);
|
||||
// Just needs to get here without infinite recursion.
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
mod refracted_color {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn refracted_color_with_opaque_surface() {
|
||||
// The refracted color with an opaque surface.
|
||||
let w = World::test_world();
|
||||
let shape = &w.objects[0];
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let xs = Intersections::new(vec![
|
||||
Intersection::new(4., &shape),
|
||||
Intersection::new(6., &shape),
|
||||
]);
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let c = w.refracted_color(&comps, 5);
|
||||
assert_eq!(c, BLACK);
|
||||
}
|
||||
#[test]
|
||||
fn refracted_color_at_maximum_recursion_depth() {
|
||||
// The refracted color at the maximum recursive depth.
|
||||
let mut w = World::test_world();
|
||||
w.objects[0].material.transparency = 1.0;
|
||||
w.objects[0].material.refractive_index = 1.5;
|
||||
let shape = &w.objects[0];
|
||||
let r = Ray::new(point(0., 0., -5.), vector(0., 0., 1.));
|
||||
let xs = Intersections::new(vec![
|
||||
Intersection::new(4., &shape),
|
||||
Intersection::new(6., &shape),
|
||||
]);
|
||||
let comps = prepare_computations(&xs[0], &r, &xs);
|
||||
let c = w.refracted_color(&comps, 0);
|
||||
assert_eq!(c, BLACK);
|
||||
}
|
||||
#[test]
|
||||
fn refracted_color_under_total_internal_reflection() {
|
||||
// The refracted color under total internal reflection.
|
||||
let mut w = World::test_world();
|
||||
w.objects[0].material.transparency = 1.0;
|
||||
w.objects[0].material.refractive_index = 1.5;
|
||||
let shape = &w.objects[0];
|
||||
let r = Ray::new(point(0., 0., (2 as Float).sqrt() / 2.), vector(0., 1., 0.));
|
||||
let xs = Intersections::new(vec![
|
||||
Intersection::new(-(2 as Float).sqrt() / 2., &shape),
|
||||
Intersection::new((2 as Float).sqrt() / 2., &shape),
|
||||
]);
|
||||
let comps = prepare_computations(&xs[1], &r, &xs);
|
||||
let c = w.refracted_color(&comps, 5);
|
||||
assert_eq!(c, BLACK);
|
||||
}
|
||||
#[test]
|
||||
fn refracted_color_with_a_refracted_ray() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// The refracted color with a refracted ray.
|
||||
let mut w = World::test_world();
|
||||
w.objects[0].material.ambient = 1.;
|
||||
w.objects[0].material.color = test_pattern().build()?;
|
||||
|
||||
w.objects[1].material.transparency = 1.;
|
||||
w.objects[1].material.refractive_index = 1.5;
|
||||
|
||||
let r = Ray::new(point(0., 0., 0.1), vector(0., 1., 0.));
|
||||
let a = &w.objects[0];
|
||||
let b = &w.objects[1];
|
||||
let xs = Intersections::new(vec![
|
||||
Intersection::new(-0.9899, &a),
|
||||
Intersection::new(-0.4899, &b),
|
||||
Intersection::new(0.4899, &b),
|
||||
Intersection::new(0.9899, &a),
|
||||
]);
|
||||
let comps = prepare_computations(&xs[2], &r, &xs);
|
||||
let c = w.refracted_color(&comps, 5);
|
||||
assert_eq!(c, [0., 0.99887, 0.04721].into());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
2277
rtiow/Cargo.lock
generated
2277
rtiow/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,13 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
|
||||
members = [
|
||||
"noise_explorer",
|
||||
"noise_explorer_warp",
|
||||
"renderer",
|
||||
"tracer",
|
||||
"vec3",
|
||||
]
|
||||
|
||||
[profile]
|
||||
[profile.release]
|
||||
debug = true
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 3
|
||||
|
||||
@@ -2,19 +2,19 @@
|
||||
name = "noise_explorer"
|
||||
version = "0.1.0"
|
||||
authors = ["Bill Thiede <git@xinu.tv>"]
|
||||
edition = "2021"
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
actix-web = "0.7.19"
|
||||
askama = "0.7.2"
|
||||
image = "0.22.5"
|
||||
log = "0.4.17"
|
||||
rand = "0.8.5"
|
||||
actix-web = "0.7.8"
|
||||
askama = "0.7.1"
|
||||
image = "0.22.3"
|
||||
log = "0.4.5"
|
||||
rand = "0.8.3"
|
||||
rand_xorshift = "0.3.0"
|
||||
renderer = { path = "../renderer" }
|
||||
serde = "1.0.152"
|
||||
serde_derive = "1.0.152"
|
||||
stderrlog = "0.4.3"
|
||||
structopt = "0.2.18"
|
||||
serde = "1.0.79"
|
||||
serde_derive = "1.0.79"
|
||||
stderrlog = "0.4.1"
|
||||
structopt = "0.2.10"
|
||||
|
||||
@@ -1,26 +1,44 @@
|
||||
use std::{fmt, time::SystemTime};
|
||||
use std::fmt;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use actix_web::{http, middleware, server, App, HttpRequest, HttpResponse, Path, Query, Result};
|
||||
use actix_web::http;
|
||||
use actix_web::middleware;
|
||||
use actix_web::server;
|
||||
use actix_web::App;
|
||||
use actix_web::HttpRequest;
|
||||
use actix_web::HttpResponse;
|
||||
use actix_web::Path;
|
||||
use actix_web::Query;
|
||||
use actix_web::Result;
|
||||
use askama::Template;
|
||||
use image;
|
||||
use log::info;
|
||||
use rand::SeedableRng;
|
||||
use rand_xorshift::XorShiftRng;
|
||||
use serde_derive::Deserialize;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use renderer::{
|
||||
noise,
|
||||
noise::{lode::Lode, perlin::Perlin, NoiseType},
|
||||
texture::{NoiseTexture, Texture},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use renderer::noise;
|
||||
use renderer::noise::lode::Lode;
|
||||
use renderer::noise::perlin::Perlin;
|
||||
use renderer::noise::NoiseType;
|
||||
use renderer::texture::NoiseTexture;
|
||||
use renderer::texture::Texture;
|
||||
use renderer::vec3::Vec3;
|
||||
|
||||
#[derive(StructOpt)]
|
||||
#[derive(Debug, StructOpt)]
|
||||
#[structopt(name = "noise_explorer", about = "CLI for exploring Perlin noise")]
|
||||
struct Opt {
|
||||
/// HTTP listen address
|
||||
#[structopt(long = "addr", default_value = "0.0.0.0:8889")]
|
||||
pub addr: String,
|
||||
|
||||
/// Width of noise images
|
||||
#[structopt(short = "w", long = "width", default_value = "128")]
|
||||
pub width: u32,
|
||||
/// Height of noise images
|
||||
#[structopt(short = "h", long = "height", default_value = "128")]
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Deserialize, PartialEq)]
|
||||
@@ -45,6 +63,11 @@ struct OptionalParams {
|
||||
pixel_scale: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct NoiseSourceParam {
|
||||
noise_source: NoiseSource,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct NoiseParams {
|
||||
width: u32,
|
||||
@@ -443,9 +466,16 @@ fn main() -> Result<(), std::io::Error> {
|
||||
mod tests {
|
||||
use std::str;
|
||||
|
||||
use actix_web::{http::Method, test::TestServer, HttpMessage, Path, Query};
|
||||
use actix_web::http::Method;
|
||||
use actix_web::test::TestServer;
|
||||
use actix_web::HttpMessage;
|
||||
use actix_web::Path;
|
||||
use actix_web::Query;
|
||||
|
||||
use super::{NoiseParamsMarble, NoiseParamsScale, NoiseParamsTurbulence, OptionalParams};
|
||||
use super::NoiseParamsMarble;
|
||||
use super::NoiseParamsScale;
|
||||
use super::NoiseParamsTurbulence;
|
||||
use super::OptionalParams;
|
||||
|
||||
#[test]
|
||||
fn noise_param_from_req() {
|
||||
|
||||
@@ -2,18 +2,18 @@
|
||||
name = "noise_explorer_warp"
|
||||
version = "0.1.0"
|
||||
authors = ["Bill Thiede <git@xinu.tv>"]
|
||||
edition = "2021"
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
askama = "0.7.2"
|
||||
image = "0.22.5"
|
||||
log = "0.4.17"
|
||||
rand = "0.5.6"
|
||||
askama = "0.7.1"
|
||||
image = "0.22.3"
|
||||
log = "0.4.5"
|
||||
rand = "0.5.5"
|
||||
renderer = { path = "../renderer" }
|
||||
serde = "1.0.152"
|
||||
serde_derive = "1.0.152"
|
||||
stderrlog = "0.4.3"
|
||||
structopt = "0.2.18"
|
||||
warp = "0.1.23"
|
||||
serde = "1.0.79"
|
||||
serde_derive = "1.0.79"
|
||||
stderrlog = "0.4.1"
|
||||
structopt = "0.2.10"
|
||||
warp = "0.1.20"
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
imports_granularity = "Crate"
|
||||
format_code_in_doc_comments = true
|
||||
@@ -2,41 +2,29 @@
|
||||
name = "renderer"
|
||||
version = "0.1.0"
|
||||
authors = ["Bill Thiede <git@xinu.tv>"]
|
||||
edition = "2021"
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[[bench]]
|
||||
harness = false
|
||||
name = "spheres"
|
||||
[[bench]]
|
||||
harness = false
|
||||
name = "aabb"
|
||||
|
||||
[dependencies]
|
||||
chrono = "*"
|
||||
core_affinity = "0.5"
|
||||
cpuprofiler = { version = "0.0.3", optional = true }
|
||||
image = "0.22.5"
|
||||
lazy_static = "1.4.0"
|
||||
log = "0.4.17"
|
||||
num_cpus = "1.15.0"
|
||||
rand = "0.8.5"
|
||||
serde = "1.0.152"
|
||||
serde_derive = "1.0.152"
|
||||
serde_json = "1.0.93"
|
||||
structopt = "0.2.18"
|
||||
vec3 = {path = "../vec3"}
|
||||
stl = {path = "../../../stl"}
|
||||
strum = { version = "0.24.1", features = ["derive"] }
|
||||
strum_macros = "0.24.3"
|
||||
thiserror = "1.0.38"
|
||||
tev_client = "0.5.2"
|
||||
#stl = {git = "https://git-private.z.xinu.tv/wathiede/stl"}
|
||||
image = "0.22.3"
|
||||
lazy_static = "1.1.0"
|
||||
log = "0.4.5"
|
||||
num_cpus = "1.8.0"
|
||||
rand = "0.8.3"
|
||||
serde = "1.0.79"
|
||||
serde_derive = "1.0.79"
|
||||
serde_json = "1.0.41"
|
||||
structopt = "0.2.10"
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = "0.4"
|
||||
pretty_assertions = "1.3.0"
|
||||
proptest = "1.1.0"
|
||||
criterion = "0.2"
|
||||
|
||||
[features]
|
||||
profile = ["cpuprofiler"]
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
use criterion::*;
|
||||
use renderer::{aabb::AABB, ray::Ray};
|
||||
|
||||
fn bench(c: &mut Criterion) {
|
||||
let bb = AABB::new([1., -1., -1.], [3., 1., 1.]);
|
||||
let r_hit = Ray::new([0., 0., 0.], [1., 0., 0.], 0.);
|
||||
let r_miss = Ray::new([0., 0., 0.], [-1., 0., 0.], 0.);
|
||||
let t_min = 0.001;
|
||||
let t_max = f32::MAX;
|
||||
|
||||
let mut group = c.benchmark_group("aabb");
|
||||
group.throughput(Throughput::Elements(1));
|
||||
group.bench_with_input(BenchmarkId::new("hit_naive", "r_hit"), &r_hit, |b, r| {
|
||||
b.iter(|| bb.hit_naive(*r, t_min, t_max))
|
||||
});
|
||||
group.bench_with_input(BenchmarkId::new("hit2", "r_hit"), &r_hit, |b, r| {
|
||||
b.iter(|| bb.hit2(*r, t_min, t_max))
|
||||
});
|
||||
//group.bench_with_input(BenchmarkId::new("hit_precompute", "r_hit"), &r_hit, |b, r| { b.iter(|| bb.hit_precompute(*r, t_min, t_max)) });
|
||||
group.bench_with_input(BenchmarkId::new("hit_fast", "r_hit"), &r_hit, |b, r| {
|
||||
b.iter(|| bb.hit_fast(*r, t_min, t_max))
|
||||
});
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
group.bench_with_input(BenchmarkId::new("hit_simd", "r_hit"), &r_hit, |b, r| {
|
||||
b.iter(|| bb.hit_simd(*r, t_min, t_max))
|
||||
});
|
||||
|
||||
group.bench_with_input(BenchmarkId::new("hit_naive", "r_miss"), &r_miss, |b, r| {
|
||||
b.iter(|| bb.hit_naive(*r, t_min, t_max))
|
||||
});
|
||||
group.bench_with_input(BenchmarkId::new("hit2", "r_miss"), &r_miss, |b, r| {
|
||||
b.iter(|| bb.hit2(*r, t_min, t_max))
|
||||
});
|
||||
//group.bench_with_input(BenchmarkId::new("hit_precompute", "r_miss"), &r_miss, |b, r| { b.iter(|| bb.hit_precompute(*r, t_min, t_max)) });
|
||||
group.bench_with_input(BenchmarkId::new("hit_fast", "r_miss"), &r_miss, |b, r| {
|
||||
b.iter(|| bb.hit_fast(*r, t_min, t_max))
|
||||
});
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
group.bench_with_input(BenchmarkId::new("hit_simd", "r_miss"), &r_miss, |b, r| {
|
||||
b.iter(|| bb.hit_simd(*r, t_min, t_max))
|
||||
});
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(benches, bench);
|
||||
criterion_main!(benches);
|
||||
@@ -1,9 +1,15 @@
|
||||
use criterion::*;
|
||||
#[macro_use]
|
||||
extern crate criterion;
|
||||
|
||||
use renderer::{
|
||||
hitable::Hit, material::Lambertian, ray::Ray, sphere::Sphere, texture::ConstantTexture,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use criterion::Criterion;
|
||||
use criterion::ParameterizedBenchmark;
|
||||
|
||||
use rtiow::hitable::Hit;
|
||||
use rtiow::material::Lambertian;
|
||||
use rtiow::ray::Ray;
|
||||
use rtiow::sphere::Sphere;
|
||||
use rtiow::texture::ConstantTexture;
|
||||
use rtiow::vec3::Vec3;
|
||||
|
||||
fn criterion_benchmark(c: &mut Criterion) {
|
||||
let sphere = Sphere::new(
|
||||
@@ -17,15 +23,14 @@ fn criterion_benchmark(c: &mut Criterion) {
|
||||
// Miss
|
||||
Ray::new([0., 0., -2.], [0., 0., -1.], 0.),
|
||||
];
|
||||
let mut group = c.benchmark_group("sphere");
|
||||
group.throughput(Throughput::Elements(1));
|
||||
group.bench_with_input(BenchmarkId::new("Sphere", "hit"), &rays[0], |b, r| {
|
||||
b.iter(|| sphere.hit(*r, 0., 1.))
|
||||
});
|
||||
group.bench_with_input(BenchmarkId::new("Sphere", "miss"), &rays[1], |b, r| {
|
||||
b.iter(|| sphere.hit(*r, 0., 1.))
|
||||
});
|
||||
group.finish()
|
||||
c.bench(
|
||||
"sphere",
|
||||
ParameterizedBenchmark::new(
|
||||
"Sphere",
|
||||
move |b, r| b.iter(|| sphere.hit(*r, 0., 1.)),
|
||||
rays,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
criterion_group!(benches, criterion_benchmark);
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
imports_granularity = "Crate"
|
||||
format_code_in_doc_comments = true
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::fmt;
|
||||
|
||||
use crate::{ray::Ray, vec3::Vec3};
|
||||
use crate::ray::Ray;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Default, Copy, Clone, PartialEq)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AABB {
|
||||
bounds: [Vec3; 2],
|
||||
}
|
||||
@@ -29,65 +30,15 @@ fn max(x: f32, y: f32) -> f32 {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for AABB {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"AABB: <{} - {}> Vol: {} Area: {}",
|
||||
self.bounds[0],
|
||||
self.bounds[1],
|
||||
self.volume(),
|
||||
self.area()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl AABB {
|
||||
// Create AABB with min = f32::MAX and max = -f32::MAX. It is expected the caller will use grow to create
|
||||
// a vaild AABB.
|
||||
pub fn infinite() -> AABB {
|
||||
AABB {
|
||||
bounds: [Vec3::from(f32::MAX), Vec3::from(f32::MIN)],
|
||||
}
|
||||
}
|
||||
pub fn new<V: Into<Vec3>>(min: V, max: V) -> AABB {
|
||||
let min: Vec3 = min.into();
|
||||
let max: Vec3 = max.into();
|
||||
assert!(min.x <= max.x);
|
||||
assert!(min.y <= max.y);
|
||||
assert!(min.z <= max.z);
|
||||
pub fn new(min: Vec3, max: Vec3) -> AABB {
|
||||
AABB { bounds: [min, max] }
|
||||
}
|
||||
|
||||
pub fn area(&self) -> f32 {
|
||||
if self.max().x == f32::MIN || self.min().x == f32::MAX {
|
||||
return 0.;
|
||||
}
|
||||
let e = self.max() - self.min();
|
||||
let v = e.x * e.y + e.y * e.z + e.z * e.x;
|
||||
if v.is_finite() {
|
||||
v
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}
|
||||
pub fn volume(&self) -> f32 {
|
||||
if self.max().x == f32::MIN || self.min().x == f32::MAX {
|
||||
return 0.;
|
||||
}
|
||||
let v = (self.min().x - self.max().x).abs()
|
||||
(self.min().x - self.max().x).abs()
|
||||
* (self.min().y - self.max().y).abs()
|
||||
* (self.min().z - self.max().z).abs();
|
||||
if v.is_finite() {
|
||||
v
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}
|
||||
|
||||
pub fn grow(&mut self, v: Vec3) {
|
||||
self.bounds[0] = vec3::min(self.bounds[0], v);
|
||||
self.bounds[1] = vec3::max(self.bounds[1], v);
|
||||
* (self.min().z - self.max().z).abs()
|
||||
}
|
||||
|
||||
pub fn longest_axis(&self) -> usize {
|
||||
@@ -111,39 +62,11 @@ impl AABB {
|
||||
pub fn min(&self) -> Vec3 {
|
||||
self.bounds[0]
|
||||
}
|
||||
|
||||
pub fn max(&self) -> Vec3 {
|
||||
self.bounds[1]
|
||||
}
|
||||
|
||||
// TODO(wathiede): implement branchless https://tavianator.com/cgit/dimension.git/tree/libdimension/bvh/bvh.c#n194
|
||||
|
||||
pub fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> bool {
|
||||
self.hit_simd(r, t_min, t_max).is_some()
|
||||
}
|
||||
|
||||
pub fn hit_distance(&self, r: Ray, t_min: f32, t_max: f32) -> Option<f32> {
|
||||
self.hit_simd(r, t_min, t_max)
|
||||
}
|
||||
|
||||
pub fn hit_naive(&self, r: Ray, t_min: f32, t_max: f32) -> Option<f32> {
|
||||
let mut t_min = t_min;
|
||||
let mut t_max = t_max;
|
||||
for axis in 0..3 {
|
||||
let t0 = ((self.min()[axis] - r.origin[axis]) * r.inv_direction[axis])
|
||||
.min((self.max()[axis] - r.origin[axis]) * r.inv_direction[axis]);
|
||||
let t1 = ((self.min()[axis] - r.origin[axis]) * r.inv_direction[axis])
|
||||
.max((self.max()[axis] - r.origin[axis]) * r.inv_direction[axis]);
|
||||
t_min = t0.max(t_min);
|
||||
t_max = t1.min(t_max);
|
||||
if t_max <= t_min {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(t_min)
|
||||
}
|
||||
|
||||
pub fn hit2(&self, r: Ray, t_min: f32, t_max: f32) -> Option<f32> {
|
||||
pub fn hit2(&self, r: Ray, t_min: f32, t_max: f32) -> bool {
|
||||
let mut t_min = t_min;
|
||||
let mut t_max = t_max;
|
||||
for axis in 0..3 {
|
||||
@@ -159,13 +82,13 @@ impl AABB {
|
||||
t_min = max(t0, t_min);
|
||||
t_max = min(t1, t_max);
|
||||
if t_max <= t_min {
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Some(t_min)
|
||||
true
|
||||
}
|
||||
|
||||
pub fn hit_precompute(&self, r: Ray, t0: f32, t1: f32) -> Option<f32> {
|
||||
pub fn hit_precompute(&self, r: Ray, t0: f32, t1: f32) -> bool {
|
||||
// TODO(wathiede): this has bugs.
|
||||
let mut t_min = (self.bounds[r.sign[0]].x - r.origin.x) * r.inv_direction.x;
|
||||
let mut t_max = (self.bounds[1 - r.sign[0]].x - r.origin.x) * r.inv_direction.x;
|
||||
@@ -173,7 +96,7 @@ impl AABB {
|
||||
let t_y_max = (self.bounds[1 - r.sign[0]].y - r.origin.y) * r.inv_direction.y;
|
||||
|
||||
if t_min > t_y_max || t_y_min > t_max {
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
|
||||
if t_y_min > t_min {
|
||||
@@ -186,7 +109,7 @@ impl AABB {
|
||||
let t_z_min = (self.bounds[r.sign[2]].z - r.origin.z) * r.inv_direction.z;
|
||||
let t_z_max = (self.bounds[1 - r.sign[2]].z - r.origin.z) * r.inv_direction.z;
|
||||
if t_min > t_z_max || t_z_min > t_max {
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
if t_z_min > t_min {
|
||||
t_min = t_z_min;
|
||||
@@ -194,42 +117,27 @@ impl AABB {
|
||||
if t_z_max < t_max {
|
||||
t_max = t_z_max;
|
||||
}
|
||||
if t_min < t1 && t_max > t0 {
|
||||
Some(t_min)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
t_min < t1 && t_max > t0
|
||||
}
|
||||
|
||||
pub fn hit_simd(&self, r: Ray, t_min: f32, t_max: f32) -> Option<f32> {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
unsafe {
|
||||
use std::arch::x86_64::*;
|
||||
let o4 = _mm_set_ps(0., r.origin.z, r.origin.y, r.origin.x);
|
||||
let d4 = _mm_set_ps(0., r.inv_direction.z, r.inv_direction.y, r.inv_direction.x);
|
||||
let bmin4 = _mm_set_ps(0., self.min().z, self.min().y, self.min().x);
|
||||
let bmax4 = _mm_set_ps(0., self.max().z, self.max().y, self.max().x);
|
||||
let mask4 = _mm_cmpeq_ps(_mm_setzero_ps(), _mm_set_ps(1., 0., 0., 0.));
|
||||
let t1 = _mm_mul_ps(_mm_sub_ps(_mm_and_ps(bmin4, mask4), o4), d4);
|
||||
let t2 = _mm_mul_ps(_mm_sub_ps(_mm_and_ps(bmax4, mask4), o4), d4);
|
||||
let vmax4 = _mm_max_ps(t1, t2);
|
||||
let vmin4 = _mm_min_ps(t1, t2);
|
||||
let vmax4: (f32, f32, f32, f32) = std::mem::transmute(vmax4);
|
||||
let vmin4: (f32, f32, f32, f32) = std::mem::transmute(vmin4);
|
||||
let tmax = min(min(vmax4.0, min(vmax4.1, vmax4.2)), t_max);
|
||||
let tmin = max(max(vmin4.0, max(vmin4.1, vmin4.2)), t_min);
|
||||
if tmin <= tmax {
|
||||
Some(tmin)
|
||||
} else {
|
||||
None
|
||||
pub fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> bool {
|
||||
let mut t_min = t_min;
|
||||
let mut t_max = t_max;
|
||||
for axis in 0..3 {
|
||||
let t0 = ((self.min()[axis] - r.origin[axis]) * r.inv_direction[axis])
|
||||
.min((self.max()[axis] - r.origin[axis]) * r.inv_direction[axis]);
|
||||
let t1 = ((self.min()[axis] - r.origin[axis]) * r.inv_direction[axis])
|
||||
.max((self.max()[axis] - r.origin[axis]) * r.inv_direction[axis]);
|
||||
t_min = t0.max(t_min);
|
||||
t_max = t1.min(t_max);
|
||||
if t_max <= t_min {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
// TODO(wathiede): add NEON implementation.
|
||||
self.hit2(r, t_min, t_max)
|
||||
true
|
||||
}
|
||||
|
||||
pub fn hit_fast(&self, r: Ray, _t_min: f32, _t_max: f32) -> Option<f32> {
|
||||
pub fn hit_fast(&self, r: Ray, _t_min: f32, _t_max: f32) -> bool {
|
||||
let b = self;
|
||||
let mut t1 = (b.min()[0] - r.origin[0]) * 1. / r.direction[0];
|
||||
let mut t2 = (b.max()[0] - r.origin[0]) * 1. / r.direction[0];
|
||||
@@ -245,11 +153,7 @@ impl AABB {
|
||||
tmax = tmax.min(t1.max(t2));
|
||||
}
|
||||
|
||||
if tmax > tmin.max(0.0) {
|
||||
Some(tmin)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
tmax > tmin.max(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,112 +170,3 @@ pub fn surrounding_box(box0: &AABB, box1: &AABB) -> AABB {
|
||||
);
|
||||
AABB::new(min, max)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn infinite() {
|
||||
let bb = AABB::infinite();
|
||||
assert_eq!(bb.area(), 0.);
|
||||
assert_eq!(bb.volume(), 0.);
|
||||
}
|
||||
|
||||
macro_rules! hit_test {
|
||||
($($name:ident,)*) => {
|
||||
$(
|
||||
mod $name {
|
||||
use super::*;
|
||||
const T_MIN: f32 = 0.001;
|
||||
const T_MAX: f32 = f32::MAX;
|
||||
|
||||
fn test_bb() -> AABB {
|
||||
AABB::new([-1., -1., -1.], [1., 1., 1.])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_front() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([-2., 0., 0.], [1., 0., 0.], 0.5);
|
||||
assert!(bb.$name(r, T_MIN, T_MAX).is_some());
|
||||
}
|
||||
#[test]
|
||||
fn hit_back() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([2., 0., 0.], [-1., 0., 0.], 0.5);
|
||||
assert!(bb.$name(r, T_MIN, T_MAX).is_some());
|
||||
}
|
||||
#[test]
|
||||
fn hit_top() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([0., 2., 0.], [0., -1., 0.], 0.5);
|
||||
assert!(bb.$name(r, T_MIN, T_MAX).is_some());
|
||||
}
|
||||
#[test]
|
||||
fn hit_bottom() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([0., -2., 0.], [0., 1., 0.], 0.5);
|
||||
assert!(bb.$name(r, T_MIN, T_MAX).is_some());
|
||||
}
|
||||
#[test]
|
||||
fn hit_left() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([0., 0., -2.], [0., 0., 1.], 0.5);
|
||||
assert!(bb.$name(r, T_MIN, T_MAX).is_some());
|
||||
}
|
||||
#[test]
|
||||
fn hit_right() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([0., 0., 2.], [0., 0., -1.], 0.5);
|
||||
assert!(bb.$name(r, T_MIN, T_MAX).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn miss_front() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([0., 1.1, -1.1], [0., -1., 0.], 0.5);
|
||||
assert_eq!(bb.$name(r, T_MIN, T_MAX), None);
|
||||
}
|
||||
#[test]
|
||||
fn miss_back() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([0., 1.1, 1.1], [0., -1., 0.], 0.5);
|
||||
assert_eq!(bb.$name(r, T_MIN, T_MAX), None);
|
||||
}
|
||||
#[test]
|
||||
fn miss_top() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([0., 1.1, -1.1], [0., 0., 1.], 0.5);
|
||||
assert_eq!(bb.$name(r, T_MIN, T_MAX), None);
|
||||
}
|
||||
#[test]
|
||||
fn miss_bottom() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([0., -1.1, -1.1], [0., 0., 1.], 0.5);
|
||||
assert_eq!(bb.$name(r, T_MIN, T_MAX), None);
|
||||
}
|
||||
#[test]
|
||||
fn miss_left() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([-1.1, 0., -1.1], [0., 0., 1.], 0.5);
|
||||
assert_eq!(bb.$name(r, T_MIN, T_MAX), None);
|
||||
}
|
||||
#[test]
|
||||
fn miss_right() {
|
||||
let bb = test_bb();
|
||||
let r = Ray::new([1.1, 0., -1.1], [0., 0., 1.], 0.5);
|
||||
assert_eq!(bb.$name(r, T_MIN, T_MAX), None);
|
||||
}
|
||||
}
|
||||
)*
|
||||
}
|
||||
}
|
||||
|
||||
hit_test! {
|
||||
hit_naive,
|
||||
hit_simd,
|
||||
hit_fast,
|
||||
hit2,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
use std::{self, fmt, time::Instant};
|
||||
use std;
|
||||
use std::fmt;
|
||||
use std::time::Instant;
|
||||
|
||||
use log::info;
|
||||
use rand::{self, Rng};
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::{
|
||||
aabb::{surrounding_box, AABB},
|
||||
hitable::{Hit, HitRecord},
|
||||
ray::Ray,
|
||||
};
|
||||
use crate::aabb::surrounding_box;
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::ray::Ray;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum BVHNode {
|
||||
Leaf(Box<dyn Hit>),
|
||||
Branch {
|
||||
@@ -179,7 +181,6 @@ impl Hit for BVHNode {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BVH {
|
||||
root: BVHNode,
|
||||
}
|
||||
@@ -231,13 +232,12 @@ impl Hit for BVH {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
material::{Lambertian, Metal},
|
||||
sphere::Sphere,
|
||||
texture::ConstantTexture,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::aabb::AABB;
|
||||
use crate::material::Lambertian;
|
||||
use crate::material::Metal;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -1,711 +0,0 @@
|
||||
/// Implementation based on blog post @
|
||||
/// https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/
|
||||
use std::f32::EPSILON;
|
||||
use std::fmt;
|
||||
|
||||
use log::info;
|
||||
use stl::STL;
|
||||
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
material::Material,
|
||||
ray::Ray,
|
||||
vec3::{cross, dot, Vec3},
|
||||
};
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct BVHNode {
|
||||
aabb: AABB,
|
||||
// When tri_count==0, left_first holds the left child's index in bvh_nodes. When >0 left_first
|
||||
// holds the index for the first triangle in triangles.
|
||||
left_first: u32,
|
||||
tri_count: u32,
|
||||
}
|
||||
|
||||
impl BVHNode {
|
||||
fn is_leaf(&self) -> bool {
|
||||
self.tri_count > 0
|
||||
}
|
||||
|
||||
fn cost(&self) -> f32 {
|
||||
let area = self.aabb.area();
|
||||
self.tri_count as f32 * area
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct Triangle {
|
||||
centroid: Vec3,
|
||||
verts: [Vec3; 3],
|
||||
}
|
||||
impl fmt::Debug for Triangle {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"Tri: <{}, {}, {}> @ {}",
|
||||
self.verts[0], self.verts[1], self.verts[2], self.centroid
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BVHTriangles<M>
|
||||
where
|
||||
M: Material,
|
||||
{
|
||||
pub triangles: Vec<Triangle>,
|
||||
triangle_index: Vec<usize>,
|
||||
material: M,
|
||||
bvh_nodes: Vec<BVHNode>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Bin {
|
||||
bounds: AABB,
|
||||
tri_count: usize,
|
||||
}
|
||||
|
||||
impl<M> fmt::Debug for BVHTriangles<M>
|
||||
where
|
||||
M: Material,
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{} triangles", self.triangles.len())?;
|
||||
if f.alternate() {
|
||||
writeln!(f)?;
|
||||
}
|
||||
for (i, t) in self.triangles.iter().enumerate() {
|
||||
if f.alternate() {
|
||||
write!(f, "\t")?;
|
||||
}
|
||||
write!(f, "{i:>3} {:?} ", t)?;
|
||||
if f.alternate() {
|
||||
writeln!(f)?;
|
||||
}
|
||||
}
|
||||
if f.alternate() {
|
||||
writeln!(f)?;
|
||||
}
|
||||
for (i, n) in self.bvh_nodes.iter().enumerate() {
|
||||
write!(f, "N[{i}] {n:?}")?;
|
||||
if f.alternate() {
|
||||
writeln!(f)?;
|
||||
}
|
||||
let n = &self.bvh_nodes[i];
|
||||
if n.is_leaf() {
|
||||
for t_idx in n.left_first..(n.left_first + n.tri_count) {
|
||||
if f.alternate() {
|
||||
write!(f, "\t")?;
|
||||
}
|
||||
write!(f, "{:?} ", self.triangles[t_idx as usize])?;
|
||||
if f.alternate() {
|
||||
writeln!(f)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SplitCost {
|
||||
pos: f32,
|
||||
axis: usize,
|
||||
cost: f32,
|
||||
}
|
||||
|
||||
const ROOT_NODE_IDX: usize = 0;
|
||||
impl<M> BVHTriangles<M>
|
||||
where
|
||||
M: Material,
|
||||
{
|
||||
pub fn new(stl: &STL, material: M, scale_factor: f32) -> BVHTriangles<M> {
|
||||
let now = std::time::Instant::now();
|
||||
|
||||
assert_eq!(std::mem::size_of::<BVHNode>(), 32);
|
||||
let div3 = 1. / 3.;
|
||||
let triangles: Vec<_> = stl
|
||||
.triangles
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let v0 = t.verts[0] * scale_factor;
|
||||
let v1 = t.verts[1] * scale_factor;
|
||||
let v2 = t.verts[2] * scale_factor;
|
||||
let centroid = (v0 + v1 + v2) * div3;
|
||||
Triangle {
|
||||
centroid,
|
||||
verts: [v0, v1, v2],
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let triangle_index = (0..triangles.len()).collect();
|
||||
|
||||
let n = 2 * triangles.len() - 2;
|
||||
let bvh_nodes = Vec::with_capacity(n);
|
||||
let mut bvh = BVHTriangles {
|
||||
triangles,
|
||||
triangle_index,
|
||||
bvh_nodes,
|
||||
material,
|
||||
};
|
||||
bvh.build_bvh();
|
||||
info!(
|
||||
"BVHTriangles build time {:0.3}s",
|
||||
now.elapsed().as_secs_f32()
|
||||
);
|
||||
struct Stats {
|
||||
nodes: usize,
|
||||
leafs: usize,
|
||||
min_tris: u32,
|
||||
max_tris: u32,
|
||||
}
|
||||
impl Default for Stats {
|
||||
fn default() -> Self {
|
||||
Stats {
|
||||
nodes: 0,
|
||||
leafs: 0,
|
||||
min_tris: u32::MAX,
|
||||
max_tris: u32::MIN,
|
||||
}
|
||||
}
|
||||
}
|
||||
let stats = bvh.bvh_nodes.iter().fold(Stats::default(), |mut stats, n| {
|
||||
stats.nodes += 1;
|
||||
if n.is_leaf() {
|
||||
stats.leafs += 1;
|
||||
stats.min_tris = n.tri_count.min(stats.min_tris);
|
||||
stats.max_tris = n.tri_count.max(stats.max_tris);
|
||||
}
|
||||
stats
|
||||
});
|
||||
info!("BVHTriangles build stats:");
|
||||
info!(" Nodes: {}", stats.nodes);
|
||||
info!(" Leaves: {}", stats.leafs);
|
||||
info!(" Tris: {}", bvh.triangles.len());
|
||||
info!(" Min Tri: {}", stats.min_tris);
|
||||
info!(" Max Tri: {}", stats.max_tris);
|
||||
info!(" Avg Tri: {}", bvh.triangles.len() / stats.leafs);
|
||||
info!(" Predict: {}", bvh.bvh_nodes.capacity());
|
||||
info!(" Actual: {}", bvh.bvh_nodes.len());
|
||||
info!(
|
||||
" Savings: {} bytes",
|
||||
(bvh.bvh_nodes.capacity() - bvh.bvh_nodes.len()) * std::mem::size_of::<BVHNode>()
|
||||
);
|
||||
bvh.bvh_nodes.shrink_to_fit();
|
||||
//dbg!(&bvh);
|
||||
bvh
|
||||
}
|
||||
|
||||
fn build_bvh(&mut self) {
|
||||
// assign all triangles to root node
|
||||
let root = BVHNode {
|
||||
aabb: AABB::default(),
|
||||
left_first: 0,
|
||||
tri_count: self.triangles.len() as u32,
|
||||
};
|
||||
self.bvh_nodes.push(root);
|
||||
self.update_node_bounds(ROOT_NODE_IDX);
|
||||
// subdivide recursively
|
||||
self.subdivide(ROOT_NODE_IDX);
|
||||
}
|
||||
fn update_node_bounds(&mut self, node_idx: usize) {
|
||||
let node = &mut self.bvh_nodes[node_idx];
|
||||
let mut aabb_min: Vec3 = f32::MAX.into();
|
||||
let mut aabb_max: Vec3 = f32::MIN.into();
|
||||
for i in node.left_first..(node.left_first + node.tri_count) {
|
||||
let leaf_tri_idx = self.triangle_index[i as usize];
|
||||
let leaf_tri = &self.triangles[leaf_tri_idx];
|
||||
aabb_min = vec3::min(aabb_min, leaf_tri.verts[0]);
|
||||
aabb_min = vec3::min(aabb_min, leaf_tri.verts[1]);
|
||||
aabb_min = vec3::min(aabb_min, leaf_tri.verts[2]);
|
||||
aabb_max = vec3::max(aabb_max, leaf_tri.verts[0]);
|
||||
aabb_max = vec3::max(aabb_max, leaf_tri.verts[1]);
|
||||
aabb_max = vec3::max(aabb_max, leaf_tri.verts[2]);
|
||||
}
|
||||
node.aabb = AABB::new(aabb_min, aabb_max);
|
||||
}
|
||||
|
||||
fn find_best_split_plane(&self, node: &BVHNode) -> SplitCost {
|
||||
let mut best = SplitCost {
|
||||
pos: 0.,
|
||||
cost: f32::MAX,
|
||||
axis: usize::MAX,
|
||||
};
|
||||
|
||||
for axis in 0..3 {
|
||||
let mut bounds_min = f32::MAX;
|
||||
let mut bounds_max = f32::MIN;
|
||||
|
||||
for i in 0..node.tri_count {
|
||||
let triangle = &self.triangles[self.triangle_index[(node.left_first + i) as usize]];
|
||||
bounds_min = bounds_min.min(triangle.centroid[axis]);
|
||||
bounds_max = bounds_max.max(triangle.centroid[axis]);
|
||||
}
|
||||
|
||||
if bounds_min == bounds_max {
|
||||
continue;
|
||||
}
|
||||
|
||||
const NUM_BINS: usize = 8;
|
||||
let mut bins: Vec<_> = (0..NUM_BINS)
|
||||
.map(|_| Bin {
|
||||
bounds: AABB::infinite(),
|
||||
tri_count: 0,
|
||||
})
|
||||
.collect();
|
||||
let scale = bins.len() as f32 / (bounds_max - bounds_min);
|
||||
// populate the bins
|
||||
for i in 0..node.tri_count {
|
||||
let triangle = &self.triangles[self.triangle_index[(node.left_first + i) as usize]];
|
||||
let bin_idx = (triangle.centroid[axis] - bounds_min) * scale;
|
||||
let bin_idx = (bins.len() - 1).min(bin_idx as usize);
|
||||
|
||||
bins[bin_idx].tri_count += 1;
|
||||
bins[bin_idx].bounds.grow(triangle.verts[0]);
|
||||
bins[bin_idx].bounds.grow(triangle.verts[1]);
|
||||
bins[bin_idx].bounds.grow(triangle.verts[2]);
|
||||
}
|
||||
|
||||
// gather data for the 7 planes between the 8 bins
|
||||
let mut left_area: Vec<_> = (0..bins.len() - 1).map(|_| 0.).collect();
|
||||
let mut right_area: Vec<_> = (0..bins.len() - 1).map(|_| 0.).collect();
|
||||
let mut left_count: Vec<_> = (0..bins.len() - 1).map(|_| 0).collect();
|
||||
let mut right_count: Vec<_> = (0..bins.len() - 1).map(|_| 0).collect();
|
||||
let mut left_box = AABB::infinite();
|
||||
let mut right_box = AABB::infinite();
|
||||
let mut left_sum = 0;
|
||||
let mut right_sum = 0;
|
||||
for i in 0..(bins.len() - 1) {
|
||||
left_sum += bins[i].tri_count;
|
||||
left_count[i] = left_sum;
|
||||
left_box.grow(bins[i].bounds.min());
|
||||
left_box.grow(bins[i].bounds.max());
|
||||
left_area[i] = left_box.area();
|
||||
|
||||
right_sum += bins[bins.len() - 1 - i].tri_count;
|
||||
right_count[bins.len() - 2 - i] = right_sum;
|
||||
right_box.grow(bins[bins.len() - 1 - i].bounds.min());
|
||||
right_box.grow(bins[bins.len() - 1 - i].bounds.max());
|
||||
right_area[bins.len() - 2 - i] = right_box.area();
|
||||
}
|
||||
|
||||
let scale = (bounds_max - bounds_min) / bins.len() as f32;
|
||||
// calculate SAH cost for the 7 planes
|
||||
for i in 0..(bins.len() - 1) {
|
||||
let plane_cost =
|
||||
left_count[i] as f32 * left_area[i] + right_count[i] as f32 * right_area[i];
|
||||
if plane_cost < best.cost {
|
||||
best.axis = axis;
|
||||
best.pos = bounds_min + scale * (i as f32 + 1.);
|
||||
best.cost = plane_cost;
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
fn subdivide(&mut self, idx: usize) {
|
||||
let (left_first, tri_count, left_count, i) = {
|
||||
let node = &self.bvh_nodes[idx];
|
||||
let split = self.find_best_split_plane(&node);
|
||||
let no_split_cost = node.cost();
|
||||
// Stop subdividing if it isn't getting any better.
|
||||
if split.cost >= no_split_cost {
|
||||
return;
|
||||
}
|
||||
|
||||
// Split the group in two halves.
|
||||
let mut i = node.left_first as isize;
|
||||
let mut j = i + node.tri_count as isize - 1;
|
||||
while i <= j {
|
||||
if self.triangles[self.triangle_index[i as usize]].centroid[split.axis] < split.pos
|
||||
{
|
||||
i += 1;
|
||||
} else {
|
||||
self.triangles.swap(
|
||||
self.triangle_index[i as usize],
|
||||
self.triangle_index[j as usize],
|
||||
);
|
||||
j -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Create child nodes for each half.
|
||||
let left_count = i as u32 - node.left_first;
|
||||
if left_count == 0 || left_count == node.tri_count {
|
||||
return;
|
||||
}
|
||||
(node.left_first, node.tri_count, left_count, i)
|
||||
};
|
||||
|
||||
// create child nodes
|
||||
let left_child_idx = self.bvh_nodes.len() as u32;
|
||||
let right_child_idx = left_child_idx + 1 as u32;
|
||||
let left = BVHNode {
|
||||
aabb: AABB::default(),
|
||||
left_first,
|
||||
tri_count: left_count as u32,
|
||||
};
|
||||
let right = BVHNode {
|
||||
aabb: AABB::default(),
|
||||
left_first: i as u32,
|
||||
tri_count: (tri_count - left_count) as u32,
|
||||
};
|
||||
self.bvh_nodes.push(left);
|
||||
self.bvh_nodes.push(right);
|
||||
let node = &mut self.bvh_nodes[idx];
|
||||
node.left_first = left_child_idx;
|
||||
node.tri_count = 0;
|
||||
|
||||
// Recurse
|
||||
self.update_node_bounds(left_child_idx as usize);
|
||||
self.subdivide(left_child_idx as usize);
|
||||
self.update_node_bounds(right_child_idx as usize);
|
||||
self.subdivide(right_child_idx as usize);
|
||||
}
|
||||
|
||||
fn intersect_bvh(&self, r: Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
|
||||
let mut node = &self.bvh_nodes[ROOT_NODE_IDX];
|
||||
let mut stack = Vec::with_capacity(2);
|
||||
let mut nearest = None;
|
||||
loop {
|
||||
if node.is_leaf() {
|
||||
let canditate = (node.left_first..(node.left_first + node.tri_count))
|
||||
// Map from idx to Triangle
|
||||
.map(|idx| &self.triangles[self.triangle_index[idx as usize]])
|
||||
// Try to hit all triangles for this node, filtering out misses.
|
||||
.filter_map(|tri| intersect_tri(r, &tri))
|
||||
// Find the nearest hit (if any).
|
||||
.min_by(|a, b| a.t.partial_cmp(&b.t).unwrap());
|
||||
|
||||
// merge candidate with nearest.
|
||||
nearest = match (&canditate, &nearest) {
|
||||
(Some(_), None) => canditate,
|
||||
(None, Some(_)) => nearest,
|
||||
(Some(c), Some(n)) => {
|
||||
//info!("merging {c:#?} and {n:#?}");
|
||||
if c.t < n.t {
|
||||
canditate
|
||||
} else {
|
||||
nearest
|
||||
}
|
||||
}
|
||||
(None, None) => None,
|
||||
};
|
||||
if stack.is_empty() {
|
||||
break;
|
||||
}
|
||||
node = stack.pop().unwrap();
|
||||
continue;
|
||||
}
|
||||
|
||||
let child1 = &self.bvh_nodes[node.left_first as usize];
|
||||
let child2 = &self.bvh_nodes[node.left_first as usize + 1];
|
||||
let dist1 = child1.aabb.hit_distance(r, t_min, t_max);
|
||||
let dist2 = child2.aabb.hit_distance(r, t_min, t_max);
|
||||
// Swap c1/c2 & d1/d2 based on d1/d2.
|
||||
let (child1, child2, dist1, dist2) = match (dist1, dist2) {
|
||||
(Some(d1), Some(d2)) if d1 > d2 => (child2, child1, dist2, dist1),
|
||||
(None, Some(_)) => (child2, child1, dist2, dist1),
|
||||
_ => (child1, child2, dist1, dist2),
|
||||
};
|
||||
|
||||
// dist1/child1 should now be the nearest hit.
|
||||
|
||||
// If we missed dist1/child1, then we implicitly missed dist2/child2, so pop a child
|
||||
// from the stack or exit the function.
|
||||
if dist1.is_none() {
|
||||
if stack.is_empty() {
|
||||
break;
|
||||
}
|
||||
node = stack.pop().unwrap();
|
||||
} else {
|
||||
// We hit child1, so process it next.
|
||||
node = child1;
|
||||
// If we also hit child2 save it on the stack so we can process it later.
|
||||
if dist2.is_some() {
|
||||
stack.push(child2);
|
||||
}
|
||||
}
|
||||
}
|
||||
nearest
|
||||
.and_then(|rtr: RayTriangleResult| Some(rtr.hit_record_with_material(&self.material)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Based on https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection.html
|
||||
fn intersect_tri(r: Ray, tri: &Triangle) -> Option<RayTriangleResult> {
|
||||
// #ifdef MOLLER_TRUMBORE
|
||||
// Vec3f v0v1 = v1 - v0;
|
||||
// Vec3f v0v2 = v2 - v0;
|
||||
// Vec3f pvec = dir.crossProduct(v0v2);
|
||||
// float det = v0v1.dotProduct(pvec);
|
||||
// #ifdef CULLING
|
||||
// // if the determinant is negative, the triangle is 'back facing'
|
||||
// // if the determinant is close to 0, the ray misses the triangle
|
||||
// if (det < kEpsilon) return false;
|
||||
// #else
|
||||
// // ray and triangle are parallel if det is close to 0
|
||||
// if (fabs(det) < kEpsilon) return false;
|
||||
// #endif
|
||||
// float invDet = 1 / det;
|
||||
//
|
||||
// Vec3f tvec = orig - v0;
|
||||
// u = tvec.dotProduct(pvec) * invDet;
|
||||
// if (u < 0 || u > 1) return false;
|
||||
//
|
||||
// Vec3f qvec = tvec.crossProduct(v0v1);
|
||||
// v = dir.dotProduct(qvec) * invDet;
|
||||
// if (v < 0 || u + v > 1) return false;
|
||||
//
|
||||
// t = v0v2.dotProduct(qvec) * invDet;
|
||||
//
|
||||
let v0 = tri.verts[0];
|
||||
let v1 = tri.verts[1];
|
||||
let v2 = tri.verts[2];
|
||||
|
||||
let v0v1 = v1 - v0;
|
||||
let v0v2 = v2 - v0;
|
||||
let p = cross(r.direction, v0v2);
|
||||
let det = dot(v0v1, p);
|
||||
if det.abs() < EPSILON {
|
||||
return None;
|
||||
}
|
||||
|
||||
let inv_det = 1. / det;
|
||||
|
||||
let t = r.origin - v0;
|
||||
let u = dot(t, p) * inv_det;
|
||||
if u < 0. || u > 1. {
|
||||
return None;
|
||||
}
|
||||
|
||||
let q = cross(t, v0v1);
|
||||
let v = dot(r.direction, q) * inv_det;
|
||||
if v < 0. || u + v > 1. {
|
||||
return None;
|
||||
}
|
||||
let t = dot(v0v2, q) * inv_det;
|
||||
|
||||
if t > EPSILON {
|
||||
return Some(RayTriangleResult {
|
||||
t,
|
||||
p: r.point_at_parameter(t),
|
||||
tri: tri.clone(),
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl<M> Hit for BVHTriangles<M>
|
||||
where
|
||||
M: Material,
|
||||
{
|
||||
fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
|
||||
self.intersect_bvh(r, t_min, t_max)
|
||||
}
|
||||
|
||||
fn bounding_box(&self, _t_min: f32, _t_max: f32) -> Option<AABB> {
|
||||
Some(self.bvh_nodes[ROOT_NODE_IDX].aabb)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RayTriangleResult {
|
||||
t: f32,
|
||||
p: Vec3,
|
||||
tri: Triangle,
|
||||
}
|
||||
|
||||
impl RayTriangleResult {
|
||||
fn hit_record_with_material<'m>(self, material: &'m dyn Material) -> HitRecord<'m> {
|
||||
// We don't support UV (yet?).
|
||||
let uv = (0.5, 0.5);
|
||||
let v0 = self.tri.verts[0];
|
||||
let v1 = self.tri.verts[1];
|
||||
let v2 = self.tri.verts[2];
|
||||
|
||||
let v0v1 = v1 - v0;
|
||||
let v0v2 = v2 - v0;
|
||||
let normal = cross(v0v1, v0v2).unit_vector();
|
||||
//println!("hit triangle {tri:?}");
|
||||
HitRecord {
|
||||
t: self.t,
|
||||
uv,
|
||||
p: self.p,
|
||||
normal,
|
||||
material,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
bvh_triangles::BVHTriangles,
|
||||
cuboid::Cuboid,
|
||||
hitable::Hit,
|
||||
material::{Dielectric, Lambertian},
|
||||
ray::Ray,
|
||||
texture::ConstantTexture,
|
||||
};
|
||||
use pretty_assertions::assert_eq;
|
||||
use proptest::prelude::*;
|
||||
use std::{
|
||||
io::{BufReader, Cursor},
|
||||
sync::Arc,
|
||||
};
|
||||
use stl::STL;
|
||||
|
||||
#[test]
|
||||
fn compare_cuboid() {
|
||||
let c = Cuboid::new(
|
||||
[0., 0., 0.].into(),
|
||||
[20., 20., 20.].into(),
|
||||
Arc::new(Dielectric::new(1.5)),
|
||||
);
|
||||
let stl_cube = STL::parse(
|
||||
BufReader::new(Cursor::new(include_bytes!("../stls/cube.stl"))),
|
||||
false,
|
||||
)
|
||||
.expect("failed to parse cube");
|
||||
|
||||
let s = BVHTriangles::new(
|
||||
&stl_cube,
|
||||
Dielectric::new(1.5),
|
||||
//Metal::new(Vec3::new(0.8, 0.8, 0.8), 0.2),
|
||||
//Lambertian::new(ConstantTexture::new(Vec3::new(1.0, 0.2, 0.2))),
|
||||
);
|
||||
//dbg!(&s);
|
||||
let mut rays: Vec<_> = (1..20)
|
||||
.flat_map(|y| {
|
||||
(1..20).flat_map(move |x| {
|
||||
let x = x as f32;
|
||||
let y = y as f32;
|
||||
vec![
|
||||
// Outward in angle
|
||||
Ray::new([-1., x, y], [1., 0., 0.], 0.),
|
||||
Ray::new([21., x, y], [-1., 0., 0.], 0.),
|
||||
Ray::new([x, -1., y], [0., 1., 0.], 0.),
|
||||
Ray::new([x, 21., y], [0., -1., 0.], 0.),
|
||||
Ray::new([x, y, -1.], [0., 0., 1.], 0.),
|
||||
Ray::new([x, y, 21.], [0., 0., -1.], 0.),
|
||||
// Inward out (
|
||||
Ray::new([x, y, 10.], [1., 0., 0.], 0.),
|
||||
Ray::new([x, y, 10.], [-1., 0., 0.], 0.),
|
||||
Ray::new([x, 10., y], [1., 0., 0.], 0.),
|
||||
Ray::new([x, 10., y], [-1., 0., 0.], 0.),
|
||||
Ray::new([10., x, y], [1., 0., 0.], 0.),
|
||||
Ray::new([10., x, y], [-1., 0., 0.], 0.),
|
||||
Ray::new([x, y, 10.], [0., 1., 0.], 0.),
|
||||
Ray::new([x, y, 10.], [0., -1., 0.], 0.),
|
||||
Ray::new([x, 10., y], [0., 1., 0.], 0.),
|
||||
Ray::new([x, 10., y], [0., -1., 0.], 0.),
|
||||
Ray::new([10., x, y], [0., 1., 0.], 0.),
|
||||
Ray::new([10., x, y], [0., -1., 0.], 0.),
|
||||
Ray::new([x, y, 10.], [0., 0., 1.], 0.),
|
||||
Ray::new([x, y, 10.], [0., 0., -1.], 0.),
|
||||
Ray::new([x, 10., y], [0., 0., 1.], 0.),
|
||||
Ray::new([x, 10., y], [0., 0., -1.], 0.),
|
||||
Ray::new([10., x, y], [0., 0., 1.], 0.),
|
||||
Ray::new([10., x, y], [0., 0., -1.], 0.),
|
||||
]
|
||||
.into_iter()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if false {
|
||||
// Outward in at an angle.
|
||||
let sqrt2 = 2f32.sqrt();
|
||||
rays.extend(vec![
|
||||
Ray::new([-1., 10., 10.], [sqrt2, sqrt2, 0.], 0.),
|
||||
Ray::new([-1., 10., 10.], [sqrt2, -sqrt2, 0.], 0.),
|
||||
Ray::new([-1., 10., 10.], [sqrt2, 0., sqrt2], 0.),
|
||||
Ray::new([-1., 10., 10.], [sqrt2, 0., -sqrt2], 0.),
|
||||
]);
|
||||
}
|
||||
|
||||
for r in rays.into_iter() {
|
||||
let c_hit = c
|
||||
.hit(r, 0., f32::MAX)
|
||||
.expect(&format!("c_hit missed {r:#?}"));
|
||||
let s_hit = s
|
||||
.hit(r, 0., f32::MAX)
|
||||
.expect(&format!("s_hit missed {r:#?}"));
|
||||
assert!(
|
||||
(c_hit.t - s_hit.t).abs() < EPSILON,
|
||||
"{r:?} [t] c_hit: {c_hit:#?}, s_hit: {s_hit:#?}"
|
||||
);
|
||||
// uv isn't valid for BVHTriangles.
|
||||
// assert_eq!( c_hit.uv, s_hit.uv, "{i}: [uv] c_hit: {c_hit:?}, s_hit: {s_hit:?}");
|
||||
assert_eq!(
|
||||
c_hit.p, s_hit.p,
|
||||
"{r:?}: [p] c_hit: {c_hit:#?}, s_hit: {s_hit:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
c_hit.normal, s_hit.normal,
|
||||
"{r:?}: [normal] c_hit: {c_hit:?}, s_hit: {s_hit:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
// TODO(wathiede): make this work.
|
||||
//#[test]
|
||||
fn compare_cuboid_proptest(
|
||||
ox in -20.0f32..40.0,
|
||||
oy in -20.0f32..40.0,
|
||||
oz in -20.0f32..40.0,
|
||||
dx in -1.0f32..1.0,
|
||||
dy in -1.0f32..1.0,
|
||||
dz in -1.0f32..1.0,
|
||||
) {
|
||||
let r = Ray::new([ox,oy,oz].into(), Vec3::new(dx, dy, dz).unit_vector(), 0.5);
|
||||
let c = Cuboid::new(
|
||||
[0., 0., 0.].into(),
|
||||
[20., 20., 20.].into(),
|
||||
Arc::new(Dielectric::new(1.5)),
|
||||
);
|
||||
let stl_cube = STL::parse(
|
||||
BufReader::new(Cursor::new(include_bytes!("../stls/cube.stl"))),
|
||||
false,
|
||||
)
|
||||
.expect("failed to parse cube");
|
||||
|
||||
let s = BVHTriangles::new(
|
||||
&stl_cube,
|
||||
Dielectric::new(1.5),
|
||||
//Metal::new(Vec3::new(0.8, 0.8, 0.8), 0.2),
|
||||
//Lambertian::new(ConstantTexture::new(Vec3::new(1.0, 0.2, 0.2))),
|
||||
);
|
||||
|
||||
let c_hit = c .hit(r, 0., f32::MAX);
|
||||
let s_hit = s .hit(r, 0., f32::MAX);
|
||||
|
||||
match (c_hit, s_hit) {
|
||||
(Some(_), None)=>assert!(false, "hit cuboid but not STL"),
|
||||
(None, Some(_))=>assert!(false, "hit STL but not cuboid"),
|
||||
(Some(c_hit), Some(s_hit))=> {
|
||||
assert!(
|
||||
(c_hit.t - s_hit.t).abs() < 0.00001,
|
||||
"{r:?} [t] c_hit: {c_hit:#?}, s_hit: {s_hit:#?}"
|
||||
);
|
||||
// uv isn't valid for BVHTriangles.
|
||||
// assert_eq!( c_hit.uv, s_hit.uv, "{i}: [uv] c_hit: {c_hit:?}, s_hit: {s_hit:?}");
|
||||
assert_eq!(
|
||||
c_hit.p, s_hit.p,
|
||||
"{r:?}: [p] c_hit: {c_hit:#?}, s_hit: {s_hit:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
c_hit.normal, s_hit.normal,
|
||||
"{r:?}: [normal] c_hit: {c_hit:?}, s_hit: {s_hit:?}"
|
||||
);
|
||||
},
|
||||
// It's okay if they both miss.
|
||||
(None,None)=>(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
use std::f32::consts::PI;
|
||||
|
||||
use rand::{self, Rng};
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::{
|
||||
ray::Ray,
|
||||
vec3::{cross, Vec3},
|
||||
};
|
||||
use crate::ray::Ray;
|
||||
use crate::vec3::cross;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
fn random_in_unit_disk() -> Vec3 {
|
||||
let mut rng = rand::thread_rng();
|
||||
@@ -18,7 +18,6 @@ fn random_in_unit_disk() -> Vec3 {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Camera {
|
||||
origin: Vec3,
|
||||
lower_left_corner: Vec3,
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
use rand::{self, Rng};
|
||||
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
// HSV values in [0..1]
|
||||
// returns [r, g, b] values from 0 to 255
|
||||
//From https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
|
||||
pub fn hsv_to_rgb(h: f32, s: f32, v: f32) -> Vec3 {
|
||||
let h_i = (h * 6.) as i32;
|
||||
let f = h * 6. - h_i as f32;
|
||||
let p = v * (1. - s);
|
||||
let q = v * (1. - f * s);
|
||||
let t = v * (1. - (1. - f) * s);
|
||||
match h_i {
|
||||
0 => Vec3::new(v, t, p),
|
||||
1 => Vec3::new(q, v, p),
|
||||
2 => Vec3::new(p, v, t),
|
||||
3 => Vec3::new(p, q, v),
|
||||
4 => Vec3::new(t, p, v),
|
||||
5 => Vec3::new(v, p, q),
|
||||
_ => panic!("Unknown H value {}", h_i),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_rainbow(num: usize) -> Vec<Vec3> {
|
||||
(0..num)
|
||||
.map(|n| {
|
||||
let h = n as f32 / num as f32;
|
||||
hsv_to_rgb(h, 0.99, 0.99)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
pub fn generate_palette(num: usize) -> Vec<Vec3> {
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut random = || rng.gen();
|
||||
// use golden ratio
|
||||
let golden_ratio_conjugate = 0.618_034;
|
||||
let mut h = random();
|
||||
(0..num)
|
||||
.map(|_| {
|
||||
h += golden_ratio_conjugate;
|
||||
h %= 1.0;
|
||||
hsv_to_rgb(h, 0.99, 0.99)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
use std;
|
||||
|
||||
use rand::{self, Rng};
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
material::Isotropic,
|
||||
ray::Ray,
|
||||
texture::Texture,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::material::Isotropic;
|
||||
use crate::ray::Ray;
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ConstantMedium<H, T>
|
||||
where
|
||||
H: Hit,
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
flip_normals::FlipNormals,
|
||||
hitable::{Hit, HitRecord},
|
||||
hitable_list::HitableList,
|
||||
material::Material,
|
||||
ray::Ray,
|
||||
rect::{XYRect, XZRect, YZRect},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::aabb::AABB;
|
||||
use crate::flip_normals::FlipNormals;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::material::Material;
|
||||
use crate::ray::Ray;
|
||||
use crate::rect::XYRect;
|
||||
use crate::rect::XZRect;
|
||||
use crate::rect::YZRect;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Cuboid {
|
||||
p_min: Vec3,
|
||||
p_max: Vec3,
|
||||
@@ -22,9 +22,6 @@ impl Cuboid {
|
||||
// This clippy doesn't work right with Arc.
|
||||
#[allow(clippy::needless_pass_by_value)]
|
||||
pub fn new(p_min: Vec3, p_max: Vec3, material: Arc<dyn Material>) -> Cuboid {
|
||||
assert!(p_min.x <= p_max.x);
|
||||
assert!(p_min.y <= p_max.y);
|
||||
assert!(p_min.z <= p_max.z);
|
||||
Cuboid {
|
||||
p_min,
|
||||
p_max,
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
material::Lambertian,
|
||||
ray::Ray,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DebugHit<H>
|
||||
where
|
||||
H: Hit,
|
||||
{
|
||||
hitable: H,
|
||||
material: Lambertian<[f32; 3]>,
|
||||
}
|
||||
|
||||
impl<H> DebugHit<H>
|
||||
where
|
||||
H: Hit,
|
||||
{
|
||||
pub fn new(hitable: H) -> DebugHit<H>
|
||||
where {
|
||||
DebugHit {
|
||||
hitable,
|
||||
material: Lambertian::new([0.2, 0.2, 0.2]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<H> Hit for DebugHit<H>
|
||||
where
|
||||
H: Hit,
|
||||
{
|
||||
fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
|
||||
if let Some(hit) = self.hitable.hit(r, t_min, t_max) {
|
||||
return Some(HitRecord { t: hit.t, ..hit });
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn bounding_box(&self, t_min: f32, t_max: f32) -> Option<AABB> {
|
||||
self.hitable.bounding_box(t_min, t_max)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
ray::Ray,
|
||||
};
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::ray::Ray;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FlipNormals<H>
|
||||
where
|
||||
H: Hit,
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
cuboid::Cuboid,
|
||||
hitable::{Hit, HitRecord},
|
||||
material::Material,
|
||||
ray::Ray,
|
||||
vec3::Vec3,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Glowybox {
|
||||
p_min: Vec3,
|
||||
p_max: Vec3,
|
||||
main: Cuboid,
|
||||
edges: [Cuboid; 12],
|
||||
}
|
||||
|
||||
impl Glowybox {
|
||||
// This clippy doesn't work right with Arc.
|
||||
#[allow(clippy::needless_pass_by_value)]
|
||||
pub fn new(
|
||||
p_min: Vec3,
|
||||
p_max: Vec3,
|
||||
edge_thickness: f32,
|
||||
main_material: Arc<dyn Material>,
|
||||
edge_material: Arc<dyn Material>,
|
||||
) -> Glowybox {
|
||||
assert!(p_min.x < p_max.x);
|
||||
assert!(p_min.y < p_max.y);
|
||||
assert!(p_min.z < p_max.z);
|
||||
let main = Cuboid::new(p_min, p_max, main_material);
|
||||
// Top edges
|
||||
let ht = edge_thickness / 2.;
|
||||
let edges = [
|
||||
// Top edges
|
||||
Cuboid::new(
|
||||
[p_min.x - ht, p_max.y - ht, p_min.z - ht].into(),
|
||||
[p_min.x + ht, p_max.y + ht, p_max.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
Cuboid::new(
|
||||
[p_min.x - ht, p_max.y - ht, p_min.z - ht].into(),
|
||||
[p_max.x + ht, p_max.y + ht, p_min.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
Cuboid::new(
|
||||
[p_max.x - ht, p_max.y - ht, p_min.z - ht].into(),
|
||||
[p_max.x + ht, p_max.y + ht, p_max.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
Cuboid::new(
|
||||
[p_min.x - ht, p_max.y - ht, p_max.z - ht].into(),
|
||||
[p_max.x + ht, p_max.y + ht, p_max.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
// Bottom edges
|
||||
Cuboid::new(
|
||||
[p_min.x - ht, p_min.y - ht, p_min.z - ht].into(),
|
||||
[p_min.x + ht, p_min.y + ht, p_max.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
Cuboid::new(
|
||||
[p_min.x - ht, p_min.y - ht, p_min.z - ht].into(),
|
||||
[p_max.x + ht, p_min.y + ht, p_min.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
Cuboid::new(
|
||||
[p_max.x - ht, p_min.y - ht, p_min.z - ht].into(),
|
||||
[p_max.x + ht, p_min.y + ht, p_max.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
Cuboid::new(
|
||||
[p_min.x - ht, p_min.y - ht, p_max.z - ht].into(),
|
||||
[p_max.x + ht, p_min.y + ht, p_max.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
// Middle edges
|
||||
Cuboid::new(
|
||||
[p_min.x - ht, p_min.y - ht, p_min.z - ht].into(),
|
||||
[p_min.x + ht, p_max.y + ht, p_min.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
Cuboid::new(
|
||||
[p_min.x - ht, p_min.y - ht, p_max.z - ht].into(),
|
||||
[p_min.x + ht, p_max.y + ht, p_max.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
Cuboid::new(
|
||||
[p_max.x - ht, p_min.y - ht, p_min.z - ht].into(),
|
||||
[p_max.x + ht, p_max.y + ht, p_min.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
Cuboid::new(
|
||||
[p_max.x - ht, p_min.y - ht, p_max.z - ht].into(),
|
||||
[p_max.x + ht, p_max.y + ht, p_max.z + ht].into(),
|
||||
Arc::clone(&edge_material),
|
||||
),
|
||||
];
|
||||
let p_min = [p_min.x - ht, p_min.y - ht, p_min.z - ht].into();
|
||||
let p_max = [p_max.x + ht, p_max.y + ht, p_max.z + ht].into();
|
||||
Glowybox {
|
||||
p_min,
|
||||
p_max,
|
||||
main,
|
||||
edges,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hit for Glowybox {
|
||||
fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
|
||||
let mut edge_hit = None;
|
||||
for edge in &self.edges {
|
||||
if let Some(hit) = edge.hit(r, t_min, t_max) {
|
||||
edge_hit = Some(hit);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let main_hit = self.main.hit(r, t_min, t_max);
|
||||
match (edge_hit, main_hit) {
|
||||
(Some(ehit), Some(mhit)) => {
|
||||
if mhit.t < ehit.t {
|
||||
Some(mhit)
|
||||
} else {
|
||||
Some(ehit)
|
||||
}
|
||||
}
|
||||
(Some(ehit), None) => Some(ehit),
|
||||
(None, Some(mhit)) => Some(mhit),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn bounding_box(&self, _t_min: f32, _t_max: f32) -> Option<AABB> {
|
||||
Some(AABB::new(self.p_min, self.p_max))
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
use std::{fmt::Debug, sync::Arc};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{aabb::AABB, material::Material, ray::Ray, vec3::Vec3};
|
||||
use crate::aabb::AABB;
|
||||
use crate::material::Material;
|
||||
use crate::ray::Ray;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct HitRecord<'m> {
|
||||
pub t: f32,
|
||||
pub uv: (f32, f32),
|
||||
@@ -11,7 +13,7 @@ pub struct HitRecord<'m> {
|
||||
pub material: &'m dyn Material,
|
||||
}
|
||||
|
||||
pub trait Hit: Send + Sync + Debug {
|
||||
pub trait Hit: Send + Sync {
|
||||
fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> Option<HitRecord>;
|
||||
fn bounding_box(&self, t_min: f32, t_max: f32) -> Option<AABB>;
|
||||
}
|
||||
@@ -24,12 +26,3 @@ impl Hit for Arc<dyn Hit> {
|
||||
(**self).bounding_box(t_min, t_max)
|
||||
}
|
||||
}
|
||||
|
||||
impl Hit for Box<dyn Hit> {
|
||||
fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
|
||||
(**self).hit(r, t_min, t_max)
|
||||
}
|
||||
fn bounding_box(&self, t_min: f32, t_max: f32) -> Option<AABB> {
|
||||
(**self).bounding_box(t_min, t_max)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use std;
|
||||
|
||||
use crate::{
|
||||
aabb::{surrounding_box, AABB},
|
||||
hitable::{Hit, HitRecord},
|
||||
ray::Ray,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::aabb::surrounding_box;
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::ray::Ray;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[derive(Default)]
|
||||
pub struct HitableList {
|
||||
list: Vec<Box<dyn Hit>>,
|
||||
}
|
||||
|
||||
@@ -130,12 +130,6 @@ impl Formatter {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Formatter {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Scales {
|
||||
/// Instantiates a new `Scales` with SI keys
|
||||
pub fn new() -> Self {
|
||||
@@ -205,7 +199,7 @@ impl Scales {
|
||||
}
|
||||
}
|
||||
|
||||
0.0
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
fn to_scaled_value(&self, value: f64) -> ScaledValue {
|
||||
@@ -227,9 +221,3 @@ impl Scales {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Scales {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,12 @@ use std::fmt;
|
||||
|
||||
use log::info;
|
||||
|
||||
use crate::{
|
||||
aabb::{surrounding_box, AABB},
|
||||
hitable::{Hit, HitRecord},
|
||||
hitable_list::HitableList,
|
||||
ray::Ray,
|
||||
};
|
||||
use crate::aabb::surrounding_box;
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::ray::Ray;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum KDTree {
|
||||
Leaf(Box<dyn Hit>),
|
||||
Branch {
|
||||
@@ -104,14 +102,6 @@ impl KDTree {
|
||||
}),
|
||||
_ => panic!("Unreachable"),
|
||||
};
|
||||
//info!("left_half {:?}", left_half);
|
||||
//info!("right_half {:?}", right_half);
|
||||
if left_half.is_empty() {
|
||||
return KDTree::Leaf(Box::new(HitableList::new(right_half)));
|
||||
};
|
||||
if right_half.is_empty() {
|
||||
return KDTree::Leaf(Box::new(HitableList::new(left_half)));
|
||||
};
|
||||
KDTree::Branch {
|
||||
left: Box::new(KDTree::new(left_half, t_min, t_max)),
|
||||
right: Box::new(KDTree::new(right_half, t_min, t_max)),
|
||||
@@ -156,7 +146,7 @@ fn print_tree(f: &mut fmt::Formatter, depth: usize, kdt: &KDTree) -> fmt::Result
|
||||
impl fmt::Display for KDTree {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
writeln!(f, "kd-tree")?;
|
||||
print_tree(f, 1, self)
|
||||
print_tree(f, 1, &self)
|
||||
}
|
||||
}
|
||||
impl Hit for KDTree {
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
pub mod aabb;
|
||||
pub mod bvh;
|
||||
pub mod bvh_triangles;
|
||||
pub mod camera;
|
||||
pub mod colors;
|
||||
pub mod constant_medium;
|
||||
pub mod cuboid;
|
||||
pub mod debug_hit;
|
||||
pub mod flip_normals;
|
||||
pub mod glowybox;
|
||||
pub mod hitable;
|
||||
pub mod hitable_list;
|
||||
pub mod human;
|
||||
@@ -16,15 +12,12 @@ pub mod material;
|
||||
pub mod moving_sphere;
|
||||
pub mod noise;
|
||||
pub mod output;
|
||||
pub mod parser;
|
||||
pub mod ray;
|
||||
pub mod rect;
|
||||
pub mod renderer;
|
||||
pub mod rotate;
|
||||
pub mod scale;
|
||||
pub mod scenes;
|
||||
pub mod sphere;
|
||||
pub mod texture;
|
||||
pub mod translate;
|
||||
pub mod triangles;
|
||||
pub mod vec3;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use std::{fmt::Debug, sync::Arc};
|
||||
use std::sync::Arc;
|
||||
|
||||
use rand::{self, Rng};
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::{
|
||||
hitable::HitRecord,
|
||||
ray::Ray,
|
||||
texture::Texture,
|
||||
vec3::{dot, Vec3},
|
||||
};
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::ray::Ray;
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::dot;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
fn random_in_unit_sphere() -> Vec3 {
|
||||
let mut rng = rand::thread_rng();
|
||||
@@ -20,14 +20,14 @@ fn random_in_unit_sphere() -> Vec3 {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
#[derive(Default)]
|
||||
pub struct ScatterResponse {
|
||||
pub scattered: Ray,
|
||||
pub attenutation: Vec3,
|
||||
pub reflected: bool,
|
||||
}
|
||||
|
||||
pub trait Material: Send + Sync + Debug {
|
||||
pub trait Material: Send + Sync {
|
||||
fn scatter(&self, r_in: &Ray, rec: &HitRecord) -> ScatterResponse;
|
||||
fn emitted(&self, _u: f32, _v: f32, _p: Vec3) -> Vec3 {
|
||||
Vec3::new(0., 0., 0.)
|
||||
@@ -52,7 +52,6 @@ impl Material for Box<dyn Material> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Isotropic<T>
|
||||
where
|
||||
T: Texture,
|
||||
@@ -83,7 +82,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Lambertian<T>
|
||||
where
|
||||
T: Texture,
|
||||
@@ -115,7 +113,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Metal {
|
||||
albedo: Vec3,
|
||||
fuzzy: f32,
|
||||
@@ -170,7 +167,6 @@ fn schlick(cosine: f32, ref_idx: f32) -> f32 {
|
||||
r0 + (1. - r0) * (1. - cosine).powf(5.)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Dielectric {
|
||||
ref_idx: f32,
|
||||
}
|
||||
@@ -217,7 +213,6 @@ impl Material for Dielectric {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DiffuseLight<T>
|
||||
where
|
||||
T: Texture,
|
||||
@@ -251,20 +246,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DebugMaterial {}
|
||||
|
||||
impl Material for DebugMaterial {
|
||||
fn scatter(&self, _r_in: &Ray, rec: &HitRecord) -> ScatterResponse {
|
||||
let dir = Vec3::new(0., -1., -1.).unit_vector();
|
||||
ScatterResponse {
|
||||
scattered: Ray::new(rec.p, dir, 0.),
|
||||
attenutation: [1., 1., 1.].into(),
|
||||
reflected: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use crate::{
|
||||
aabb::{surrounding_box, AABB},
|
||||
hitable::{Hit, HitRecord},
|
||||
material::Material,
|
||||
ray::Ray,
|
||||
sphere::get_sphere_uv,
|
||||
vec3::{dot, Vec3},
|
||||
};
|
||||
use crate::aabb::surrounding_box;
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::material::Material;
|
||||
use crate::ray::Ray;
|
||||
use crate::sphere::get_sphere_uv;
|
||||
use crate::vec3::dot;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MovingSphere<M>
|
||||
where
|
||||
M: Material,
|
||||
|
||||
@@ -2,10 +2,10 @@ use log::trace;
|
||||
/// Implements the concepts from https://lodev.org/cgtutor/randomnoise.html
|
||||
use rand;
|
||||
|
||||
use crate::{noise::NoiseSource, vec3::Vec3};
|
||||
use crate::noise::NoiseSource;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
const NOISE_SIZE: usize = 128;
|
||||
#[derive(Debug)]
|
||||
pub struct Lode {
|
||||
// Using fixed array causes stack overflow.
|
||||
noise: Vec<Vec<Vec<f32>>>, //[[[f32; NOISE_SIZE]; NOISE_SIZE]; NOISE_SIZE],
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
pub mod lode;
|
||||
pub mod perlin;
|
||||
|
||||
use std::{f32::consts::PI, fmt::Debug};
|
||||
use std::f32::consts::PI;
|
||||
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub trait NoiseSource: Send + Sync + Debug {
|
||||
pub trait NoiseSource: Send + Sync {
|
||||
/// value returns noise on the interval [0., 1.).
|
||||
fn value(&self, p: Vec3) -> f32;
|
||||
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
// There are many math functions in this file, so we allow single letter variable names.
|
||||
#![allow(clippy::many_single_char_names)]
|
||||
use log::trace;
|
||||
use rand::{seq::SliceRandom, Rng};
|
||||
use rand::seq::SliceRandom;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::{
|
||||
noise::NoiseSource,
|
||||
vec3::{dot, Vec3},
|
||||
};
|
||||
use crate::noise::NoiseSource;
|
||||
use crate::vec3::dot;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Perlin {
|
||||
ran_vec: Vec<Vec3>,
|
||||
perm_x: Vec<usize>,
|
||||
@@ -36,7 +35,7 @@ fn perlin_generate_perm<R>(rng: &mut R) -> Vec<usize>
|
||||
where
|
||||
R: Rng,
|
||||
{
|
||||
let mut p: Vec<usize> = (0..256).collect();
|
||||
let mut p: Vec<usize> = (0..256).map(|i| i).collect();
|
||||
p.shuffle(rng);
|
||||
p
|
||||
}
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::File,
|
||||
io::BufWriter,
|
||||
net::TcpStream,
|
||||
path::Path,
|
||||
sync::{Arc, Mutex},
|
||||
time,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::BufWriter;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time;
|
||||
|
||||
use chrono::Local;
|
||||
use image;
|
||||
use lazy_static::lazy_static;
|
||||
use log::info;
|
||||
use serde_derive::Serialize;
|
||||
use tev_client::{PacketCreateImage, PacketUpdateImage, TevClient};
|
||||
|
||||
use crate::{renderer::Scene, vec3::Vec3};
|
||||
use crate::renderer::Scene;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
// Main RGB image output from rendering the scene.
|
||||
pub const MAIN_IMAGE: &str = "@final";
|
||||
@@ -25,6 +24,10 @@ pub const ADAPTIVE_DEPTH: &str = "adaptive_depth";
|
||||
// Grey scale showing rays cast per pixel.
|
||||
pub const RAYS_PER_PIXEL: &str = "rays_per_pixel";
|
||||
|
||||
lazy_static! {
|
||||
static ref DEBUGGER: Arc<Mutex<Debugger>> = Arc::new(Mutex::new(Debugger::new()));
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ImageMetadata {
|
||||
name: String,
|
||||
@@ -71,180 +74,149 @@ impl Image {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OutputManager {
|
||||
images: Arc<Mutex<HashMap<String, (ImageType, Image)>>>,
|
||||
tev_client: Option<Arc<Mutex<TevClient>>>,
|
||||
struct Debugger {
|
||||
images: HashMap<String, (ImageType, Image)>,
|
||||
}
|
||||
|
||||
impl OutputManager {
|
||||
pub fn new(tev_addr: &Option<String>) -> std::io::Result<OutputManager> {
|
||||
let tev_client = if let Some(addr) = tev_addr {
|
||||
Some(Arc::new(Mutex::new(TevClient::wrap(TcpStream::connect(
|
||||
addr,
|
||||
)?))))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(OutputManager {
|
||||
images: Arc::new(Mutex::new(HashMap::new())),
|
||||
tev_client,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn register_image(&self, name: String, dimensions: (usize, usize), it: ImageType) {
|
||||
let mut images = self.images.lock().unwrap();
|
||||
images.insert(name.clone(), (it, Image::new(dimensions.0, dimensions.1)));
|
||||
self.tev_client.clone().map(|c| {
|
||||
c.lock().unwrap().send(PacketCreateImage {
|
||||
image_name: &name,
|
||||
grab_focus: false,
|
||||
width: dimensions.0 as u32,
|
||||
height: dimensions.1 as u32,
|
||||
channel_names: &["R", "G", "B"],
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
pub fn set_pixel(&self, name: &str, x: usize, y: usize, pixel: Vec3) {
|
||||
let mut images = self.images.lock().unwrap();
|
||||
let (_it, img) = images
|
||||
.get_mut(name)
|
||||
.unwrap_or_else(|| panic!("couldn't find image named '{}'", name));
|
||||
let y_inv = img.h - y - 1;
|
||||
img.put_pixel(x, y_inv, pixel);
|
||||
self.tev_client.clone().map(|c| {
|
||||
c.lock().unwrap().send(PacketUpdateImage {
|
||||
image_name: &name,
|
||||
grab_focus: false,
|
||||
channel_names: &["R", "G", "B"],
|
||||
channel_offsets: &[0, 1, 2],
|
||||
channel_strides: &[0, 0, 0],
|
||||
x: x as u32,
|
||||
y: y_inv as u32,
|
||||
width: 1,
|
||||
height: 1,
|
||||
data: &[pixel.x, pixel.y, pixel.z],
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
pub fn set_pixel_grey(&self, name: &str, x: usize, y: usize, grey: f32) {
|
||||
let mut images = self.images.lock().unwrap();
|
||||
let (_it, img) = images
|
||||
.get_mut(name)
|
||||
.unwrap_or_else(|| panic!("couldn't find image named '{}'", name));
|
||||
let y_inv = img.h - y - 1;
|
||||
img.put_pixel(x, y_inv, [grey, grey, grey].into());
|
||||
}
|
||||
pub fn write_images<P: AsRef<Path>>(
|
||||
&self,
|
||||
scene: &Scene,
|
||||
render_time: time::Duration,
|
||||
output_dir: P,
|
||||
) -> std::io::Result<()> {
|
||||
let output_dir: &Path = output_dir.as_ref();
|
||||
let now = Local::now();
|
||||
let images = self.images.lock().unwrap();
|
||||
// Write out images in consistent order.
|
||||
let mut names = images.keys().collect::<Vec<_>>();
|
||||
names.sort();
|
||||
let mut image_metadata = Vec::new();
|
||||
for name in &names {
|
||||
let (it, img) = images.get(*name).unwrap();
|
||||
let image = format!("{}.png", name);
|
||||
let binary = format!("{}.json", name);
|
||||
let ratio = img.w as f32 / img.h as f32;
|
||||
let size = (img.w, img.h);
|
||||
let image_path = output_dir.join(&image);
|
||||
let binary_path = output_dir.join(&binary);
|
||||
image_metadata.push(ImageMetadata {
|
||||
name: name.to_string(),
|
||||
image,
|
||||
binary,
|
||||
ratio,
|
||||
size,
|
||||
format: *it,
|
||||
});
|
||||
info!("Saving {}", image_path.to_string_lossy());
|
||||
match it {
|
||||
ImageType::RGB01 => {
|
||||
let mut out_img = image::RgbImage::new(img.w as u32, img.h as u32);
|
||||
out_img
|
||||
.enumerate_pixels_mut()
|
||||
.enumerate()
|
||||
.for_each(|(i, (_x, _y, p))| {
|
||||
let pixel = img.pix[i];
|
||||
*p = image::Rgb([
|
||||
(pixel[0] * 255.).min(255.) as u8,
|
||||
(pixel[1] * 255.).min(255.) as u8,
|
||||
(pixel[2] * 255.).min(255.) as u8,
|
||||
])
|
||||
});
|
||||
out_img.save(image_path)?;
|
||||
}
|
||||
ImageType::Grey01 => {
|
||||
let mut out_img = image::GrayImage::new(img.w as u32, img.h as u32);
|
||||
out_img
|
||||
.enumerate_pixels_mut()
|
||||
.enumerate()
|
||||
.for_each(|(i, (_x, _y, p))| {
|
||||
let pixel = img.pix[i];
|
||||
*p = image::Luma([(pixel[0] * 255.).min(255.) as u8])
|
||||
});
|
||||
out_img.save(image_path)?;
|
||||
}
|
||||
ImageType::GreyNormalized => {
|
||||
let mut out_img = image::GrayImage::new(img.w as u32, img.h as u32);
|
||||
|
||||
let max_val = img.pix.iter().map(|v| v.x).fold(0., f32::max);
|
||||
out_img
|
||||
.enumerate_pixels_mut()
|
||||
.enumerate()
|
||||
.for_each(|(i, (_x, _y, p))| {
|
||||
let pixel = img.pix[i];
|
||||
*p = image::Luma([(pixel[0] / max_val * 255.).min(255.) as u8])
|
||||
});
|
||||
out_img.save(image_path)?;
|
||||
}
|
||||
};
|
||||
info!("Saving {}", binary_path.to_string_lossy());
|
||||
let f = File::create(output_dir.join(binary_path))?;
|
||||
let f = BufWriter::new(f);
|
||||
match it {
|
||||
ImageType::RGB01 => {
|
||||
serde_json::ser::to_writer(
|
||||
f,
|
||||
&img.pix
|
||||
.iter()
|
||||
.map(|v| [v.x, v.y, v.z])
|
||||
.collect::<Vec<[f32; 3]>>(),
|
||||
)?;
|
||||
}
|
||||
ImageType::Grey01 | ImageType::GreyNormalized => {
|
||||
serde_json::ser::to_writer(
|
||||
f,
|
||||
&img.pix.iter().map(|v| v.x).collect::<Vec<f32>>(),
|
||||
)?;
|
||||
}
|
||||
};
|
||||
impl Debugger {
|
||||
fn new() -> Debugger {
|
||||
Debugger {
|
||||
images: HashMap::new(),
|
||||
}
|
||||
let f = File::create(output_dir.join("data.json"))?;
|
||||
let f = BufWriter::new(f);
|
||||
serde_json::ser::to_writer(
|
||||
f,
|
||||
&Data {
|
||||
timestamp: now.timestamp(),
|
||||
render_time_seconds: render_time.as_secs_f32(),
|
||||
scene,
|
||||
image_metadata,
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_image(name: String, dimensions: (usize, usize), it: ImageType) {
|
||||
let mut debugger = DEBUGGER.lock().unwrap();
|
||||
debugger
|
||||
.images
|
||||
.insert(name, (it, Image::new(dimensions.0, dimensions.1)));
|
||||
}
|
||||
|
||||
pub fn set_pixel(name: &str, x: usize, y: usize, pixel: Vec3) {
|
||||
let mut debugger = DEBUGGER.lock().unwrap();
|
||||
let (_it, img) = debugger
|
||||
.images
|
||||
.get_mut(name)
|
||||
.expect(&format!("couldn't find image named '{}'", name));
|
||||
let y_inv = img.h - y - 1;
|
||||
img.put_pixel(x, y_inv, pixel);
|
||||
}
|
||||
|
||||
pub fn set_pixel_grey(name: &str, x: usize, y: usize, grey: f32) {
|
||||
let mut debugger = DEBUGGER.lock().unwrap();
|
||||
let (_it, img) = debugger
|
||||
.images
|
||||
.get_mut(name)
|
||||
.expect(&format!("couldn't find image named '{}'", name));
|
||||
let y_inv = img.h - y - 1;
|
||||
img.put_pixel(x, y_inv, [grey, grey, grey].into());
|
||||
}
|
||||
|
||||
trait ImageSaver {
|
||||
fn save<Q>(&self, path: Q) -> std::io::Result<()>
|
||||
where
|
||||
Q: AsRef<Path> + Sized;
|
||||
}
|
||||
|
||||
pub fn write_images<P: AsRef<Path>>(
|
||||
scene: &Scene,
|
||||
render_time: time::Duration,
|
||||
output_dir: P,
|
||||
) -> std::io::Result<()> {
|
||||
let output_dir: &Path = output_dir.as_ref();
|
||||
let debugger = DEBUGGER.lock().unwrap();
|
||||
let now = Local::now();
|
||||
// Write out images in consistent order.
|
||||
let mut names = debugger.images.keys().collect::<Vec<_>>();
|
||||
names.sort();
|
||||
let mut image_metadata = Vec::new();
|
||||
for name in &names {
|
||||
let (it, img) = debugger.images.get(*name).unwrap();
|
||||
let image = format!("{}.png", name);
|
||||
let binary = format!("{}.json", name);
|
||||
let ratio = img.w as f32 / img.h as f32;
|
||||
let size = (img.w, img.h);
|
||||
let image_path = output_dir.join(&image);
|
||||
let binary_path = output_dir.join(&binary);
|
||||
image_metadata.push(ImageMetadata {
|
||||
name: name.to_string(),
|
||||
image,
|
||||
binary,
|
||||
ratio,
|
||||
size,
|
||||
format: *it,
|
||||
});
|
||||
info!("Saving {}", image_path.to_string_lossy());
|
||||
match it {
|
||||
ImageType::RGB01 => {
|
||||
let mut out_img = image::RgbImage::new(img.w as u32, img.h as u32);
|
||||
out_img
|
||||
.enumerate_pixels_mut()
|
||||
.enumerate()
|
||||
.for_each(|(i, (_x, _y, p))| {
|
||||
let pixel = img.pix[i];
|
||||
*p = image::Rgb([
|
||||
(pixel[0] * 255.).min(255.) as u8,
|
||||
(pixel[1] * 255.).min(255.) as u8,
|
||||
(pixel[2] * 255.).min(255.) as u8,
|
||||
])
|
||||
});
|
||||
out_img.save(image_path)?;
|
||||
}
|
||||
ImageType::Grey01 => {
|
||||
let mut out_img = image::GrayImage::new(img.w as u32, img.h as u32);
|
||||
out_img
|
||||
.enumerate_pixels_mut()
|
||||
.enumerate()
|
||||
.for_each(|(i, (_x, _y, p))| {
|
||||
let pixel = img.pix[i];
|
||||
*p = image::Luma([(pixel[0] * 255.).min(255.) as u8])
|
||||
});
|
||||
out_img.save(image_path)?;
|
||||
}
|
||||
ImageType::GreyNormalized => {
|
||||
let mut out_img = image::GrayImage::new(img.w as u32, img.h as u32);
|
||||
|
||||
let max_val = img.pix.iter().map(|v| v.x).fold(0., f32::max);
|
||||
out_img
|
||||
.enumerate_pixels_mut()
|
||||
.enumerate()
|
||||
.for_each(|(i, (_x, _y, p))| {
|
||||
let pixel = img.pix[i];
|
||||
*p = image::Luma([(pixel[0] / max_val * 255.).min(255.) as u8])
|
||||
});
|
||||
out_img.save(image_path)?;
|
||||
}
|
||||
};
|
||||
info!("Saving {}", binary_path.to_string_lossy());
|
||||
let f = File::create(output_dir.join(binary_path))?;
|
||||
let f = BufWriter::new(f);
|
||||
match it {
|
||||
ImageType::RGB01 => {
|
||||
serde_json::ser::to_writer(
|
||||
f,
|
||||
&img.pix
|
||||
.iter()
|
||||
.map(|v| [v.x, v.y, v.z])
|
||||
.collect::<Vec<[f32; 3]>>(),
|
||||
)?;
|
||||
}
|
||||
ImageType::Grey01 | ImageType::GreyNormalized => {
|
||||
serde_json::ser::to_writer(f, &img.pix.iter().map(|v| v.x).collect::<Vec<f32>>())?;
|
||||
}
|
||||
};
|
||||
}
|
||||
let f = File::create(output_dir.join("data.json"))?;
|
||||
let f = BufWriter::new(f);
|
||||
serde_json::ser::to_writer(
|
||||
f,
|
||||
&Data {
|
||||
timestamp: now.timestamp(),
|
||||
render_time_seconds: render_time.as_secs_f32(),
|
||||
scene,
|
||||
image_metadata,
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
use crate::{
|
||||
bvh_triangles::BVHTriangles,
|
||||
camera::Camera,
|
||||
cuboid::Cuboid,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
material::{Dielectric, DiffuseLight, Isotropic, Lambertian, Material, Metal},
|
||||
renderer::Scene,
|
||||
sphere::Sphere,
|
||||
texture::{EnvMap, Texture},
|
||||
};
|
||||
use chrono::IsoWeek;
|
||||
use serde::Deserialize;
|
||||
use std::{collections::HashMap, fs::File, io::BufReader, path::PathBuf, sync::Arc};
|
||||
use stl::STL;
|
||||
use thiserror::Error;
|
||||
use vec3::Vec3;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Config {
|
||||
scene: SceneConfig,
|
||||
camera: CameraConfig,
|
||||
materials: Vec<MaterialConfig>,
|
||||
hitables: Vec<HitableConfig>,
|
||||
envmap: Option<EnvMapConfig>,
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ConfigError {
|
||||
#[error("failed to load image")]
|
||||
ImageError(#[from] image::ImageError),
|
||||
#[error("failed to parser STL")]
|
||||
STLError(#[from] stl::ParseError),
|
||||
#[error("I/O error")]
|
||||
IOError(#[from] std::io::Error),
|
||||
#[error("duplication material named '{0}'")]
|
||||
DuplicateMaterial(String),
|
||||
#[error("unkown material named '{0}'")]
|
||||
UnknownMaterial(String),
|
||||
}
|
||||
|
||||
impl TryFrom<Config> for Scene {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(c: Config) -> Result<Scene, Self::Error> {
|
||||
let mut materials = HashMap::new();
|
||||
for mc in c.materials {
|
||||
let v: Arc<dyn Material> = match mc.material {
|
||||
Materials::Metal { albedo, fuzzy } => Arc::new(Metal::new(albedo, fuzzy)),
|
||||
Materials::Dielectric { ref_idx } => Arc::new(Dielectric::new(ref_idx)),
|
||||
Materials::DiffuseLight { texture } => Arc::new(DiffuseLight::new(texture)),
|
||||
Materials::Isotropic { texture } => Arc::new(Isotropic::new(texture)),
|
||||
Materials::Lambertian { texture } => Arc::new(Lambertian::new(texture)),
|
||||
};
|
||||
if materials.insert(mc.name.clone(), v).is_some() {
|
||||
return Err(ConfigError::DuplicateMaterial(mc.name));
|
||||
}
|
||||
}
|
||||
|
||||
let hitables: Result<Vec<Box<dyn Hit>>, Self::Error> = c
|
||||
.hitables
|
||||
.into_iter()
|
||||
.map(|hc| -> Result<Box<dyn Hit>, Self::Error> {
|
||||
match hc.hitable {
|
||||
Hitables::Sphere { center, radius } => Ok(Box::new(Sphere::new(
|
||||
center,
|
||||
radius,
|
||||
Arc::clone(
|
||||
materials
|
||||
.get(&hc.material_name)
|
||||
.ok_or(ConfigError::UnknownMaterial(hc.material_name))?,
|
||||
),
|
||||
))),
|
||||
Hitables::Cuboid { min, max } => Ok(Box::new(Cuboid::new(
|
||||
min.into(),
|
||||
max.into(),
|
||||
Arc::clone(
|
||||
materials
|
||||
.get(&hc.material_name)
|
||||
.ok_or(ConfigError::UnknownMaterial(hc.material_name))?,
|
||||
),
|
||||
))),
|
||||
Hitables::STL { path, scale } => {
|
||||
let r = BufReader::new(File::open(path)?);
|
||||
let stl = STL::parse(r, false)?;
|
||||
Ok(Box::new(BVHTriangles::new(
|
||||
&stl,
|
||||
Arc::clone(
|
||||
materials
|
||||
.get(&hc.material_name)
|
||||
.ok_or(ConfigError::UnknownMaterial(hc.material_name))?,
|
||||
),
|
||||
scale.unwrap_or(1.),
|
||||
)))
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let hitables = hitables?;
|
||||
|
||||
let world: Box<dyn Hit> = Box::new(HitableList::new(hitables));
|
||||
let mut env_map: Option<EnvMap> = None;
|
||||
|
||||
if let Some(em) = c.envmap {
|
||||
let im = image::open(em.path)?.into_rgb();
|
||||
env_map = Some(EnvMap::new(im));
|
||||
};
|
||||
|
||||
let camera = make_camera(&c.camera, c.scene.width, c.scene.height);
|
||||
|
||||
let scene = Scene {
|
||||
world,
|
||||
camera,
|
||||
env_map,
|
||||
subsamples: c.scene.subsamples.unwrap_or(8),
|
||||
adaptive_subsampling: c.scene.adaptive_subsampling,
|
||||
num_threads: c.scene.num_threads,
|
||||
width: c.scene.width,
|
||||
height: c.scene.height,
|
||||
global_illumination: c.scene.global_illumination.unwrap_or(true),
|
||||
};
|
||||
Ok(scene)
|
||||
}
|
||||
}
|
||||
|
||||
fn make_camera(cfg: &CameraConfig, width: usize, height: usize) -> Camera {
|
||||
Camera::new(
|
||||
cfg.lookfrom.into(),
|
||||
cfg.lookat.into(),
|
||||
Vec3::new(0., 1., 0.),
|
||||
cfg.fov,
|
||||
width as f32 / height as f32,
|
||||
cfg.aperture,
|
||||
cfg.focus_dist,
|
||||
cfg.time_min,
|
||||
cfg.time_max,
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SceneConfig {
|
||||
subsamples: Option<usize>,
|
||||
adaptive_subsampling: Option<f32>,
|
||||
num_threads: Option<usize>,
|
||||
width: usize,
|
||||
height: usize,
|
||||
global_illumination: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
struct HitableConfig {
|
||||
material_name: String,
|
||||
#[serde(flatten)]
|
||||
hitable: Hitables,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
enum Hitables {
|
||||
#[serde(rename = "sphere")]
|
||||
Sphere { center: [f32; 3], radius: f32 },
|
||||
#[serde(rename = "cuboid")]
|
||||
Cuboid { min: [f32; 3], max: [f32; 3] },
|
||||
#[serde(rename = "stl")]
|
||||
STL { path: PathBuf, scale: Option<f32> },
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct MaterialConfig {
|
||||
name: String,
|
||||
#[serde(flatten)]
|
||||
material: Materials,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
enum Materials {
|
||||
#[serde(rename = "metal")]
|
||||
Metal { albedo: [f32; 3], fuzzy: f32 },
|
||||
#[serde(rename = "dielectric")]
|
||||
Dielectric { ref_idx: f32 },
|
||||
// TODO(wathiede): these all take Textures, for now, only support RGB
|
||||
#[serde(rename = "diffuse_light")]
|
||||
DiffuseLight { texture: [f32; 3] },
|
||||
#[serde(rename = "isotropic")]
|
||||
Isotropic { texture: [f32; 3] },
|
||||
#[serde(rename = "lambertian")]
|
||||
Lambertian { texture: [f32; 3] },
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CameraConfig {
|
||||
lookfrom: [f32; 3],
|
||||
lookat: [f32; 3],
|
||||
fov: f32,
|
||||
aperture: f32,
|
||||
focus_dist: f32,
|
||||
time_min: f32,
|
||||
time_max: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct EnvMapConfig {
|
||||
path: PathBuf,
|
||||
}
|
||||
@@ -5,9 +5,6 @@ pub struct Ray {
|
||||
pub origin: Vec3,
|
||||
pub direction: Vec3,
|
||||
pub time: f32,
|
||||
|
||||
// Precache 1/direction, a single ray intersects multiple AABB's, and divides are more
|
||||
// expensive than multiplies.
|
||||
pub inv_direction: Vec3,
|
||||
pub sign: [usize; 3],
|
||||
}
|
||||
@@ -17,7 +14,7 @@ impl Ray {
|
||||
where
|
||||
V: Into<Vec3>,
|
||||
{
|
||||
let direction: Vec3 = direction.into();
|
||||
let direction = direction.into();
|
||||
let origin = origin.into();
|
||||
let inv = 1. / direction;
|
||||
Ray {
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
// There are many math functions in this file, so we allow single letter variable names.
|
||||
#![allow(clippy::many_single_char_names)]
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
material::Material,
|
||||
ray::Ray,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::material::Material;
|
||||
use crate::ray::Ray;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XYRect<M>
|
||||
where
|
||||
M: Material,
|
||||
@@ -70,7 +68,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XZRect<M>
|
||||
where
|
||||
M: Material,
|
||||
@@ -132,7 +129,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct YZRect<M>
|
||||
where
|
||||
M: Material,
|
||||
|
||||
@@ -1,41 +1,40 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fmt,
|
||||
ops::{AddAssign, Range},
|
||||
path::{Path, PathBuf},
|
||||
str, sync,
|
||||
sync::{
|
||||
mpsc::{sync_channel, Receiver, SyncSender},
|
||||
Arc, Mutex,
|
||||
},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use std::fmt;
|
||||
use std::ops::AddAssign;
|
||||
use std::ops::Range;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::str;
|
||||
use std::sync;
|
||||
use std::sync::mpsc::sync_channel;
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::sync::mpsc::SyncSender;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::thread;
|
||||
use std::time;
|
||||
|
||||
use core_affinity;
|
||||
use log::{info, trace};
|
||||
use log::info;
|
||||
use log::trace;
|
||||
use num_cpus;
|
||||
use rand::{self, Rng};
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
use serde_derive::Serialize;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
hitable::Hit,
|
||||
human,
|
||||
material::{Lambertian, Material},
|
||||
output,
|
||||
output::OutputManager,
|
||||
ray::Ray,
|
||||
scenes,
|
||||
sphere::Sphere,
|
||||
texture::{ConstantTexture, EnvMap},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use strum::{EnumString, EnumVariantNames};
|
||||
use crate::camera::Camera;
|
||||
use crate::hitable::Hit;
|
||||
use crate::human;
|
||||
use crate::material::Lambertian;
|
||||
use crate::output;
|
||||
use crate::ray::Ray;
|
||||
use crate::scenes;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::texture::EnvMap;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug, EnumString, EnumVariantNames, strum::Display)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
#[derive(Debug)]
|
||||
pub enum Model {
|
||||
BVH,
|
||||
Bench,
|
||||
@@ -46,30 +45,24 @@ pub enum Model {
|
||||
Mandelbrot,
|
||||
PerlinDebug,
|
||||
Spheramid,
|
||||
Stltest,
|
||||
Test,
|
||||
Tron,
|
||||
Tutorial,
|
||||
Dragon,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
pub fn scene(&self, opt: &Opt) -> Scene {
|
||||
match self {
|
||||
Model::BVH => scenes::bvh::new(opt),
|
||||
Model::Bench => scenes::bench::new(opt),
|
||||
Model::Book => scenes::book::new(opt),
|
||||
Model::CornellBox => scenes::cornell_box::new(opt),
|
||||
Model::CornellSmoke => scenes::cornell_smoke::new(opt),
|
||||
Model::Dragon => scenes::dragon::new(opt),
|
||||
Model::Final => scenes::final_scene::new(opt),
|
||||
Model::Mandelbrot => scenes::mandelbrot::new(opt),
|
||||
Model::PerlinDebug => scenes::perlin_debug::new(opt),
|
||||
Model::Spheramid => scenes::spheramid::new(opt),
|
||||
Model::Stltest => scenes::stltest::new(opt),
|
||||
Model::Test => scenes::test::new(opt),
|
||||
Model::Tron => scenes::tron::new(opt),
|
||||
Model::Tutorial => scenes::tutorial::new(opt),
|
||||
Model::BVH => scenes::bvh::new(&opt),
|
||||
Model::Bench => scenes::bench::new(&opt),
|
||||
Model::Book => scenes::book::new(&opt),
|
||||
Model::CornellBox => scenes::cornell_box::new(&opt),
|
||||
Model::CornellSmoke => scenes::cornell_smoke::new(&opt),
|
||||
Model::Final => scenes::final_scene::new(&opt),
|
||||
Model::Mandelbrot => scenes::mandelbrot::new(&opt),
|
||||
Model::PerlinDebug => scenes::perlin_debug::new(&opt),
|
||||
Model::Spheramid => scenes::spheramid::new(&opt),
|
||||
Model::Test => scenes::test::new(&opt),
|
||||
Model::Tutorial => scenes::tutorial::new(&opt),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,6 +76,44 @@ impl fmt::Display for ModelParseError {
|
||||
}
|
||||
}
|
||||
|
||||
impl str::FromStr for Model {
|
||||
type Err = ModelParseError;
|
||||
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
|
||||
match s {
|
||||
"bench" => Ok(Model::Bench),
|
||||
"book" => Ok(Model::Book),
|
||||
"bvh" => Ok(Model::BVH),
|
||||
"cornell_box" => Ok(Model::CornellBox),
|
||||
"cornell_smoke" => Ok(Model::CornellSmoke),
|
||||
"final" => Ok(Model::Final),
|
||||
"mandelbrot" => Ok(Model::Mandelbrot),
|
||||
"perlin_debug" => Ok(Model::PerlinDebug),
|
||||
"spheramid" => Ok(Model::Spheramid),
|
||||
"test" => Ok(Model::Test),
|
||||
"tutorial" => Ok(Model::Tutorial),
|
||||
_ => Err(ModelParseError(s.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::string::ToString for Model {
|
||||
fn to_string(&self) -> String {
|
||||
match self {
|
||||
Model::BVH => "bvh".to_string(),
|
||||
Model::Bench => "bench".to_string(),
|
||||
Model::Book => "book".to_string(),
|
||||
Model::CornellBox => "cornell_box".to_string(),
|
||||
Model::CornellSmoke => "cornell_smoke".to_string(),
|
||||
Model::Final => "final".to_string(),
|
||||
Model::Mandelbrot => "mandelbrot".to_string(),
|
||||
Model::PerlinDebug => "perlin_debug".to_string(),
|
||||
Model::Spheramid => "spheramid".to_string(),
|
||||
Model::Test => "test".to_string(),
|
||||
Model::Tutorial => "tutorial".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, StructOpt)]
|
||||
#[structopt(name = "tracer", about = "An experimental ray tracer.")]
|
||||
pub struct Opt {
|
||||
@@ -98,29 +129,19 @@ pub struct Opt {
|
||||
/// Sub-samples per pixel
|
||||
#[structopt(short = "s", long = "subsample", default_value = "8")]
|
||||
pub subsamples: usize,
|
||||
/// Select scene to render.
|
||||
#[structopt(long = "model")]
|
||||
pub model: Option<Model>,
|
||||
/// Toml config describing scene.
|
||||
#[structopt(long = "config")]
|
||||
pub config: Option<PathBuf>,
|
||||
/// Select scene to render, one of: "bench", "book", "tutorial", "bvh", "test", "cornell_box",
|
||||
/// "cornell_smoke", "perlin_debug", "final"
|
||||
#[structopt(long = "model", default_value = "book")]
|
||||
pub model: Model,
|
||||
/// Path to store pprof profile data, i.e. /tmp/cpuprofile.pprof
|
||||
#[structopt(long = "pprof", parse(from_os_str))]
|
||||
pub pprof: Option<PathBuf>,
|
||||
/// Use acceleration data structure, may be BVH or kd-tree depending on scene.
|
||||
#[structopt(long = "use_accel")]
|
||||
pub use_accel: bool,
|
||||
/// Host:port of running tev instance.
|
||||
#[structopt(long = "tev_addr")]
|
||||
pub tev_addr: Option<String>,
|
||||
|
||||
/// Output directory
|
||||
#[structopt(
|
||||
short = "o",
|
||||
long = "output",
|
||||
parse(from_os_str),
|
||||
default_value = "/tmp/tracer"
|
||||
)]
|
||||
#[structopt(parse(from_os_str), default_value = "/tmp/tracer")]
|
||||
pub output: PathBuf,
|
||||
}
|
||||
|
||||
@@ -132,20 +153,18 @@ pub fn opt_hash(opt: &Opt) -> String {
|
||||
opt.height,
|
||||
opt.subsamples,
|
||||
opt.pprof.is_some(),
|
||||
opt.model.as_ref().unwrap().to_string(),
|
||||
opt.model.to_string(),
|
||||
opt.use_accel,
|
||||
opt.output.display().to_string().replace('/', "_")
|
||||
opt.output.display().to_string().replace("/", "_")
|
||||
)
|
||||
}
|
||||
|
||||
// TODO(wathiede): implement the skips and then the renderer could use json as an input file type.
|
||||
#[derive(Debug, Serialize)]
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Scene {
|
||||
#[serde(skip)]
|
||||
pub world: Box<dyn Hit>,
|
||||
//#[serde(skip)]
|
||||
//pub materials: HashMap<String, Box<dyn Material>>,
|
||||
#[serde(skip)]
|
||||
pub camera: Camera,
|
||||
pub subsamples: usize,
|
||||
@@ -250,7 +269,6 @@ fn trace_pixel_adaptive(
|
||||
x_range: Range<f32>,
|
||||
y_range: Range<f32>,
|
||||
scene: &Scene,
|
||||
output: &OutputManager,
|
||||
) -> (Vec3, usize) {
|
||||
let w = scene.width as f32;
|
||||
let h = scene.height as f32;
|
||||
@@ -265,7 +283,7 @@ fn trace_pixel_adaptive(
|
||||
&scene.env_map,
|
||||
);
|
||||
if depth == 0 {
|
||||
output.set_pixel(output::ADAPTIVE_DEPTH, x, y, [1., 0., 0.].into());
|
||||
output::set_pixel(output::ADAPTIVE_DEPTH, x, y, [1., 0., 0.].into());
|
||||
return (center, rays);
|
||||
}
|
||||
// t = top
|
||||
@@ -307,7 +325,6 @@ fn trace_pixel_adaptive(
|
||||
x_range.start..x_mid,
|
||||
y_range.start..y_mid,
|
||||
scene,
|
||||
output,
|
||||
);
|
||||
let tr = trace_pixel_adaptive(
|
||||
depth - 1,
|
||||
@@ -317,7 +334,6 @@ fn trace_pixel_adaptive(
|
||||
x_mid..x_range.end,
|
||||
y_range.start..y_mid,
|
||||
scene,
|
||||
output,
|
||||
);
|
||||
let bl = trace_pixel_adaptive(
|
||||
depth - 1,
|
||||
@@ -327,7 +343,6 @@ fn trace_pixel_adaptive(
|
||||
x_range.start..x_mid,
|
||||
y_mid..y_range.end,
|
||||
scene,
|
||||
output,
|
||||
);
|
||||
let br = trace_pixel_adaptive(
|
||||
depth - 1,
|
||||
@@ -337,14 +352,13 @@ fn trace_pixel_adaptive(
|
||||
x_mid..x_range.end,
|
||||
y_mid..y_range.end,
|
||||
scene,
|
||||
output,
|
||||
);
|
||||
let pixel = (tl.0 + tr.0 + bl.0 + br.0) / 4.;
|
||||
let rays = tl.1 + tr.1 + bl.1 + br.1;
|
||||
(pixel, rays)
|
||||
} else {
|
||||
if depth == MAX_ADAPTIVE_DEPTH {
|
||||
output.set_pixel(output::ADAPTIVE_DEPTH, x, y, [0., 1., 0.].into());
|
||||
output::set_pixel(output::ADAPTIVE_DEPTH, x, y, [0., 1., 0.].into());
|
||||
}
|
||||
(corners, rays)
|
||||
}
|
||||
@@ -364,7 +378,7 @@ fn trace_pixel_random(x: usize, y: usize, scene: &Scene) -> (Vec3, usize) {
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct RenderStats {
|
||||
rays: usize,
|
||||
pixels: usize,
|
||||
@@ -380,37 +394,33 @@ impl AddAssign for RenderStats {
|
||||
}
|
||||
|
||||
fn progress(
|
||||
start_time: Instant,
|
||||
last_stat: &RenderStats,
|
||||
current_stat: &RenderStats,
|
||||
time_diff: Duration,
|
||||
time_diff: time::Duration,
|
||||
pixel_total: usize,
|
||||
) -> String {
|
||||
let human = human::Formatter::new();
|
||||
let pixel_diff = current_stat.pixels - last_stat.pixels;
|
||||
let ray_diff = current_stat.rays - last_stat.rays;
|
||||
let now = Instant::now();
|
||||
let start_diff = now - start_time;
|
||||
let ratio = current_stat.pixels as f32 / pixel_total as f32;
|
||||
let percent = ratio * 100.;
|
||||
let elapsed = start_diff.as_secs_f32();
|
||||
let total = elapsed * (1. / ratio);
|
||||
let eta = total - elapsed;
|
||||
format!(
|
||||
"{:7} / {:7}pixels ({:2.0}%) {:7}pixels/s {:7}rays/s eta {:.0}s",
|
||||
"{:7} / {:7}pixels ({:2}%) {:7}pixels/s {:7}rays/s",
|
||||
human.format(current_stat.pixels as f64),
|
||||
human.format(pixel_total as f64),
|
||||
percent,
|
||||
100 * current_stat.pixels / pixel_total,
|
||||
human.format(pixel_diff as f64 / time_diff.as_secs_f64()),
|
||||
human.format(ray_diff as f64 / time_diff.as_secs_f64()),
|
||||
eta
|
||||
human.format(ray_diff as f64 / time_diff.as_secs_f64())
|
||||
)
|
||||
}
|
||||
|
||||
impl Default for RenderStats {
|
||||
fn default() -> Self {
|
||||
RenderStats { rays: 0, pixels: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
enum Request {
|
||||
Pixel { x: usize, y: usize },
|
||||
Line { width: usize, y: usize },
|
||||
// TODO(wathiede): add Cohort that does 4x4 or 8x8 pixel chunks.
|
||||
}
|
||||
|
||||
enum Response {
|
||||
@@ -427,7 +437,7 @@ enum Response {
|
||||
},
|
||||
}
|
||||
|
||||
fn render_pixel(scene: &Scene, x: usize, y: usize, output: &OutputManager) -> (Vec3, usize) {
|
||||
fn render_pixel(scene: &Scene, x: usize, y: usize) -> (Vec3, usize) {
|
||||
let (pixel, rays) = if let Some(threshold) = scene.adaptive_subsampling {
|
||||
trace_pixel_adaptive(
|
||||
MAX_ADAPTIVE_DEPTH,
|
||||
@@ -437,7 +447,6 @@ fn render_pixel(scene: &Scene, x: usize, y: usize, output: &OutputManager) -> (V
|
||||
0.0..1.0,
|
||||
0.0..1.0,
|
||||
scene,
|
||||
output,
|
||||
)
|
||||
} else {
|
||||
let (pixel, rays) = (0..scene.subsamples)
|
||||
@@ -446,7 +455,7 @@ fn render_pixel(scene: &Scene, x: usize, y: usize, output: &OutputManager) -> (V
|
||||
([0., 0., 0.].into(), 0),
|
||||
|(p1, r1): (Vec3, usize), (p2, r2): (Vec3, usize)| ((p1 + p2), (r1 + r2)),
|
||||
);
|
||||
output.set_pixel_grey(output::RAYS_PER_PIXEL, x, y, rays as f32);
|
||||
output::set_pixel_grey(output::RAYS_PER_PIXEL, x, y, rays as f32);
|
||||
(pixel / scene.subsamples as f32, rays)
|
||||
};
|
||||
// Gamma correct, use gamma 2 correction, which is 1/gamma where gamma=2 which is 1/2 or
|
||||
@@ -462,7 +471,6 @@ fn render_worker(
|
||||
scene: &Scene,
|
||||
input_chan: Arc<Mutex<Receiver<Request>>>,
|
||||
output_chan: &SyncSender<Response>,
|
||||
output: &OutputManager,
|
||||
) {
|
||||
loop {
|
||||
let job = { input_chan.lock().unwrap().recv() };
|
||||
@@ -477,7 +485,7 @@ fn render_worker(
|
||||
let batch = false;
|
||||
if batch {
|
||||
let (pixels, rays): (Vec<Vec3>, Vec<usize>) = (0..width)
|
||||
.map(|x| render_pixel(scene, x, y, output))
|
||||
.map(|x| render_pixel(scene, x, y))
|
||||
.collect::<Vec<(_, _)>>()
|
||||
.into_iter()
|
||||
.unzip();
|
||||
@@ -494,7 +502,7 @@ fn render_worker(
|
||||
.expect("failed to send pixel response");
|
||||
} else {
|
||||
(0..width).for_each(|x| {
|
||||
let (pixel, rays) = render_pixel(scene, x, y, output);
|
||||
let (pixel, rays) = render_pixel(scene, x, y);
|
||||
output_chan
|
||||
.send(Response::Pixel {
|
||||
x,
|
||||
@@ -508,7 +516,7 @@ fn render_worker(
|
||||
}
|
||||
Request::Pixel { x, y } => {
|
||||
trace!("tid {} x {} y {}", tid, x, y);
|
||||
let (pixel, rays) = render_pixel(scene, x, y, output);
|
||||
let (pixel, rays) = render_pixel(scene, x, y);
|
||||
output_chan
|
||||
.send(Response::Pixel {
|
||||
x,
|
||||
@@ -523,19 +531,8 @@ fn render_worker(
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
lazy_static! {
|
||||
static ref DEBUGGER: Arc<Mutex<OutputManager>> = Arc::new(Mutex::new(OutputManager::new()));
|
||||
}
|
||||
*/
|
||||
|
||||
pub fn render(
|
||||
scene: Scene,
|
||||
output_dir: &Path,
|
||||
tev_addr: &Option<String>,
|
||||
) -> std::result::Result<(), std::io::Error> {
|
||||
// Default to half the cores to disable hyperthreading.
|
||||
let num_threads = scene.num_threads.unwrap_or_else(|| num_cpus::get() / 2);
|
||||
pub fn render(scene: Scene, output_dir: &Path) -> std::result::Result<(), std::io::Error> {
|
||||
let num_threads = scene.num_threads.unwrap_or_else(num_cpus::get);
|
||||
let (pixel_req_tx, pixel_req_rx) = sync_channel(2 * num_threads);
|
||||
let (pixel_resp_tx, pixel_resp_rx) = sync_channel(2 * num_threads);
|
||||
|
||||
@@ -549,23 +546,20 @@ pub fn render(
|
||||
} else {
|
||||
core_ids
|
||||
};
|
||||
let output = output::OutputManager::new(tev_addr)?;
|
||||
let output = Arc::new(output);
|
||||
|
||||
info!("Creating {} render threads", core_ids.len());
|
||||
output.register_image(
|
||||
output::register_image(
|
||||
output::MAIN_IMAGE.to_string(),
|
||||
(scene.width, scene.height),
|
||||
output::ImageType::RGB01,
|
||||
);
|
||||
if scene.adaptive_subsampling.is_some() {
|
||||
output.register_image(
|
||||
output::register_image(
|
||||
output::ADAPTIVE_DEPTH.to_string(),
|
||||
(scene.width, scene.height),
|
||||
output::ImageType::RGB01,
|
||||
);
|
||||
}
|
||||
output.register_image(
|
||||
output::register_image(
|
||||
output::RAYS_PER_PIXEL.to_string(),
|
||||
(scene.width, scene.height),
|
||||
output::ImageType::GreyNormalized,
|
||||
@@ -579,19 +573,19 @@ pub fn render(
|
||||
let s = sync::Arc::clone(&scene);
|
||||
let pixel_req_rx = pixel_req_rx.clone();
|
||||
let pixel_resp_tx = pixel_resp_tx.clone();
|
||||
let output = sync::Arc::clone(&output);
|
||||
thread::spawn(move || {
|
||||
core_affinity::set_for_current(id);
|
||||
render_worker(i, &s, pixel_req_rx, &pixel_resp_tx, &output);
|
||||
render_worker(i, &s, pixel_req_rx, &pixel_resp_tx);
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
drop(pixel_req_rx);
|
||||
drop(pixel_resp_tx);
|
||||
|
||||
let start_time = time::Instant::now();
|
||||
let (w, h) = (scene.width, scene.height);
|
||||
handles.push(thread::spawn(move || {
|
||||
let batch_line_requests = false;
|
||||
let batch_line_requests = true;
|
||||
if batch_line_requests {
|
||||
for y in 0..h {
|
||||
pixel_req_tx
|
||||
@@ -613,36 +607,29 @@ pub fn render(
|
||||
info!("Rendering with {} subsamples", scene.subsamples);
|
||||
|
||||
let pixel_total = scene.width * scene.height;
|
||||
let mut last_time = Instant::now();
|
||||
let mut last_time = time::Instant::now();
|
||||
let mut last_stat: RenderStats = Default::default();
|
||||
let mut current_stat: RenderStats = Default::default();
|
||||
let render_start_time = Instant::now();
|
||||
for resp in pixel_resp_rx {
|
||||
match resp {
|
||||
Response::Pixel { x, y, pixel, rs } => {
|
||||
current_stat += rs;
|
||||
output.set_pixel(output::MAIN_IMAGE, x, y, pixel);
|
||||
output::set_pixel(output::MAIN_IMAGE, x, y, pixel);
|
||||
}
|
||||
Response::Line { y, pixels, rs } => {
|
||||
current_stat += rs;
|
||||
for (x, pixel) in pixels.iter().enumerate() {
|
||||
output.set_pixel(output::MAIN_IMAGE, x, y, *pixel);
|
||||
output::set_pixel(output::MAIN_IMAGE, x, y, *pixel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
let now = time::Instant::now();
|
||||
let time_diff = now - last_time;
|
||||
if time_diff > Duration::from_secs(5) {
|
||||
println!(
|
||||
if time_diff > time::Duration::from_secs(1) {
|
||||
info!(
|
||||
"{}",
|
||||
progress(
|
||||
render_start_time,
|
||||
&last_stat,
|
||||
¤t_stat,
|
||||
time_diff,
|
||||
pixel_total
|
||||
)
|
||||
progress(&last_stat, ¤t_stat, time_diff, pixel_total)
|
||||
);
|
||||
last_stat = current_stat;
|
||||
last_time = now;
|
||||
@@ -651,18 +638,12 @@ pub fn render(
|
||||
for thr in handles {
|
||||
thr.join().expect("thread join");
|
||||
}
|
||||
let time_diff = Instant::now() - render_start_time;
|
||||
println!(
|
||||
"Render {} seconds {}",
|
||||
let time_diff = time::Instant::now() - start_time;
|
||||
info!(
|
||||
"Runtime {} seconds {}",
|
||||
time_diff.as_secs_f32(),
|
||||
progress(
|
||||
render_start_time,
|
||||
&Default::default(),
|
||||
¤t_stat,
|
||||
time_diff,
|
||||
pixel_total
|
||||
)
|
||||
progress(&Default::default(), ¤t_stat, time_diff, pixel_total)
|
||||
);
|
||||
|
||||
output.write_images(&scene, time_diff, output_dir)
|
||||
output::write_images(&scene, time_diff, output_dir)
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use std::f32::{consts::PI, MAX, MIN};
|
||||
use std::f32::consts::PI;
|
||||
use std::f32::MAX;
|
||||
use std::f32::MIN;
|
||||
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
ray::Ray,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::ray::Ray;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RotateY<H>
|
||||
where
|
||||
H: Hit,
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
ray::Ray,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Scale<H>
|
||||
where
|
||||
H: Hit,
|
||||
{
|
||||
hitable: H,
|
||||
scale: f32,
|
||||
}
|
||||
|
||||
impl<H> Scale<H>
|
||||
where
|
||||
H: Hit,
|
||||
{
|
||||
pub fn new(hitable: H, scale: f32) -> Scale<H> {
|
||||
Scale { hitable, scale }
|
||||
}
|
||||
}
|
||||
|
||||
impl<H> Hit for Scale<H>
|
||||
where
|
||||
H: Hit,
|
||||
{
|
||||
fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
|
||||
let moved_r = Ray::new(r.origin / self.scale, r.direction, r.time);
|
||||
if let Some(rec) = self.hitable.hit(moved_r, t_min, t_max) {
|
||||
return Some(HitRecord {
|
||||
p: rec.p * self.scale,
|
||||
t: rec.t * self.scale,
|
||||
..rec
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn bounding_box(&self, t_min: f32, t_max: f32) -> Option<AABB> {
|
||||
if let Some(bbox) = self.hitable.bounding_box(t_min, t_max) {
|
||||
return Some(AABB::new(bbox.min() * self.scale, bbox.max() * self.scale));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
use log::trace;
|
||||
use rand::{self, Rng};
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::{
|
||||
bvh::BVH,
|
||||
camera::Camera,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::Lambertian,
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::ConstantTexture,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::bvh::BVH;
|
||||
use crate::camera::Camera;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::kdtree::KDTree;
|
||||
use crate::material::Lambertian;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(20., 20., 20.);
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
use rand::{self, Rng};
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{Dielectric, Lambertian, Material, Metal},
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::{CheckerTexture, ConstantTexture, EnvMap},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::camera::Camera;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::kdtree::KDTree;
|
||||
use crate::material::Dielectric;
|
||||
use crate::material::Lambertian;
|
||||
use crate::material::Material;
|
||||
use crate::material::Metal;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::CheckerTexture;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::texture::EnvMap;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(13., 2., 3.);
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
use log::trace;
|
||||
|
||||
use crate::{
|
||||
bvh::BVH,
|
||||
camera::Camera,
|
||||
hitable::Hit,
|
||||
material::{Lambertian, Metal},
|
||||
moving_sphere::MovingSphere,
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::ConstantTexture,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::bvh::BVH;
|
||||
use crate::camera::Camera;
|
||||
use crate::hitable::Hit;
|
||||
use crate::material::Lambertian;
|
||||
use crate::material::Metal;
|
||||
use crate::moving_sphere::MovingSphere;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(3., 3., 2.);
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
cuboid::Cuboid,
|
||||
flip_normals::FlipNormals,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{DiffuseLight, Lambertian},
|
||||
rect::{XYRect, XZRect, YZRect},
|
||||
renderer::{Opt, Scene},
|
||||
rotate::RotateY,
|
||||
texture::ConstantTexture,
|
||||
translate::Translate,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::camera::Camera;
|
||||
use crate::cuboid::Cuboid;
|
||||
use crate::flip_normals::FlipNormals;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::kdtree::KDTree;
|
||||
use crate::material::DiffuseLight;
|
||||
use crate::material::Lambertian;
|
||||
use crate::rect::XYRect;
|
||||
use crate::rect::XZRect;
|
||||
use crate::rect::YZRect;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::rotate::RotateY;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::translate::Translate;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(278., 278., -800.);
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
constant_medium::ConstantMedium,
|
||||
cuboid::Cuboid,
|
||||
flip_normals::FlipNormals,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{DiffuseLight, Lambertian, Material},
|
||||
rect::{XYRect, XZRect, YZRect},
|
||||
renderer::{Opt, Scene},
|
||||
rotate::RotateY,
|
||||
texture::ConstantTexture,
|
||||
translate::Translate,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::camera::Camera;
|
||||
use crate::constant_medium::ConstantMedium;
|
||||
use crate::cuboid::Cuboid;
|
||||
use crate::flip_normals::FlipNormals;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::kdtree::KDTree;
|
||||
use crate::material::DiffuseLight;
|
||||
use crate::material::Lambertian;
|
||||
use crate::material::Material;
|
||||
use crate::rect::XYRect;
|
||||
use crate::rect::XZRect;
|
||||
use crate::rect::YZRect;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::rotate::RotateY;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::translate::Translate;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(278., 278., -800.);
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
use std::{
|
||||
f32::consts::PI,
|
||||
io::{BufReader, Cursor},
|
||||
};
|
||||
|
||||
use stl::STL;
|
||||
|
||||
use crate::{
|
||||
bvh_triangles::BVHTriangles,
|
||||
camera::Camera,
|
||||
colors::generate_rainbow,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{Lambertian, Metal},
|
||||
renderer::{Opt, Scene},
|
||||
rotate::RotateY,
|
||||
scale::Scale,
|
||||
sphere::Sphere,
|
||||
texture::{ConstantTexture, EnvMap},
|
||||
translate::Translate,
|
||||
vec3::Vec3,
|
||||
};
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(0., 80., 80.);
|
||||
let lookat = Vec3::new(0., 0., 0.);
|
||||
let dist_to_focus = 10.0;
|
||||
let aperture = 0.0;
|
||||
let time_min = 0.;
|
||||
let time_max = 1.;
|
||||
let camera = Camera::new(
|
||||
lookfrom,
|
||||
lookat,
|
||||
Vec3::new(0., 1., 0.),
|
||||
45.,
|
||||
opt.width as f32 / opt.height as f32,
|
||||
aperture,
|
||||
dist_to_focus,
|
||||
time_min,
|
||||
time_max,
|
||||
);
|
||||
//let dragon_material = Dielectric::new(1.5);
|
||||
let dragon_material = Metal::new(Vec3::new(0.6, 0.6, 0.6), 0.0);
|
||||
//let dragon_material = Lambertian::new(ConstantTexture::new(Vec3::new(1.0, 1.0, 0.2)));
|
||||
|
||||
let ground_color = if opt.use_accel {
|
||||
ConstantTexture::new(Vec3::new(1.0, 0.4, 0.4))
|
||||
} else {
|
||||
ConstantTexture::new(Vec3::new(0.4, 0.4, 0.4))
|
||||
};
|
||||
|
||||
let stl_cube = STL::parse(
|
||||
BufReader::new(Cursor::new(include_bytes!("../../stls/dragon.stl"))),
|
||||
false,
|
||||
)
|
||||
.expect("failed to parse cube");
|
||||
let _light_size = 50.;
|
||||
let _light_height = 200.;
|
||||
let sphere_radius = 5.;
|
||||
let circle_radius = 40.;
|
||||
let num_spheres = 16;
|
||||
let palette = generate_rainbow(num_spheres);
|
||||
let spheres: Vec<Box<dyn Hit>> = (0..num_spheres)
|
||||
.map(|i| (i, i as f32, num_spheres as f32))
|
||||
.map(|(idx, idx_f, n)| (idx, idx_f * 2. * PI / n))
|
||||
.map(|(idx, rad)| -> Box<dyn Hit> {
|
||||
let x = circle_radius * rad.cos();
|
||||
let y = 4. * sphere_radius;
|
||||
let z = circle_radius * rad.sin();
|
||||
let c = palette[idx];
|
||||
Box::new(Sphere::new(
|
||||
[x, y, z],
|
||||
sphere_radius,
|
||||
Lambertian::new(ConstantTexture::new(c)),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let mut objects: Vec<Box<dyn Hit>> = vec![
|
||||
Box::new(Sphere::new(
|
||||
Vec3::new(0., 0.1, -0.5),
|
||||
0.1,
|
||||
Lambertian::new([0., 1., 1.]),
|
||||
)),
|
||||
// Earth sized sphere
|
||||
//Box::new(Sphere::new( Vec3::new(0., -10000., 0.), 10000., Lambertian::new(ground_color),)),
|
||||
// STL Mesh
|
||||
Box::new(crate::debug_hit::DebugHit::new(RotateY::new(
|
||||
Translate::new(
|
||||
BVHTriangles::new(&stl_cube, dragon_material, 250.),
|
||||
[0., -10., 0.],
|
||||
),
|
||||
180.,
|
||||
))),
|
||||
];
|
||||
objects.extend(spheres);
|
||||
|
||||
let world: Box<dyn Hit> = if opt.use_accel {
|
||||
Box::new(KDTree::new(objects, time_min, time_max))
|
||||
} else {
|
||||
Box::new(HitableList::new(objects))
|
||||
};
|
||||
let skybox_bytes = include_bytes!("../../images/envmap.jpg");
|
||||
let skybox = image::load_from_memory(skybox_bytes).unwrap().to_rgb();
|
||||
Scene {
|
||||
camera,
|
||||
world,
|
||||
subsamples: opt.subsamples,
|
||||
num_threads: opt.num_threads,
|
||||
width: opt.width,
|
||||
height: opt.height,
|
||||
global_illumination: true,
|
||||
env_map: Some(EnvMap::new(skybox)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,33 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use image;
|
||||
use rand::{self, Rng};
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
constant_medium::ConstantMedium,
|
||||
cuboid::Cuboid,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{Dielectric, DiffuseLight, Lambertian, Material, Metal},
|
||||
moving_sphere::MovingSphere,
|
||||
noise::{perlin::Perlin, NoiseType},
|
||||
rect::XZRect,
|
||||
renderer::{Opt, Scene},
|
||||
rotate::RotateY,
|
||||
sphere::Sphere,
|
||||
texture::{ConstantTexture, ImageTexture, NoiseTexture},
|
||||
translate::Translate,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::camera::Camera;
|
||||
use crate::constant_medium::ConstantMedium;
|
||||
use crate::cuboid::Cuboid;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::kdtree::KDTree;
|
||||
use crate::material::Dielectric;
|
||||
use crate::material::DiffuseLight;
|
||||
use crate::material::Lambertian;
|
||||
use crate::material::Material;
|
||||
use crate::material::Metal;
|
||||
use crate::moving_sphere::MovingSphere;
|
||||
use crate::noise::perlin::Perlin;
|
||||
use crate::noise::NoiseType;
|
||||
use crate::rect::XZRect;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::rotate::RotateY;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::texture::ImageTexture;
|
||||
use crate::texture::NoiseTexture;
|
||||
use crate::translate::Translate;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(478., 278., -600.);
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
use rand;
|
||||
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{DiffuseLight, Lambertian},
|
||||
noise::{perlin::Perlin, NoiseType},
|
||||
rect::{XYRect, XZRect, YZRect},
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::{ConstantTexture, ImageTexture, Mandelbrot, NoiseTexture},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::camera::Camera;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::kdtree::KDTree;
|
||||
use crate::material::DiffuseLight;
|
||||
use crate::material::Lambertian;
|
||||
use crate::noise::perlin::Perlin;
|
||||
use crate::noise::NoiseType;
|
||||
use crate::rect::XYRect;
|
||||
use crate::rect::XZRect;
|
||||
use crate::rect::YZRect;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::texture::ImageTexture;
|
||||
use crate::texture::Mandelbrot;
|
||||
use crate::texture::NoiseTexture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(20., 20., 20.);
|
||||
|
||||
@@ -3,12 +3,9 @@ pub mod book;
|
||||
pub mod bvh;
|
||||
pub mod cornell_box;
|
||||
pub mod cornell_smoke;
|
||||
pub mod dragon;
|
||||
pub mod final_scene;
|
||||
pub mod mandelbrot;
|
||||
pub mod perlin_debug;
|
||||
pub mod spheramid;
|
||||
pub mod stltest;
|
||||
pub mod test;
|
||||
pub mod tron;
|
||||
pub mod tutorial;
|
||||
|
||||
@@ -2,18 +2,19 @@ use std::sync::Arc;
|
||||
|
||||
use rand;
|
||||
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::Lambertian,
|
||||
noise::{perlin::Perlin, NoiseType},
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::{NoiseTexture, Texture},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::camera::Camera;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::kdtree::KDTree;
|
||||
use crate::material::Lambertian;
|
||||
use crate::noise::perlin::Perlin;
|
||||
use crate::noise::NoiseType;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::NoiseTexture;
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(13., 2., 3.);
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
material::{Dielectric, Lambertian, Metal},
|
||||
moving_sphere::MovingSphere,
|
||||
rect::XYRect,
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::{CheckerTexture, ConstantTexture, EnvMap},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::camera::Camera;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::material::Dielectric;
|
||||
use crate::material::Lambertian;
|
||||
use crate::material::Metal;
|
||||
use crate::moving_sphere::MovingSphere;
|
||||
use crate::rect::XYRect;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::CheckerTexture;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::texture::EnvMap;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
// Draws many spheres along each positive axis.
|
||||
// Blue X-positive
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
use std::{
|
||||
io::{BufReader, Cursor},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use stl::STL;
|
||||
|
||||
use crate::{
|
||||
bvh_triangles::BVHTriangles,
|
||||
camera::Camera,
|
||||
cuboid::Cuboid,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{Dielectric, Lambertian, Metal},
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::{ConstantTexture, EnvMap},
|
||||
translate::Translate,
|
||||
vec3::Vec3,
|
||||
};
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(0., 40., -100.);
|
||||
let lookat = Vec3::new(0., 10., 0.);
|
||||
let dist_to_focus = 10.0;
|
||||
let aperture = 0.0;
|
||||
let time_min = 0.;
|
||||
let time_max = 1.;
|
||||
let camera = Camera::new(
|
||||
lookfrom,
|
||||
lookat,
|
||||
Vec3::new(0., 1., 0.),
|
||||
45.,
|
||||
opt.width as f32 / opt.height as f32,
|
||||
aperture,
|
||||
dist_to_focus,
|
||||
time_min,
|
||||
time_max,
|
||||
);
|
||||
let ground_color = if opt.use_accel {
|
||||
ConstantTexture::new(Vec3::new(1.0, 0.4, 0.4))
|
||||
} else {
|
||||
ConstantTexture::new(Vec3::new(0.4, 0.4, 0.4))
|
||||
};
|
||||
|
||||
let glass = Dielectric::new(1.5);
|
||||
let metal = Metal::new(Vec3::new(0.8, 0.8, 0.8), 0.2);
|
||||
let red = Lambertian::new(ConstantTexture::new(Vec3::new(1.0, 0.2, 0.2)));
|
||||
|
||||
//let box_material = glass;
|
||||
let _ = glass;
|
||||
let _ = metal;
|
||||
let _ = red;
|
||||
|
||||
let stl_cube = STL::parse(
|
||||
BufReader::new(Cursor::new(include_bytes!("../../stls/cube.stl"))),
|
||||
false,
|
||||
)
|
||||
.expect("failed to parse cube");
|
||||
let objects: Vec<Box<dyn Hit>> = vec![
|
||||
// Light from above - white
|
||||
// Earth sized sphere
|
||||
Box::new(Sphere::new(
|
||||
Vec3::new(0., -10000., 0.),
|
||||
10000.,
|
||||
Lambertian::new(ground_color),
|
||||
)),
|
||||
Box::new(Sphere::new(
|
||||
Vec3::new(0., 20., -40.),
|
||||
10.,
|
||||
Lambertian::new(ConstantTexture::new(Vec3::new(1., 0.2, 1.))),
|
||||
)),
|
||||
// Blue sphere
|
||||
Box::new(Sphere::new(
|
||||
Vec3::new(0., 20., 40.),
|
||||
20.,
|
||||
Lambertian::new(ConstantTexture::new(Vec3::new(0.2, 0.2, 1.))),
|
||||
)),
|
||||
Box::new(Sphere::new(
|
||||
Vec3::new(40., 20., 40.),
|
||||
20.,
|
||||
//Metal::new(Vec3::new(0.8, 0.8, 0.8), 0.2),
|
||||
Lambertian::new(ConstantTexture::new(Vec3::new(0.2, 1.0, 0.2))),
|
||||
)),
|
||||
Box::new(Sphere::new(
|
||||
Vec3::new(-40., 20., 40.),
|
||||
20.,
|
||||
//Metal::new(Vec3::new(0.8, 0.8, 0.8), 0.2),
|
||||
Lambertian::new(ConstantTexture::new(Vec3::new(1.0, 0.2, 0.2))),
|
||||
)),
|
||||
// STL Mesh
|
||||
Box::new(Translate::new(
|
||||
BVHTriangles::new(&stl_cube, glass, 1.),
|
||||
[0., 10., 0.],
|
||||
)),
|
||||
//Box::new(BVHTriangles::new(&stl_cube, box_material.clone())),
|
||||
Box::new(Cuboid::new(
|
||||
[-20., 0., 0.].into(),
|
||||
[0., 20., 20.].into(),
|
||||
Arc::new(red),
|
||||
)),
|
||||
];
|
||||
let world: Box<dyn Hit> = if opt.use_accel {
|
||||
Box::new(KDTree::new(objects, time_min, time_max))
|
||||
} else {
|
||||
Box::new(HitableList::new(objects))
|
||||
};
|
||||
let skybox_bytes = include_bytes!("../../images/envmap.jpg");
|
||||
let skybox = image::load_from_memory(skybox_bytes).unwrap().to_rgb();
|
||||
Scene {
|
||||
camera,
|
||||
world,
|
||||
subsamples: opt.subsamples,
|
||||
num_threads: opt.num_threads,
|
||||
width: opt.width,
|
||||
height: opt.height,
|
||||
global_illumination: true,
|
||||
env_map: Some(EnvMap::new(skybox)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,24 @@
|
||||
use image;
|
||||
use rand;
|
||||
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{DiffuseLight, Lambertian},
|
||||
noise::{perlin::Perlin, NoiseType},
|
||||
rect::{XYRect, XZRect, YZRect},
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::{ConstantTexture, ImageTexture, NoiseTexture},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::camera::Camera;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::kdtree::KDTree;
|
||||
use crate::material::DiffuseLight;
|
||||
use crate::material::Lambertian;
|
||||
use crate::noise::perlin::Perlin;
|
||||
use crate::noise::NoiseType;
|
||||
use crate::rect::XYRect;
|
||||
use crate::rect::XZRect;
|
||||
use crate::rect::YZRect;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::texture::ImageTexture;
|
||||
use crate::texture::NoiseTexture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(20., 20., 20.);
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use log::info;
|
||||
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
glowybox::Glowybox,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{DiffuseLight, Lambertian},
|
||||
rect::{XYRect, XZRect, YZRect},
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::ConstantTexture,
|
||||
vec3::Vec3,
|
||||
};
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(20., 20., 20.);
|
||||
let lookat = Vec3::new(0., 1., 0.);
|
||||
let dist_to_focus = 10.0;
|
||||
let aperture = 0.0;
|
||||
let time_min = 0.;
|
||||
let time_max = 1.;
|
||||
let camera = Camera::new(
|
||||
lookfrom,
|
||||
lookat,
|
||||
Vec3::new(0., 1., 0.),
|
||||
20.,
|
||||
opt.width as f32 / opt.height as f32,
|
||||
aperture,
|
||||
dist_to_focus,
|
||||
time_min,
|
||||
time_max,
|
||||
);
|
||||
let ground_color = if opt.use_accel {
|
||||
ConstantTexture::new(Vec3::new(1.0, 0.4, 0.4))
|
||||
} else {
|
||||
ConstantTexture::new(Vec3::new(0.4, 1.0, 0.4))
|
||||
};
|
||||
|
||||
let lights: Vec<Box<dyn Hit>> = vec![
|
||||
Box::new(XZRect::new(
|
||||
-100.,
|
||||
100.,
|
||||
-100.,
|
||||
1000.,
|
||||
60.,
|
||||
DiffuseLight::new(ConstantTexture::new(Vec3::new(1., 1., 1.))),
|
||||
)),
|
||||
Box::new(YZRect::new(
|
||||
1.,
|
||||
3.,
|
||||
-1.,
|
||||
1.,
|
||||
4.,
|
||||
DiffuseLight::new(ConstantTexture::new(Vec3::new(4., 0., 4.))),
|
||||
)),
|
||||
Box::new(YZRect::new(
|
||||
1.,
|
||||
3.,
|
||||
-1.,
|
||||
1.,
|
||||
-4.,
|
||||
DiffuseLight::new(ConstantTexture::new(Vec3::new(0., 4., 0.))),
|
||||
)),
|
||||
Box::new(XZRect::new(
|
||||
-1.,
|
||||
1.,
|
||||
-1.,
|
||||
1.,
|
||||
6.,
|
||||
DiffuseLight::new(ConstantTexture::new(Vec3::new(4., 4., 0.))),
|
||||
)),
|
||||
Box::new(XYRect::new(
|
||||
-1.,
|
||||
1.,
|
||||
1.,
|
||||
3.,
|
||||
-4.,
|
||||
DiffuseLight::new(ConstantTexture::new(Vec3::new(0., 0., 4.))),
|
||||
)),
|
||||
Box::new(XYRect::new(
|
||||
-1.,
|
||||
1.,
|
||||
1.,
|
||||
3.,
|
||||
4.,
|
||||
DiffuseLight::new(ConstantTexture::new(Vec3::new(0., 4., 4.))),
|
||||
)),
|
||||
];
|
||||
let mut objects: Vec<Box<dyn Hit>> = vec![
|
||||
// Earth sized sphere
|
||||
Box::new(Sphere::new(
|
||||
Vec3::new(0., -1010., 0.),
|
||||
1000.,
|
||||
Lambertian::new(ground_color),
|
||||
)),
|
||||
Box::new(Glowybox::new(
|
||||
[-4., -4., -4.].into(),
|
||||
[4., 4., 4.].into(),
|
||||
0.01,
|
||||
Arc::new(Lambertian::new(ConstantTexture::new([0., 0., 0.]))),
|
||||
Arc::new(DiffuseLight::new(ConstantTexture::new([100., 0., 0.]))),
|
||||
)),
|
||||
];
|
||||
objects.extend(lights);
|
||||
info!("objects {:?}", objects);
|
||||
let world: Box<dyn Hit> = if opt.use_accel {
|
||||
Box::new(KDTree::new(objects, time_min, time_max))
|
||||
} else {
|
||||
Box::new(HitableList::new(objects))
|
||||
};
|
||||
Scene {
|
||||
camera,
|
||||
world,
|
||||
subsamples: opt.subsamples,
|
||||
num_threads: opt.num_threads,
|
||||
width: opt.width,
|
||||
height: opt.height,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
use crate::{
|
||||
camera::Camera,
|
||||
hitable::Hit,
|
||||
hitable_list::HitableList,
|
||||
kdtree::KDTree,
|
||||
material::{Dielectric, Lambertian, Metal},
|
||||
moving_sphere::MovingSphere,
|
||||
renderer::{Opt, Scene},
|
||||
sphere::Sphere,
|
||||
texture::{CheckerTexture, ConstantTexture, Texture},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::camera::Camera;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable_list::HitableList;
|
||||
use crate::kdtree::KDTree;
|
||||
use crate::material::Dielectric;
|
||||
use crate::material::Lambertian;
|
||||
use crate::material::Metal;
|
||||
use crate::moving_sphere::MovingSphere;
|
||||
use crate::renderer::Opt;
|
||||
use crate::renderer::Scene;
|
||||
use crate::sphere::Sphere;
|
||||
use crate::texture::CheckerTexture;
|
||||
use crate::texture::ConstantTexture;
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub fn new(opt: &Opt) -> Scene {
|
||||
let lookfrom = Vec3::new(3., 4., 2.);
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
use std::f32::consts::PI;
|
||||
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
material::Material,
|
||||
ray::Ray,
|
||||
vec3::{dot, Vec3},
|
||||
};
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::material::Material;
|
||||
use crate::ray::Ray;
|
||||
use crate::vec3::dot;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Sphere<M>
|
||||
where
|
||||
M: Material,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{texture::Texture, vec3::Vec3};
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CheckerTexture<T>
|
||||
where
|
||||
T: Texture,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::{texture::Texture, vec3::Vec3};
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct ConstantTexture {
|
||||
color: Vec3,
|
||||
}
|
||||
|
||||
@@ -2,10 +2,9 @@ use std::f32;
|
||||
|
||||
use image::RgbImage;
|
||||
|
||||
use crate::{
|
||||
texture::{ImageTexture, Texture},
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::texture::ImageTexture;
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EnvMap {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use image::RgbImage;
|
||||
|
||||
use crate::{texture::Texture, vec3::Vec3};
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ImageTexture {
|
||||
|
||||
@@ -1,15 +1,55 @@
|
||||
#![allow(clippy::many_single_char_names)]
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::{colors::generate_palette, texture::Texture, vec3::Vec3};
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Mandelbrot {
|
||||
scale: f32,
|
||||
palette: Vec<Vec3>,
|
||||
}
|
||||
|
||||
// HSV values in [0..1]
|
||||
// returns [r, g, b] values from 0 to 255
|
||||
//From https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
|
||||
fn hsv_to_rgb(h: f32, s: f32, v: f32) -> Vec3 {
|
||||
let h_i = (h * 6.) as i32;
|
||||
let f = h * 6. - h_i as f32;
|
||||
let p = v * (1. - s);
|
||||
let q = v * (1. - f * s);
|
||||
let t = v * (1. - (1. - f) * s);
|
||||
match h_i {
|
||||
0 => Vec3::new(v, t, p),
|
||||
1 => Vec3::new(q, v, p),
|
||||
2 => Vec3::new(p, v, t),
|
||||
3 => Vec3::new(p, q, v),
|
||||
4 => Vec3::new(t, p, v),
|
||||
5 => Vec3::new(v, p, q),
|
||||
_ => panic!("Unknown H value {}", h_i),
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_palette(num: usize) -> Vec<Vec3> {
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut random = || rng.gen();
|
||||
// use golden ratio
|
||||
let golden_ratio_conjugate = 0.618_034;
|
||||
let mut h = random();
|
||||
(0..num)
|
||||
.map(|_| {
|
||||
h += golden_ratio_conjugate;
|
||||
h %= 1.0;
|
||||
hsv_to_rgb(h, 0.99, 0.99)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Default for Mandelbrot {
|
||||
fn default() -> Self {
|
||||
Mandelbrot {
|
||||
scale: 2.0,
|
||||
palette: generate_palette(10),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,16 +4,18 @@ mod envmap;
|
||||
mod image;
|
||||
mod mandelbrot;
|
||||
mod noise;
|
||||
pub use crate::texture::{
|
||||
checker::CheckerTexture, constant::ConstantTexture, envmap::EnvMap, image::ImageTexture,
|
||||
mandelbrot::Mandelbrot, noise::NoiseTexture,
|
||||
};
|
||||
pub use crate::texture::checker::CheckerTexture;
|
||||
pub use crate::texture::constant::ConstantTexture;
|
||||
pub use crate::texture::envmap::EnvMap;
|
||||
pub use crate::texture::image::ImageTexture;
|
||||
pub use crate::texture::mandelbrot::Mandelbrot;
|
||||
pub use crate::texture::noise::NoiseTexture;
|
||||
|
||||
use std::{fmt::Debug, sync::Arc};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
pub trait Texture: Send + Sync + Debug {
|
||||
pub trait Texture: Send + Sync {
|
||||
fn value(&self, u: f32, v: f32, p: Vec3) -> Vec3;
|
||||
}
|
||||
|
||||
@@ -29,12 +31,6 @@ impl Texture for Box<dyn Texture> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Texture for [f32; 3] {
|
||||
fn value(&self, u: f32, v: f32, p: Vec3) -> Vec3 {
|
||||
(*self).into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
use crate::{
|
||||
noise::{NoiseSource, NoiseType},
|
||||
texture::Texture,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::noise::NoiseSource;
|
||||
use crate::noise::NoiseType;
|
||||
use crate::texture::Texture;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NoiseTexture<N>
|
||||
where
|
||||
N: NoiseSource,
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
ray::Ray,
|
||||
vec3::Vec3,
|
||||
};
|
||||
use crate::aabb::AABB;
|
||||
use crate::hitable::Hit;
|
||||
use crate::hitable::HitRecord;
|
||||
use crate::ray::Ray;
|
||||
use crate::vec3::Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Translate<H>
|
||||
where
|
||||
H: Hit,
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
use std::f32::EPSILON;
|
||||
|
||||
use stl::STL;
|
||||
|
||||
use crate::{
|
||||
aabb::AABB,
|
||||
hitable::{Hit, HitRecord},
|
||||
material::Material,
|
||||
ray::Ray,
|
||||
vec3::{cross, dot, Vec3},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Triangle {
|
||||
normal: Vec3,
|
||||
verts: [Vec3; 3],
|
||||
// Precomputed data
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Triangles<M>
|
||||
where
|
||||
M: Material,
|
||||
{
|
||||
pub triangles: Vec<Triangle>,
|
||||
pub bbox: AABB,
|
||||
material: M,
|
||||
}
|
||||
|
||||
impl<M> Triangles<M>
|
||||
where
|
||||
M: Material,
|
||||
{
|
||||
pub fn new(stl: &STL, material: M, scale_factor: f32) -> Triangles<M> {
|
||||
let triangles: Vec<_> = stl
|
||||
.triangles
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let v0 = t.verts[0] * scale_factor;
|
||||
let v1 = t.verts[1] * scale_factor;
|
||||
let v2 = t.verts[2] * scale_factor;
|
||||
Triangle {
|
||||
normal: t.normal,
|
||||
verts: [v0, v1, v2],
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let (min, max) = triangles.iter().fold(
|
||||
(Vec3::from(f32::MAX), Vec3::from(f32::MIN)),
|
||||
|(min, max), t| {
|
||||
let t_min_x = t.verts[0].x.min(t.verts[1].x.min(t.verts[2].x));
|
||||
let t_min_y = t.verts[0].y.min(t.verts[1].y.min(t.verts[2].y));
|
||||
let t_min_z = t.verts[0].z.min(t.verts[1].z.min(t.verts[2].z));
|
||||
let t_max_x = t.verts[0].x.max(t.verts[1].x.max(t.verts[2].x));
|
||||
let t_max_y = t.verts[0].y.max(t.verts[1].y.max(t.verts[2].y));
|
||||
let t_max_z = t.verts[0].z.max(t.verts[1].z.max(t.verts[2].z));
|
||||
|
||||
(
|
||||
Vec3::from([min.x.min(t_min_x), min.y.min(t_min_y), min.z.min(t_min_z)]),
|
||||
Vec3::from([max.x.max(t_max_x), max.y.max(t_max_y), max.z.max(t_max_z)]),
|
||||
)
|
||||
},
|
||||
);
|
||||
let bbox = AABB::new(min, max);
|
||||
Triangles {
|
||||
triangles,
|
||||
bbox,
|
||||
material,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Based on https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection.html
|
||||
fn ray_triangle_intersect_moller_trumbore(r: Ray, tri: &Triangle) -> Option<RayTriangleResult> {
|
||||
// #ifdef MOLLER_TRUMBORE
|
||||
// Vec3f v0v1 = v1 - v0;
|
||||
// Vec3f v0v2 = v2 - v0;
|
||||
// Vec3f pvec = dir.crossProduct(v0v2);
|
||||
// float det = v0v1.dotProduct(pvec);
|
||||
// #ifdef CULLING
|
||||
// // if the determinant is negative, the triangle is 'back facing'
|
||||
// // if the determinant is close to 0, the ray misses the triangle
|
||||
// if (det < kEpsilon) return false;
|
||||
// #else
|
||||
// // ray and triangle are parallel if det is close to 0
|
||||
// if (fabs(det) < kEpsilon) return false;
|
||||
// #endif
|
||||
// float invDet = 1 / det;
|
||||
//
|
||||
// Vec3f tvec = orig - v0;
|
||||
// u = tvec.dotProduct(pvec) * invDet;
|
||||
// if (u < 0 || u > 1) return false;
|
||||
//
|
||||
// Vec3f qvec = tvec.crossProduct(v0v1);
|
||||
// v = dir.dotProduct(qvec) * invDet;
|
||||
// if (v < 0 || u + v > 1) return false;
|
||||
//
|
||||
// t = v0v2.dotProduct(qvec) * invDet;
|
||||
//
|
||||
let v0 = tri.verts[0];
|
||||
let v1 = tri.verts[1];
|
||||
let v2 = tri.verts[2];
|
||||
|
||||
let v0v1 = v1 - v0;
|
||||
let v0v2 = v2 - v0;
|
||||
let p = cross(r.direction, v0v2);
|
||||
let det = dot(v0v1, p);
|
||||
if det < EPSILON {
|
||||
return None;
|
||||
}
|
||||
|
||||
let inv_det = 1. / det;
|
||||
|
||||
let t = r.origin - v0;
|
||||
let u = dot(t, p) * inv_det;
|
||||
if u < 0. || u > 1. {
|
||||
return None;
|
||||
}
|
||||
|
||||
let q = cross(t, v0v1);
|
||||
let v = dot(r.direction, q) * inv_det;
|
||||
if v < 0. || u + v > 1. {
|
||||
return None;
|
||||
}
|
||||
let t = dot(v0v2, q) * inv_det;
|
||||
|
||||
if t > EPSILON {
|
||||
return Some(RayTriangleResult {
|
||||
t,
|
||||
p: r.origin + r.direction * t,
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl<M> Hit for Triangles<M>
|
||||
where
|
||||
M: Material,
|
||||
{
|
||||
fn hit(&self, r: Ray, _t_min: f32, _t_max: f32) -> Option<HitRecord> {
|
||||
// TODO(wathiede): add an acceleration structure to more cheaply skip some triangles.
|
||||
for tri in &self.triangles {
|
||||
if let Some(RayTriangleResult { t, p }) = ray_triangle_intersect_moller_trumbore(r, tri)
|
||||
{
|
||||
//if let Some(RayTriangleResult { t, p }) = ray_triangle_intersect_geometric(r, tri) {
|
||||
// We don't support UV (yet?).
|
||||
let uv = (0.5, 0.5);
|
||||
return Some(HitRecord {
|
||||
t,
|
||||
uv,
|
||||
p,
|
||||
normal: tri.normal,
|
||||
material: &self.material,
|
||||
});
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn bounding_box(&self, _t_min: f32, _t_max: f32) -> Option<AABB> {
|
||||
Some(self.bbox)
|
||||
}
|
||||
}
|
||||
|
||||
struct RayTriangleResult {
|
||||
t: f32,
|
||||
p: Vec3,
|
||||
}
|
||||
@@ -1 +1,279 @@
|
||||
pub use vec3::*;
|
||||
use std::convert::From;
|
||||
use std::fmt;
|
||||
use std::num::ParseFloatError;
|
||||
use std::ops::Add;
|
||||
use std::ops::Div;
|
||||
use std::ops::Index;
|
||||
use std::ops::Mul;
|
||||
use std::ops::Neg;
|
||||
use std::ops::Sub;
|
||||
use std::str;
|
||||
|
||||
use serde_derive::Deserialize;
|
||||
use serde_derive::Serialize;
|
||||
|
||||
#[derive(Default, Debug, Deserialize, Serialize, PartialEq, Copy, Clone)]
|
||||
pub struct Vec3 {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
}
|
||||
|
||||
pub fn cross(v1: Vec3, v2: Vec3) -> Vec3 {
|
||||
Vec3 {
|
||||
x: v1.y * v2.z - v1.z * v2.y,
|
||||
y: v1.z * v2.x - v1.x * v2.z,
|
||||
z: v1.x * v2.y - v1.y * v2.x,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dot(v1: Vec3, v2: Vec3) -> f32 {
|
||||
v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
|
||||
}
|
||||
|
||||
impl Vec3 {
|
||||
pub fn new(x: f32, y: f32, z: f32) -> Vec3 {
|
||||
Vec3 { x, y, z }
|
||||
}
|
||||
|
||||
pub fn min(self) -> f32 {
|
||||
self.x.min(self.y).min(self.z)
|
||||
}
|
||||
|
||||
pub fn max(self) -> f32 {
|
||||
self.x.max(self.y).max(self.z)
|
||||
}
|
||||
|
||||
pub fn length(self) -> f32 {
|
||||
self.squared_length().sqrt()
|
||||
}
|
||||
|
||||
pub fn squared_length(self) -> f32 {
|
||||
self.x * self.x + self.y * self.y + self.z * self.z
|
||||
}
|
||||
|
||||
pub fn unit_vector(self) -> Vec3 {
|
||||
self / self.length()
|
||||
}
|
||||
|
||||
pub fn make_unit_vector(&mut self) {
|
||||
*self = self.unit_vector();
|
||||
}
|
||||
}
|
||||
|
||||
impl From<[f32; 3]> for Vec3 {
|
||||
fn from(v: [f32; 3]) -> Self {
|
||||
Vec3 {
|
||||
x: v[0],
|
||||
y: v[1],
|
||||
z: v[2],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Vec3 {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{} {} {}", self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl str::FromStr for Vec3 {
|
||||
type Err = ParseFloatError;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let coords: Vec<&str> = s.split(' ').collect();
|
||||
Ok(Vec3 {
|
||||
x: coords[0].parse::<f32>()?,
|
||||
y: coords[1].parse::<f32>()?,
|
||||
z: coords[2].parse::<f32>()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Add<f32> for Vec3 {
|
||||
type Output = Vec3;
|
||||
|
||||
fn add(self, r: f32) -> Vec3 {
|
||||
Vec3 {
|
||||
x: self.x + r,
|
||||
y: self.y + r,
|
||||
z: self.z + r,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for Vec3 {
|
||||
type Output = Vec3;
|
||||
|
||||
fn add(self, r: Vec3) -> Vec3 {
|
||||
Vec3 {
|
||||
x: self.x + r.x,
|
||||
y: self.y + r.y,
|
||||
z: self.z + r.z,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Div<Vec3> for f32 {
|
||||
type Output = Vec3;
|
||||
|
||||
fn div(self, r: Vec3) -> Vec3 {
|
||||
Vec3 {
|
||||
x: self / r.x,
|
||||
y: self / r.y,
|
||||
z: self / r.z,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Div<f32> for Vec3 {
|
||||
type Output = Vec3;
|
||||
|
||||
fn div(self, r: f32) -> Vec3 {
|
||||
Vec3 {
|
||||
x: self.x / r,
|
||||
y: self.y / r,
|
||||
z: self.z / r,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Index<usize> for Vec3 {
|
||||
type Output = f32;
|
||||
fn index(&self, idx: usize) -> &f32 {
|
||||
match idx {
|
||||
0 => &self.x,
|
||||
1 => &self.y,
|
||||
2 => &self.z,
|
||||
_ => panic!("idx {} out of range for vec3", idx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul for Vec3 {
|
||||
type Output = Vec3;
|
||||
|
||||
fn mul(self, r: Vec3) -> Vec3 {
|
||||
Vec3 {
|
||||
x: self.x * r.x,
|
||||
y: self.y * r.y,
|
||||
z: self.z * r.z,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<Vec3> for f32 {
|
||||
type Output = Vec3;
|
||||
|
||||
fn mul(self, v: Vec3) -> Vec3 {
|
||||
Vec3 {
|
||||
x: v.x * self,
|
||||
y: v.y * self,
|
||||
z: v.z * self,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<f32> for Vec3 {
|
||||
type Output = Vec3;
|
||||
|
||||
fn mul(self, r: f32) -> Vec3 {
|
||||
Vec3 {
|
||||
x: self.x * r,
|
||||
y: self.y * r,
|
||||
z: self.z * r,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Neg for Vec3 {
|
||||
type Output = Vec3;
|
||||
|
||||
fn neg(self) -> Vec3 {
|
||||
-1. * self
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for Vec3 {
|
||||
type Output = Vec3;
|
||||
|
||||
fn sub(self, r: Vec3) -> Vec3 {
|
||||
Vec3 {
|
||||
x: self.x - r.x,
|
||||
y: self.y - r.y,
|
||||
z: self.z - r.z,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::f32::consts::PI;
|
||||
use std::str::FromStr;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn vec_add() {
|
||||
let v0 = Vec3::new(1., 2., 3.);
|
||||
let v1 = Vec3::new(1., 1., 1.);
|
||||
assert_eq!(v0 + v1, Vec3::new(2., 3., 4.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_div() {
|
||||
let v0 = Vec3::new(1., 2., 4.);
|
||||
assert_eq!(v0 / 2., Vec3::new(0.5, 1., 2.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_mul() {
|
||||
let v0 = Vec3::new(1., 2., 4.);
|
||||
assert_eq!(v0 * 0.5, Vec3::new(0.5, 1., 2.));
|
||||
assert_eq!(v0 * v0, Vec3::new(1., 4., 16.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_sub() {
|
||||
let v0 = Vec3::new(1., 2., 3.);
|
||||
let v1 = Vec3::new(1., 1., 1.);
|
||||
assert_eq!(v0 - v1, Vec3::new(0., 1., 2.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_idx() {
|
||||
let v0 = Vec3::new(1., 2., 3.);
|
||||
assert_eq!(v0[2], 3.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_display() {
|
||||
let v0 = Vec3::new(1., 2., 3.);
|
||||
assert_eq!(format!("{}", v0), "1 2 3".to_owned());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_from_str() {
|
||||
assert_eq!(Vec3::from_str("1. 2. 3.").unwrap(), Vec3::new(1., 2., 3.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_str_roundtrip() {
|
||||
let v = Vec3::from_str("1 2 3").unwrap();
|
||||
let s = format!("{}", v);
|
||||
assert_eq!(v, Vec3::from_str(&s).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_dot() {
|
||||
let v0 = Vec3::new(1., 0., 0.);
|
||||
let v1 = Vec3::new(-1., 0., 0.);
|
||||
assert_eq!(dot(v0, v1), v0.length() * v1.length() * PI.cos());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_cross() {
|
||||
let v0 = Vec3::new(1., 0., 0.);
|
||||
let v1 = Vec3::new(0., 1., 0.);
|
||||
assert_eq!(cross(v0, v1), Vec3::new(0., 0., 1.));
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -1 +0,0 @@
|
||||
stanford_dragon.stl
|
||||
@@ -1 +0,0 @@
|
||||
/home/wathiede/3dprint/stl/stanford_dragon-lowres.stl
|
||||
@@ -1,2 +1 @@
|
||||
imports_granularity = "Crate"
|
||||
format_code_in_doc_comments = true
|
||||
@@ -2,16 +2,12 @@
|
||||
name = "tracer"
|
||||
version = "0.1.0"
|
||||
authors = ["Bill Thiede <git@xinu.tv>"]
|
||||
edition = "2021"
|
||||
default-run = "tracer"
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.69"
|
||||
log = "0.4.17"
|
||||
log = "0.4.5"
|
||||
renderer = { path = "../renderer" }
|
||||
stderrlog = "0.4.3"
|
||||
structopt = "0.2.18"
|
||||
strum = "0.24.1"
|
||||
toml = "0.7.2"
|
||||
stderrlog = "0.4.1"
|
||||
structopt = "0.2.10"
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
[scene]
|
||||
width = 768
|
||||
height = 512
|
||||
subsamples = 100
|
||||
|
||||
[camera]
|
||||
lookfrom = [0.0, 50.0, 100.0]
|
||||
lookat = [0.0, 10.0, 0.0]
|
||||
fov = 45
|
||||
aperture = 0.0
|
||||
focus_dist = 10.0
|
||||
time_min = 0.0
|
||||
time_max = 1.0
|
||||
|
||||
[[materials]]
|
||||
name = "light1"
|
||||
type = "isotropic"
|
||||
texture = [20, 10, 10]
|
||||
[[materials]]
|
||||
name = "yellow"
|
||||
type = "isotropic"
|
||||
texture = [1, 1, 0]
|
||||
[[materials]]
|
||||
name = "magenta"
|
||||
type = "lambertian"
|
||||
texture = [1, 0, 1]
|
||||
[[materials]]
|
||||
name = "green"
|
||||
type = "diffuse_light"
|
||||
texture = [0, 1, 0]
|
||||
[[materials]]
|
||||
name = "metal"
|
||||
type = "metal"
|
||||
albedo = [1, 1, 1]
|
||||
fuzzy = 0
|
||||
[[materials]]
|
||||
name = "glass"
|
||||
type = "dielectric"
|
||||
ref_idx = 1.5
|
||||
|
||||
|
||||
[[hitables]]
|
||||
type = "sphere"
|
||||
center = [-30.0, 0.0, 0.0]
|
||||
radius = 10
|
||||
material_name = "yellow"
|
||||
[[hitables]]
|
||||
type = "sphere"
|
||||
center = [30.0, 0.0, 0.0]
|
||||
radius = 10
|
||||
material_name = "green"
|
||||
[[hitables]]
|
||||
type = "sphere"
|
||||
center = [0.0, -10.0, 0.0]
|
||||
radius = 10
|
||||
material_name = "metal"
|
||||
[[hitables]]
|
||||
type = "sphere"
|
||||
center = [0.0, 0.0, -30.0]
|
||||
radius = 10
|
||||
material_name = "magenta"
|
||||
[[hitables]]
|
||||
type = "stl"
|
||||
path = "/net/nasx.h.xinu.tv/x/3dprint/stl/stanford_dragon.stl"
|
||||
scale = 200
|
||||
material_name = "glass"
|
||||
#[[hitables]]
|
||||
#type = "sphere"
|
||||
#center = [0.0, 50.0, -100.0]
|
||||
#radius = 10
|
||||
#material_name = "light1"
|
||||
|
||||
[envmap]
|
||||
path = "/home/wathiede/src/xinu.tv/raytracers/rtiow/renderer/images/52681723945_e1d94d3df9_6k.jpg"
|
||||
@@ -1,2 +0,0 @@
|
||||
imports_granularity = "Crate"
|
||||
format_code_in_doc_comments = true
|
||||
@@ -1,17 +1,14 @@
|
||||
#![warn(unused_extern_crates)]
|
||||
use std::{fs, time::Instant};
|
||||
use std::fs;
|
||||
|
||||
use anyhow::Result;
|
||||
#[cfg(feature = "profile")]
|
||||
use cpuprofiler::PROFILER;
|
||||
use log::info;
|
||||
use stderrlog;
|
||||
use structopt::StructOpt;
|
||||
|
||||
use renderer::{
|
||||
parser::Config,
|
||||
renderer::{render, Model, Opt},
|
||||
};
|
||||
use strum::VariantNames;
|
||||
use renderer::renderer::render;
|
||||
use renderer::renderer::Opt;
|
||||
|
||||
#[cfg(not(feature = "profile"))]
|
||||
struct MockTimer;
|
||||
@@ -39,36 +36,15 @@ impl MockProfiler {
|
||||
#[cfg(not(feature = "profile"))]
|
||||
static PROFILER: MockProfiler = MockProfiler {};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let start_time = Instant::now();
|
||||
fn main() -> Result<(), std::io::Error> {
|
||||
stderrlog::new()
|
||||
.verbosity(3)
|
||||
.timestamp(stderrlog::Timestamp::Millisecond)
|
||||
.init()
|
||||
.unwrap();
|
||||
let opt = Opt::from_args();
|
||||
if opt.model.is_none() && opt.config.is_none() {
|
||||
eprintln!(
|
||||
"--config <path> or --model should be one of {:?}",
|
||||
Model::VARIANTS
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if opt.model.is_some() && opt.config.is_some() {
|
||||
eprintln!("only specify one of --config or --model");
|
||||
return Ok(());
|
||||
}
|
||||
info!("{:#?}", opt);
|
||||
let scene = match (&opt.model, &opt.config) {
|
||||
(Some(model), None) => model.scene(&opt),
|
||||
(None, Some(config)) => {
|
||||
let s = std::fs::read_to_string(config)?;
|
||||
let cfg: Config = toml::from_str(&s)?;
|
||||
println!("{:#?}", cfg);
|
||||
cfg.try_into()?
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
info!("{:?}", opt);
|
||||
let scene = opt.model.scene(&opt);
|
||||
fs::create_dir_all(&opt.output)?;
|
||||
if opt.pprof.is_some() && !cfg!(feature = "profile") {
|
||||
panic!("profiling disabled at compile time, but -pprof specified");
|
||||
@@ -80,13 +56,11 @@ fn main() -> Result<()> {
|
||||
.start(pprof_path.to_str().unwrap().as_bytes())
|
||||
.unwrap();
|
||||
}
|
||||
let res = render(scene, &opt.output, &opt.tev_addr);
|
||||
let res = render(scene, &opt.output);
|
||||
if let Some(pprof_path) = &opt.pprof {
|
||||
info!("Saving pprof to {}", pprof_path.to_string_lossy());
|
||||
PROFILER.lock().unwrap().stop().unwrap();
|
||||
}
|
||||
|
||||
let time_diff = Instant::now() - start_time;
|
||||
info!("Total runtime {} seconds", time_diff.as_secs_f32());
|
||||
Ok(res?)
|
||||
res
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user