Changed UI and integrated rays into camera

This commit is contained in:
STP
2023-11-25 03:15:59 -05:00
parent ab284e8e98
commit 137fb9f6d7
10 changed files with 313 additions and 183 deletions

View File

@@ -1,3 +1,65 @@
// engine
// .register_type::<Vector3<f32>>()
// .register_fn("V", Vector3::<f32>::new);
// engine
// .register_type::<Point3<f32>>()
// .register_fn("P", Point3::<f32>::new);
// engine
// .register_type::<Scene>()
// .register_fn("Scene", Scene::empty)
// .register_fn("addNode", Scene::add_node)
// .register_fn("addLight", Scene::add_light);
// engine
// .register_type::<Node>()
// .register_fn("Node", Node::new)
// .register_fn("translate", Node::translate)
// .register_fn("rotate", Node::rotate)
// .register_fn("scale", Node::scale);
// engine
// .register_type::<Camera>()
// .register_fn("Camera", Camera::new);
// engine
// .register_type::<Light>()
// .register_fn("Light", Light::new);
// engine
// .register_type::<Material>()
// .register_fn("Material", Material::new)
// .register_fn("MaterialRed", Material::red)
// .register_fn("MaterialBlue", Material::blue)
// .register_fn("MaterialGreen", Material::green)
// .register_fn("MaterialMagenta", Material::magenta)
// .register_fn("MaterialTurquoise", Material::turquoise);
// engine
// .register_type::<Sphere>()
// .register_fn("Sphere", Sphere::new)
// .register_fn("SphereUnit", Sphere::unit);
// engine
// .register_type::<Cube>()
// .register_fn("Cube", Cube::new)
// .register_fn("CubeUnit", Cube::unit);
// engine
// .register_type::<Cone>()
// .register_fn("Cone", Cone::new)
// .register_fn("ConeUnit", Cone::unit);
// engine
// .register_type::<Cylinder>()
// .register_fn("Cylinder", Cylinder::new);
// engine
// .register_type::<Circle>()
// .register_fn("Circle", Circle::new)
// .register_fn("CircleUnit", Circle::unit);
// engine
// .register_type::<Rectangle>()
// .register_fn("Rectangle", Rectangle::new)
// .register_fn("RectangleUnit", Rectangle::unit);
// engine
// .register_type::<SteinerSurface>()
// .register_fn("Steiner", SteinerSurface::new);
// engine
// .register_type::<Torus>()
// .register_fn("Torus", Torus::new);
let scene = Scene(); let scene = Scene();
let eye = P(0.0, 0.0, 3.0); let eye = P(0.0, 0.0, 3.0);
@@ -19,7 +81,7 @@ scene.addLight(light2);
// let node = Node(sphere); // let node = Node(sphere);
// scene.addNode(node); // scene.addNode(node);
let stein = Stein(5.0,10.0, material); let stein = Steiner(material);
let node = Node(stein); let node = Node(stein);
scene.addNode(node); scene.addNode(node);

View File

