Example 1 works

This commit is contained in:
Michael Zhang 2023-01-31 15:19:34 -06:00
parent 00000120dd
commit 000001308c
4 changed files with 27 additions and 8 deletions

View file

@ -7,6 +7,7 @@ use crate::{
vec3::Vec3,
};
/// Parse the input file into a scene
pub fn parse_input_file(path: impl AsRef<Path>) -> Result<Scene> {
let contents = {
let mut contents = String::new();

View file

@ -24,7 +24,7 @@ use crate::scene_data::Object;
use crate::vec3::Vec3;
use crate::view::Rect;
const ARBITRARY_D: f64 = 2.0;
const ARBITRARY_D: f64 = 1.0;
/// Simple raycaster.
#[derive(Parser)]
@ -84,18 +84,21 @@ fn main() -> Result<()> {
lower_right: scene.eye_pos + n * ARBITRARY_D + u * (viewing_width / 2.0) - v * (viewing_height / 2.0),
};
println!("Coords: {view_window:?}");
// Translate image pixels to real-world 3d coords
let pixel_translation = {
let translate_pixel = {
let dx = view_window.upper_right - view_window.upper_left;
let pixel_base_x = dx / scene.image_width as f64;
let dy = view_window.lower_left - view_window.upper_left;
let pixel_base_y = dy / scene.image_height as f64;
println!("Base components in 3D space: {pixel_base_x} / {pixel_base_y}");
move |px: usize, py: usize| {
let x_component = view_window.upper_left + pixel_base_x * px as f64;
let y_component = view_window.upper_left + pixel_base_y * py as f64;
x_component + y_component
let x_component = pixel_base_x * px as f64;
let y_component = pixel_base_y * py as f64;
view_window.upper_left + x_component + y_component
}
};
@ -108,7 +111,7 @@ fn main() -> Result<()> {
let pixels = pixels
.into_par_iter()
.map(|(px, py)| {
let pixel_in_space = pixel_translation(px, py);
let pixel_in_space = translate_pixel(px, py);
let ray = Ray::from_endpoints(scene.eye_pos, pixel_in_space);
let earliest_intersection = scene
@ -132,8 +135,6 @@ fn main() -> Result<()> {
None => scene.bkg_color,
};
// println!("({px}, {py}): {intersection:?}\t{ray:?} {sphere:?}");
pixel_color.to_pixel()
})
.collect::<Vec<_>>();

View file

@ -82,6 +82,7 @@ mod tests {
let sphere = Sphere {
center: Vec3::new(0.0, 0.0, -10.0),
radius: 4.0,
material: 0,
};
let point = ray.intersects_at(&sphere).map(|t| ray.eval(t));
@ -99,6 +100,7 @@ mod tests {
let sphere = Sphere {
center: Vec3::new(0.0, 0.0, -10.0),
radius: 4.0,
material: 0,
};
// oops! In this case, the ray does not intersect the sphere.

View file

@ -1,4 +1,5 @@
use std::ops::{Add, Div, Mul, Sub};
use std::fmt;
use num::Float;
@ -17,6 +18,20 @@ impl<T> Vec3<T> {
}
}
impl<T: fmt::Display> fmt::Display for Vec3<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("(")?;
self.x.fmt(f)?;
f.write_str(", ")?;
self.y.fmt(f)?;
f.write_str(", ")?;
self.z.fmt(f)?;
f.write_str(")")?;
Ok(())
}
}
impl<T: Float> Vec3<T> {
/// Cross product on floats
pub fn cross(u: Self, v: Self) -> Self {