@@ -5,53 +5,76 @@ use nalgebra::{Matrix4, Perspective3, Point3, Unit, Vector3};
const ZNEAR: f32 = EPSILON; const ZNEAR: f32 = EPSILON;
const ZFAR: f32 = INFINITY; const ZFAR: f32 = INFINITY;
#[allow(dead_code)]
#[derive(Clone)] #[derive(Clone)]
pub struct Camera { pub struct Camera {
eye: Point3<f32>, eye: Point3<f32>,
target: Point3<f32>, target: Point3<f32>,
up: Vector3<f32>, up: Vector3<f32>,
fovy: f32, fovy: f32,
aspect: f32, width: u32,
height: u32,
matrix: Matrix4<f32>, matrix: Matrix4<f32>,
inverse: Matrix4<f32>, inverse: Matrix4<f32>,
pub rays: Vec<Ray>,
} }
#[allow(dead_code)]
impl Camera { impl Camera {
pub fn new( pub fn new(
eye: Point3<f32>, eye: Point3<f32>,
target: Point3<f32>, target: Point3<f32>,
up: Vector3<f32>, up: Vector3<f32>,
width: u32,
height: u32,
fovy: f32, fovy: f32,
aspect: f32,
) -> Self { ) -> Self {
let (matrix, inverse) = Camera::build_matrix_and_inverse(&eye, &target, &up, fovy, aspect); let (matrix, inverse) = build_matrix_and_inverse(&eye, &target, &up, width, height, fovy);
let rays = cast_rays(&eye, &target, &up, width, height, fovy);
Camera { Camera {
eye, eye,
target, target,
up, up,
width,
height,
fovy, fovy,
matrix, matrix,
inverse, inverse,
aspect, rays,
} }
} }
pub fn build_matrix_and_inverse( pub fn unit() -> Self {
eye: &Point3<f32>, let eye = Point3::new(0.0, 0.0, 1.0);
target: &Point3<f32>, let target = Point3::new(0.0, 0.0, 0.0);
up: &Vector3<f32>, let up = Vector3::new(0.0, 1.0, 0.0);
fovy: f32, Camera::new(eye, target, up, 1, 1, 90.0)
aspect: f32,
) -> (Matrix4<f32>, Matrix4<f32>) {
let view = Matrix4::look_at_lh(eye, target, up);
let proj = Perspective3::new(aspect, fovy, ZNEAR, ZFAR);
let matrix = proj.as_matrix() * view;
let inverse = view.try_inverse().expect("No view") * proj.inverse();
(matrix, inverse)
} }
pub fn cast_rays(&self, width: u32, height: u32) -> Vec<Ray> { pub fn cast_rays(&self) -> Vec<Ray> {
let aspect = width as f64 / height as f64; cast_rays(
&self.eye,
&self.target,
&self.up,
self.width,
self.height,
self.fovy,
)
}
pub fn build_matrix_and_inverse(&self) -> (Matrix4<f32>, Matrix4<f32>) {
build_matrix_and_inverse(
&self.eye,
&self.target,
&self.up,
self.width,
self.height,
self.fovy,
)
}
pub fn cast_ray(&self, x: u32, y: u32) -> Ray {
let aspect = self.width as f64 / self.height as f64;
let fovy_radians = (self.fovy as f64).to_radians(); let fovy_radians = (self.fovy as f64).to_radians();
let fovh_radians = 2.0 * ((fovy_radians / 2.0).tan() * aspect).atan(); let fovh_radians = 2.0 * ((fovy_radians / 2.0).tan() * aspect).atan();
let view_direction = (self.target - self.eye).normalize(); let view_direction = (self.target - self.eye).normalize();
@@ -60,8 +83,67 @@ impl Camera {
let h_width = 2.0 * (fovh_radians / 2.0).tan(); let h_width = 2.0 * (fovh_radians / 2.0).tan();
let v_height = 2.0 * (fovy_radians / 2.0).tan(); let v_height = 2.0 * (fovy_radians / 2.0).tan();
//All good //All good
let d_hor_vec = hor * (h_width / width as f64) as f32; let d_hor_vec = hor * (h_width / self.width as f64) as f32;
let d_vert_vec = vert * (v_height / height as f64) as f32; let d_vert_vec = vert * (v_height / self.height as f64) as f32;
let half_w = self.width as i32 / 2;
let half_h = self.height as i32 / 2;
let horizontal = (x as i32 - half_w) as f32 * (d_hor_vec);
let vertical = (-(y as i32) + half_h) as f32 * (d_vert_vec);
let direction = view_direction + horizontal + vertical;
Ray::new(self.eye, Unit::new_normalize(direction))
}
pub fn set_position(&mut self, eye: Point3<f32>) {
self.eye = eye;
}
pub fn set_size(&mut self, width: u32, height: u32) {
self.width = width;
self.height = height;
self.rays = self.cast_rays();
(self.matrix, self.inverse) = self.build_matrix_and_inverse();
}
}
fn build_matrix_and_inverse(
eye: &Point3<f32>,
target: &Point3<f32>,
up: &Vector3<f32>,
width: u32,
height: u32,
fovy: f32,
) -> (Matrix4<f32>, Matrix4<f32>) {
let view = Matrix4::look_at_lh(eye, target, up);
let aspect = width as f32 / height as f32;
let proj = Perspective3::new(aspect, fovy, ZNEAR, ZFAR);
let matrix = proj.as_matrix() * view;
let inverse = view.try_inverse().expect("No view") * proj.inverse();
(matrix, inverse)
}
fn cast_rays(
eye: &Point3<f32>,
target: &Point3<f32>,
up: &Vector3<f32>,
width: u32,
height: u32,
fovy: f32,
) -> Vec<Ray> {
let aspect = width as f64 / height as f64;
let fovy_radians = (fovy as f64).to_radians();
let fovh_radians = 2.0 * ((fovy_radians / 2.0).tan() * aspect).atan();
let view_direction = (target - eye).normalize();
let hor = (view_direction.cross(&up)).normalize();
let vert = (view_direction.cross(&hor)).normalize();
let h_width = 2.0 * (fovh_radians / 2.0).tan() as f32;
let v_height = 2.0 * (fovy_radians / 2.0).tan() as f32;
//All good
let d_hor_vec = hor * (h_width / width as f32);
let d_vert_vec = vert * (v_height / height as f32);
let mut rays = Vec::with_capacity(width as usize * height as usize); let mut rays = Vec::with_capacity(width as usize * height as usize);
@@ -74,39 +156,9 @@ impl Camera {
let vertical = (-j + half_h) as f32 * (d_vert_vec); let vertical = (-j + half_h) as f32 * (d_vert_vec);
let direction = view_direction + horizontal + vertical; let direction = view_direction + horizontal + vertical;
let ray = Ray::new(self.eye, Unit::new_normalize(direction)); let ray = Ray::new(eye.clone(), Unit::new_normalize(direction));
rays.push(ray); rays.push(ray);
} }
} }
rays rays
}
pub fn cast_ray(&self, width: u32, height: u32, x: u32, y: u32) -> Ray {
let aspect = width as f64 / height as f64;
let fovy_radians = (self.fovy as f64).to_radians();
let fovh_radians = 2.0 * ((fovy_radians / 2.0).tan() * aspect).atan();
let view_direction = (self.target - self.eye).normalize();
let hor = (view_direction.cross(&self.up)).normalize();
let vert = (view_direction.cross(&hor)).normalize();
let h_width = 2.0 * (fovh_radians / 2.0).tan();
let v_height = 2.0 * (fovy_radians / 2.0).tan();
//All good
let d_hor_vec = hor * (h_width / width as f64) as f32;
let d_vert_vec = vert * (v_height / height as f64) as f32;
let half_w = width as i32 / 2;
let half_h = height as i32 / 2;
let horizontal = (x as i32 - half_w) as f32 * (d_hor_vec);
let vertical = (-(y as i32) + half_h) as f32 * (d_vert_vec);
let direction = view_direction + horizontal + vertical;
let ray = Ray::new(self.eye, Unit::new_normalize(direction));
Ray::new(self.eye, Unit::new_normalize(direction))
}
pub fn set_position(&mut self, eye: Point3<f32>) {
self.eye = eye;
}
} }

View File

@@ -1,9 +1,9 @@
use nalgebra::Point3; use crate::{camera::Camera, state::INIT_FILE, UP_VECTOR, ZERO_VECTOR};
use imgui::*;
use nalgebra::{Point3, Vector3};
use pixels::{wgpu, PixelsContext}; use pixels::{wgpu, PixelsContext};
use std::time::Instant; use std::time::Instant;
const INIT_FILE: &str = "scene.rhai";
const BUFFER_PROPORTION_INIT: f32 = 1.0; const BUFFER_PROPORTION_INIT: f32 = 1.0;
const BUFFER_PROPORTION_MIN: f32 = 0.5; const BUFFER_PROPORTION_MIN: f32 = 0.5;
const BUFFER_PROPORTION_MAX: f32 = 1.0; const BUFFER_PROPORTION_MAX: f32 = 1.0;
@@ -12,14 +12,14 @@ const RAYS_INIT: i32 = 9000;
const RAYS_MIN: i32 = 100; const RAYS_MIN: i32 = 100;
const RAYS_MAX: i32 = 10000; const RAYS_MAX: i32 = 10000;
const CAMERA_MIN: f32 = -10.0; const CAMERA_MIN_FOV: f32 = 10.0;
const CAMERA_MAX: f32 = 10.0; const CAMERA_MAX_FOV: f32 = 160.0;
const CAMERA_INIT: f32 = 5.0; const CAMERA_INIT: f32 = 5.0;
/// Manages all state required for rendering Dear ImGui over `Pixels`test. /// Manages all state required for rendering Dear ImGui over `Pixels`test.
pub enum GuiEvent { pub enum GuiEvent {
BufferResize, BufferResize(f32),
CameraRelocate, CameraUpdate(Camera),
SceneLoad(String), SceneLoad(String),
} }
@@ -32,10 +32,16 @@ pub struct Gui {
pub event: Option<GuiEvent>, pub event: Option<GuiEvent>,
pub filename: String, script_filename: String,
script: String,
pub ray_num: i32, pub ray_num: i32,
pub buffer_proportion: f32,
pub camera_eye: Point3<f32>, buffer_proportion: f32,
camera_eye: [f32; 3],
camera_target: [f32; 3],
camera_up: [f32; 3],
camera_fov: f32,
} }
impl Gui { impl Gui {
@@ -85,10 +91,15 @@ impl Gui {
last_frame: Instant::now(), last_frame: Instant::now(),
last_cursor: None, last_cursor: None,
event: None, event: None,
filename: String::from(INIT_FILE), script_filename: String::from(INIT_FILE),
script: String::new(),
ray_num: RAYS_INIT, ray_num: RAYS_INIT,
buffer_proportion: BUFFER_PROPORTION_INIT, buffer_proportion: BUFFER_PROPORTION_INIT,
camera_eye: Point3::new(CAMERA_INIT, CAMERA_INIT, CAMERA_INIT),
camera_eye: [CAMERA_INIT, CAMERA_INIT, CAMERA_INIT],
camera_target: ZERO_VECTOR.into(),
camera_up: UP_VECTOR.into(),
camera_fov: 110.0,
} }
} }
@@ -121,41 +132,62 @@ impl Gui {
self.platform.prepare_render(ui, window); self.platform.prepare_render(ui, window);
} }
// Draw windows and GUI elements here //Top Menu Bar
let mut about_open = false; let mut about_open = false;
ui.main_menu_bar(|| { ui.main_menu_bar(|| {
ui.menu("Help", || { ui.menu("Help", || {
about_open = ui.menu_item("About..."); about_open = ui.menu_item("About...");
}); });
}); });
ui.slider("# Rays: ", RAYS_MIN, RAYS_MAX, &mut self.ray_num);
//Raytracing options
if CollapsingHeader::new("Raytracer").build(ui) {
//Ray Renderer
ui.slider("# Rays: ", RAYS_MIN, RAYS_MAX, &mut self.ray_num);
//Buffer Options
ui.slider( ui.slider(
"% Buffer: ", "% Buffer: ",
BUFFER_PROPORTION_MIN, BUFFER_PROPORTION_MIN,
BUFFER_PROPORTION_MAX, BUFFER_PROPORTION_MAX,
&mut self.buffer_proportion, &mut self.buffer_proportion,
); );
if ui.button("Change Buffer") { //Apply changes
self.event = Some(GuiEvent::BufferResize); if ui.button("Apply") {
self.event = Some(GuiEvent::BufferResize(self.buffer_proportion));
}; };
}
ui.text("Vector3 Input:"); //Camera options
if CollapsingHeader::new("Camera").build(ui) {
ui.text("Camera options:");
ui.input_float3("Eye", &mut self.camera_eye).build();
ui.input_float3("Target", &mut self.camera_target).build();
ui.input_float3("Up", &mut self.camera_up).build();
ui.slider("fov", CAMERA_MIN_FOV, CAMERA_MAX_FOV, &mut self.camera_fov);
// Create three input fields for x, y, and z components // Create three input fields for x, y, and z components
ui.slider("X", CAMERA_MIN, CAMERA_MAX, &mut self.camera_eye.coords[0]);
ui.slider("Y", CAMERA_MIN, CAMERA_MAX, &mut self.camera_eye.coords[1]);
ui.slider("Z", CAMERA_MIN, CAMERA_MAX, &mut self.camera_eye.coords[2]);
// Check if any component of the Vector3 has changed
if ui.button("Apply Camera") { if ui.button("Apply Camera") {
println!("Camera changed: {:?}", self.camera_eye); println!("Camera changed: {:?}", self.camera_eye);
self.camera_eye = Point3::from(self.camera_eye); let camera = Camera::new(
self.event = Some(GuiEvent::CameraRelocate); Point3::from_slice(&self.camera_eye),
Point3::from_slice(&self.camera_target),
Vector3::from_row_slice(&self.camera_up),
1,
1,
self.camera_fov,
);
self.event = Some(GuiEvent::CameraUpdate(camera));
} }
}
//Load file from //Scripting
ui.input_text("Scene file", &mut self.filename).build(); if CollapsingHeader::new("Scripting").build(ui) {
if ui.button("Apply File") { //Import from file (We just want to replace the contents of self.script)
self.event = Some(GuiEvent::SceneLoad(self.filename.clone())); ui.input_text("Scene file", &mut self.script_filename)
.build();
if ui.button("Import from File") {
self.event = Some(GuiEvent::SceneLoad(self.script_filename.clone()));
}
//Script block
ui.input_text_multiline("script", &mut self.script, [300., 100.])
.build();
} }
// Render Dear ImGui with WGPU // Render Dear ImGui with WGPU

View File

@@ -15,9 +15,8 @@ impl Light {
falloff, falloff,
} }
} }
pub fn white() -> Self { pub fn white(position: Point3<f32>) -> Self {
let colour = Vector3::new(1.0, 1.0, 1.0); let colour = Vector3::new(1.0, 1.0, 1.0);
let position = Point3::new(0.0, 0.0, 0.0);
let falloff = Vector3::new(1.0, 0.0, 0.0); let falloff = Vector3::new(1.0, 0.0, 0.0);
Light::new(position, colour, falloff) Light::new(position, colour, falloff)
} }

View File

@@ -4,6 +4,8 @@ use error_iter::ErrorIter;
const EPSILON: f32 = 1e-6; const EPSILON: f32 = 1e-6;
const INFINITY: f32 = f32::MAX; const INFINITY: f32 = f32::MAX;
const EPSILON_VECTOR: Vector3<f32> = Vector3::new(EPSILON, EPSILON, EPSILON); const EPSILON_VECTOR: Vector3<f32> = Vector3::new(EPSILON, EPSILON, EPSILON);
static ZERO_VECTOR: Vector3<f32> = Vector3::new(0.0, 0.0, 0.0);
static UP_VECTOR: Vector3<f32> = Vector3::new(0.0, 1.0, 0.0);
use log::error; use log::error;
use std::env; use std::env;

View File

@@ -1013,52 +1013,52 @@ impl Primitive for Torus {
let d = ray.b.y; let d = ray.b.y;
let e = ray.a.z; let e = ray.a.z;
let f = ray.b.z; let f = ray.b.z;
let r = self.inner_rad; let r1 = self.inner_rad;
let R = self.outer_rad; let r2 = self.outer_rad;
let t0 = R.powf(2.0).powf(2.0) - 2.0 * R.powf(2.0) * a.powf(2.0) + a.powf(2.0).powf(2.0) let t0 = r2.powf(2.0).powf(2.0) - 2.0 * r2.powf(2.0) * a.powf(2.0) + a.powf(2.0).powf(2.0)
- 2.0 * R.powf(2.0) * c.powf(2.0) - 2.0 * r2.powf(2.0) * c.powf(2.0)
+ 2.0 * a.powf(2.0) * c.powf(2.0) + 2.0 * a.powf(2.0) * c.powf(2.0)
+ c.powf(2.0).powf(2.0) + c.powf(2.0).powf(2.0)
+ 2.0 * R.powf(2.0) * e.powf(2.0) + 2.0 * r2.powf(2.0) * e.powf(2.0)
+ 2.0 * a.powf(2.0) * e.powf(2.0) + 2.0 * a.powf(2.0) * e.powf(2.0)
+ 2.0 * c.powf(2.0) * e.powf(2.0) + 2.0 * c.powf(2.0) * e.powf(2.0)
+ e.powf(2.0).powf(2.0) + e.powf(2.0).powf(2.0)
- 2.0 * R.powf(2.0) * r.powf(2.0) - 2.0 * r2.powf(2.0) * r1.powf(2.0)
- 2.0 * a.powf(2.0) * r.powf(2.0) - 2.0 * a.powf(2.0) * r1.powf(2.0)
- 2.0 * c.powf(2.0) * r.powf(2.0) - 2.0 * c.powf(2.0) * r1.powf(2.0)
- 2.0 * e.powf(2.0) * r.powf(2.0) - 2.0 * e.powf(2.0) * r1.powf(2.0)
+ r.powf(2.0).powf(2.0); + r1.powf(2.0).powf(2.0);
let t1 = -4.0 * R.powf(2.0) * a * b + 4.0 * a.powf(3.0) * b + 4.0 * a * b * c.powf(2.0) let t1 = -4.0 * r2.powf(2.0) * a * b + 4.0 * a.powf(3.0) * b + 4.0 * a * b * c.powf(2.0)
- 4.0 * R.powf(2.0) * c * d - 4.0 * r2.powf(2.0) * c * d
+ 4.0 * a.powf(2.0) * c * d + 4.0 * a.powf(2.0) * c * d
+ 4.0 * c.powf(3.0) * d + 4.0 * c.powf(3.0) * d
+ 4.0 * a * b * e.powf(2.0) + 4.0 * a * b * e.powf(2.0)
+ 4.0 * c * d * e.powf(2.0) + 4.0 * c * d * e.powf(2.0)
+ 4.0 * R.powf(2.0) * e * f + 4.0 * r2.powf(2.0) * e * f
+ 4.0 * a.powf(2.0) * e * f + 4.0 * a.powf(2.0) * e * f
+ 4.0 * c.powf(2.0) * e * f + 4.0 * c.powf(2.0) * e * f
+ 4.0 * e.powf(3.0) * f + 4.0 * e.powf(3.0) * f
- 4.0 * a * b * r.powf(2.0) - 4.0 * a * b * r1.powf(2.0)
- 4.0 * c * d * r.powf(2.0) - 4.0 * c * d * r1.powf(2.0)
- 4.0 * e * f * r.powf(2.0); - 4.0 * e * f * r1.powf(2.0);
let t2 = -2.0 * R.powf(2.0) * b.powf(2.0) let t2 = -2.0 * r2.powf(2.0) * b.powf(2.0)
+ 6.0 * a.powf(2.0) * b.powf(2.0) + 6.0 * a.powf(2.0) * b.powf(2.0)
+ 2.0 * b.powf(2.0) * c.powf(2.0) + 2.0 * b.powf(2.0) * c.powf(2.0)
+ 8.0 * a * b * c * d + 8.0 * a * b * c * d
- 2.0 * R.powf(2.0) * d.powf(2.0) - 2.0 * r2.powf(2.0) * d.powf(2.0)
+ 2.0 * a.powf(2.0) * d.powf(2.0) + 2.0 * a.powf(2.0) * d.powf(2.0)
+ 6.0 * c.powf(2.0) * d.powf(2.0) + 6.0 * c.powf(2.0) * d.powf(2.0)
+ 2.0 * b.powf(2.0) * e.powf(2.0) + 2.0 * b.powf(2.0) * e.powf(2.0)
+ 2.0 * d.powf(2.0) * e.powf(2.0) + 2.0 * d.powf(2.0) * e.powf(2.0)
+ 8.0 * a * b * e * f + 8.0 * a * b * e * f
+ 8.0 * c * d * e * f + 8.0 * c * d * e * f
+ 2.0 * R.powf(2.0) * f.powf(2.0) + 2.0 * r2.powf(2.0) * f.powf(2.0)
+ 2.0 * a.powf(2.0) * f.powf(2.0) + 2.0 * a.powf(2.0) * f.powf(2.0)
+ 2.0 * c.powf(2.0) * f.powf(2.0) + 2.0 * c.powf(2.0) * f.powf(2.0)
+ 6.0 * e.powf(2.0) * f.powf(2.0) + 6.0 * e.powf(2.0) * f.powf(2.0)
- 2.0 * b.powf(2.0) * r.powf(2.0) - 2.0 * b.powf(2.0) * r1.powf(2.0)
- 2.0 * d.powf(2.0) * r.powf(2.0) - 2.0 * d.powf(2.0) * r1.powf(2.0)
- 2.0 * f.powf(2.0) * r.powf(2.0); - 2.0 * f.powf(2.0) * r1.powf(2.0);
let t3 = 4.0 * a * b.powf(3.0) let t3 = 4.0 * a * b.powf(3.0)
+ 4.0 * b.powf(2.0) * c * d + 4.0 * b.powf(2.0) * c * d
+ 4.0 * a * b * d.powf(2.0) + 4.0 * a * b * d.powf(2.0)
@@ -1091,11 +1091,12 @@ impl Primitive for Torus {
//Now we have the smallest non-zero t //Now we have the smallest non-zero t
let point = ray.at_t(t); let point = ray.at_t(t);
let (x, y, z) = (point.x, point.y, point.z); let (x, y, z) = (point.x, point.y, point.z);
let dx = 4.0 * (R.powf(2.0) - r.powf(2.0) + x.powf(2.0) + y.powf(2.0) + z.powf(2.0)) * R let dx = 4.0 * (r2.powf(2.0) - r1.powf(2.0) + x.powf(2.0) + y.powf(2.0) + z.powf(2.0)) * r2
- 8.0 * (x.powf(2.0) + y.powf(2.0)) * R; - 8.0 * (x.powf(2.0) + y.powf(2.0)) * r2;
let dy = -4.0 * (R.powf(2.0) - r.powf(2.0) + x.powf(2.0) + y.powf(2.0) + z.powf(2.0)) * r; let dy =
let dz = -8.0 * R.powf(2.0) * x -4.0 * (r2.powf(2.0) - r1.powf(2.0) + x.powf(2.0) + y.powf(2.0) + z.powf(2.0)) * r1;
+ 4.0 * (R.powf(2.0) - r.powf(2.0) + x.powf(2.0) + y.powf(2.0) + z.powf(2.0)) * x; let dz = -8.0 * r2.powf(2.0) * x
+ 4.0 * (r2.powf(2.0) - r1.powf(2.0) + x.powf(2.0) + y.powf(2.0) + z.powf(2.0)) * x;
let normal = Unit::new_normalize(Vector3::new(dx, dy, dz)); let normal = Unit::new_normalize(Vector3::new(dx, dy, dz));
Some(Intersection { Some(Intersection {

View File

@@ -6,6 +6,7 @@ use crate::{
}; };
use nalgebra::{Point3, Unit, Vector3}; use nalgebra::{Point3, Unit, Vector3};
#[derive(Clone)]
pub struct Ray { pub struct Ray {
pub a: Point3<f32>, pub a: Point3<f32>,
pub b: Unit<Vector3<f32>>, pub b: Unit<Vector3<f32>>,
@@ -15,6 +16,11 @@ impl Ray {
pub fn new(a: Point3<f32>, b: Unit<Vector3<f32>>) -> Ray { pub fn new(a: Point3<f32>, b: Unit<Vector3<f32>>) -> Ray {
Ray { a, b } Ray { a, b }
} }
pub fn unit() -> Ray {
let a = Point3::new(0.0, 0.0, 0.0);
let b = Unit::new_normalize(Vector3::new(0.0, 1.0, 0.0));
Ray { a, b }
}
pub fn at_t(&self, t: f32) -> Point3<f32> { pub fn at_t(&self, t: f32) -> Point3<f32> {
self.a + self.b.into_inner() * (t + EPSILON) self.a + self.b.into_inner() * (t + EPSILON)
} }

View File

@@ -1,9 +1,7 @@
use crate::{light::Light, primitive::Intersection, scene::*}; use crate::{light::Light, primitive::Intersection, scene::*, ZERO_VECTOR};
use nalgebra::{Unit, Vector3}; use nalgebra::{Unit, Vector3};
static ZERO_VECTOR: Vector3<f32> = Vector3::new(0.0, 0.0, 0.0);
// Function to shade a point in the scene using Phong shading model // Function to shade a point in the scene using Phong shading model
pub fn phong_shade_point(scene: &Scene, intersect: &Intersection) -> Vector3<u8> { pub fn phong_shade_point(scene: &Scene, intersect: &Intersection) -> Vector3<u8> {
let Intersection { let Intersection {

View File

@@ -39,7 +39,6 @@ pub struct Scene {
pub materials: Vec<Material>, pub materials: Vec<Material>,
pub lights: Vec<Light>, pub lights: Vec<Light>,
pub cameras: Vec<Camera>, pub cameras: Vec<Camera>,
pub camera: Camera,
} }
impl Scene { impl Scene {
@@ -50,13 +49,6 @@ impl Scene {
materials: Vec::new(), materials: Vec::new(),
lights: Vec::new(), lights: Vec::new(),
cameras: Vec::new(), cameras: Vec::new(),
camera: Camera::new(
Point3::new(0.0, 0.0, -10.0),
Point3::new(0.0, 0.0, 0.0),
Vector3::new(0.0, 0.0, -1.0),
120.0,
1.0,
),
} }
} }
fn add_node(&mut self, node: Node) { fn add_node(&mut self, node: Node) {
@@ -71,15 +63,8 @@ impl Scene {
fn add_camera(&mut self, camera: Camera) { fn add_camera(&mut self, camera: Camera) {
self.cameras.push(camera); self.cameras.push(camera);
} }
fn set_camera(&mut self, camera: Camera) {
self.camera = camera;
}
fn get_camera(&self) -> &Camera { pub fn from_rhai(script: &str) -> Result<Scene, Box<EvalAltResult>> {
&self.camera
}
pub fn from_script(filename: &str) -> Result<Scene, Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
engine engine
@@ -144,7 +129,7 @@ impl Scene {
.register_type::<Torus>() .register_type::<Torus>()
.register_fn("Torus", Torus::new); .register_fn("Torus", Torus::new);
let scene: Scene = engine.eval_file(filename.into())?; let scene: Scene = engine.eval(script.into())?;
Ok(scene) Ok(scene)
} }
} }

View File

@@ -1,6 +1,7 @@
//Use linear algebra module //Use linear algebra module
use crate::{gui::Gui, ray::Ray, scene::Scene}; use crate::camera::Camera;
use crate::{gui::Gui, scene::Scene};
use crate::{gui::GuiEvent, log_error}; use crate::{gui::GuiEvent, log_error};
use std::error::Error; use std::error::Error;
@@ -18,7 +19,7 @@ const START_WIDTH: i32 = 800;
const START_HEIGHT: i32 = 800; const START_HEIGHT: i32 = 800;
const COLOUR_CLEAR: [u8; 4] = [0x22, 0x00, 0x11, 0xff]; const COLOUR_CLEAR: [u8; 4] = [0x22, 0x00, 0x11, 0xff];
const INIT_FILE: &str = "test.rhai"; pub const INIT_FILE: &str = "scene.rhai";
pub fn run() -> Result<(), Box<dyn Error>> { pub fn run() -> Result<(), Box<dyn Error>> {
let event_loop = EventLoop::new(); let event_loop = EventLoop::new();
@@ -27,8 +28,7 @@ pub fn run() -> Result<(), Box<dyn Error>> {
let gui = Gui::new(&window, &pixels); let gui = Gui::new(&window, &pixels);
let mut state = State::new(window, pixels, gui); let mut state = State::new(window, pixels, gui);
state.load_scene(&String::from(INIT_FILE)); state.resize_buffer(1.0)?;
state.resize_buffer()?;
event_loop.run(move |event, _, control_flow| { event_loop.run(move |event, _, control_flow| {
state.gui.handle_event(&state.window, &event); state.gui.handle_event(&state.window, &event);
@@ -86,7 +86,7 @@ fn handle_window_event(
pub struct State { pub struct State {
scene: Scene, scene: Scene,
rays: Vec<Ray>, camera: Camera,
window: Window, window: Window,
buffer_width: u32, buffer_width: u32,
buffer_height: u32, buffer_height: u32,
@@ -96,29 +96,28 @@ pub struct State {
} }
impl State { impl State {
pub fn update_scene_from_file(&mut self, filename: &String) -> Result<(), Box<dyn Error>> { pub fn import_rhai_from_file(&mut self, filename: &str) -> Result<(), Box<dyn Error>> {
self.scene = Scene::from_script(filename)?.into(); let script = std::fs::read_to_string(filename)?;
let window_size = self.window.inner_size(); self.scene = Scene::from_rhai(&script)?.into();
self.rays = self Ok(())
.scene }
.camera
.cast_rays(window_size.width, window_size.height); pub fn import_rhai(&mut self, script: &str) -> Result<(), Box<dyn Error>> {
self.scene = Scene::from_rhai(&script)?.into();
Ok(()) Ok(())
} }
pub fn new(window: Window, pixels: Pixels, gui: Gui) -> Self { pub fn new(window: Window, pixels: Pixels, gui: Gui) -> Self {
let scene = Scene::empty(); let scene = Scene::empty();
let window_size = window.inner_size(); let window_size = window.inner_size();
let rays = scene let camera = Camera::unit();
.camera
.cast_rays(window_size.width, window_size.height);
Self { Self {
scene, scene,
rays, camera,
window, window,
buffer_width: (window_size.width as f32 * gui.buffer_proportion) as u32, buffer_width: window_size.width as u32,
buffer_height: (window_size.height as f32 * gui.buffer_proportion) as u32, buffer_height: window_size.height as u32,
pixels: Arc::new(Mutex::new(pixels)), pixels: Arc::new(Mutex::new(pixels)),
gui, gui,
index: 0, index: 0,
@@ -128,34 +127,27 @@ impl State {
fn update(&mut self) -> Result<(), Box<dyn Error>> { fn update(&mut self) -> Result<(), Box<dyn Error>> {
if let Some(event) = self.gui.event.take() { if let Some(event) = self.gui.event.take() {
match event { match event {
GuiEvent::BufferResize | GuiEvent::CameraRelocate => self.resize_buffer()?, GuiEvent::BufferResize(proportion) => self.resize_buffer(proportion)?,
GuiEvent::SceneLoad(filename) => self.load_scene(&filename), GuiEvent::CameraUpdate(camera) => self.set_camera(camera),
GuiEvent::SceneLoad(script) => self.import_rhai(&script)?,
} }
}; };
Ok(()) Ok(())
} }
fn resize_buffer(&mut self) -> Result<(), Box<dyn Error>> { fn resize_buffer(&mut self, proportion: f32) -> Result<(), Box<dyn Error>> {
let size = self.window.inner_size(); let size = self.window.inner_size();
self.buffer_width = (size.width as f32 * self.gui.buffer_proportion) as u32;
self.buffer_height = (size.height as f32 * self.gui.buffer_proportion) as u32; self.buffer_width = (size.width as f32 * proportion) as u32;
self.buffer_height = (size.height as f32 * proportion) as u32;
self.camera.set_size(self.buffer_width, self.buffer_height);
self.clear()?; self.clear()?;
let mut pixels = self.pixels.lock().unwrap(); let mut pixels = self.pixels.lock().unwrap();
pixels.resize_buffer(self.buffer_width, self.buffer_height)?; pixels.resize_buffer(self.buffer_width, self.buffer_height)?;
Ok(()) Ok(())
} }
fn load_scene(&mut self, filename: &String) {
println!("Reading {}", filename);
match self.update_scene_from_file(filename) {
Err(e) => println!("{}", e),
Ok(()) => {
println!("Loaded file: {filename}");
self.render().expect("Could not draw new file");
}
}
}
fn resize(&mut self, size: &PhysicalSize<u32>) -> Result<(), Box<dyn Error>> { fn resize(&mut self, size: &PhysicalSize<u32>) -> Result<(), Box<dyn Error>> {
let mut pixels = self.pixels.lock().unwrap(); let mut pixels = self.pixels.lock().unwrap();
pixels.resize_surface(size.width, size.height)?; pixels.resize_surface(size.width, size.height)?;
@@ -175,7 +167,8 @@ impl State {
fn draw(&mut self) -> Result<(), Box<dyn Error>> { fn draw(&mut self) -> Result<(), Box<dyn Error>> {
for _ in 0..self.gui.ray_num { for _ in 0..self.gui.ray_num {
let i = self.index as usize; let i = self.index as usize;
let colour = self.rays[i].shade_ray(&self.scene); let camera = &self.camera;
let colour = camera.rays[i].shade_ray(&self.scene);
let rgba = colour.map_or(COLOUR_CLEAR, |colour| [colour.x, colour.y, colour.z, 255]); let rgba = colour.map_or(COLOUR_CLEAR, |colour| [colour.x, colour.y, colour.z, 255]);
let mut pixels = self.pixels.lock().unwrap(); let mut pixels = self.pixels.lock().unwrap();
let frame = pixels.frame_mut(); let frame = pixels.frame_mut();
@@ -192,14 +185,14 @@ impl State {
for pixel in frame.chunks_exact_mut(4) { for pixel in frame.chunks_exact_mut(4) {
pixel.copy_from_slice(&[0x00, 0x00, 0x00, 0xff]); pixel.copy_from_slice(&[0x00, 0x00, 0x00, 0xff]);
} }
self.scene.camera.set_position(self.gui.camera_eye);
self.rays = self
.scene
.camera
.cast_rays(self.buffer_width, self.buffer_height);
Ok(()) Ok(())
} }
fn set_camera(&mut self, camera: Camera) {
self.camera = camera;
self.camera.set_size(self.buffer_width, self.buffer_height);
}
fn render(&mut self) -> Result<(), Box<dyn Error>> { fn render(&mut self) -> Result<(), Box<dyn Error>> {
self.update()?; //Update state self.update()?; //Update state
self.draw()?; //Draw to pixels self.draw()?; //Draw to pixels