Skip to content

Commit

Permalink
feat: add Camera struct
Browse files Browse the repository at this point in the history
  • Loading branch information
alanjian85 committed Jul 17, 2024
1 parent 87ffe0d commit 8cdd343
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 14 deletions.
37 changes: 37 additions & 0 deletions src/camera.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use crate::Ray;
use nalgebra::{Point2, Point3, Vector3};

pub struct Camera {
pos: Point3<f64>,
pix_orig: Point3<f64>,
pix_delta_x: Vector3<f64>,
pix_delta_y: Vector3<f64>,
}

impl Camera {
pub fn new(pos: Point3<f64>, width: u32, height: u32, focal_len: f64) -> Self {
let aspect_ratio = width as f64 / height as f64;
let viewport_height = 2.0;
let viewport_width = viewport_height * aspect_ratio;

let pix_delta_x = Vector3::new(viewport_width, 0.0, 0.0) / width as f64;
let pix_delta_y = Vector3::new(0.0, -viewport_height, 0.0) / height as f64;
let pix_orig = pos + Vector3::new(0.0, 0.0, -focal_len)
- width as f64 / 2.0 * pix_delta_x
- height as f64 / 2.0 * pix_delta_y;

Camera {
pos,
pix_orig,
pix_delta_x,
pix_delta_y,
}
}

pub fn generate_ray(&self, p: Point2<u32>) -> Ray {
let pix_pos = self.pix_orig + p.x as f64 * self.pix_delta_x + p.y as f64 * self.pix_delta_y;
let dir = pix_pos - self.pos;

Ray::new(self.pos, dir)
}
}
19 changes: 5 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
mod camera;
mod cli;
mod core;

use camera::Camera;
use clap::Parser;
use cli::{Cli, Size};
use core::Ray;
use image::{Rgb, RgbImage};
use indicatif::ProgressBar;
use nalgebra::{Point3, Vector3};
use nalgebra::{Point2, Point3, Vector3};
use palette::{LinSrgb, Srgb};

fn hit_sphere(center: Point3<f64>, radius: f64, ray: &Ray) -> Option<f64> {
Expand Down Expand Up @@ -40,22 +42,11 @@ fn main() {
let mut image = RgbImage::new(width, height);
let progress_bar = ProgressBar::new(height as u64);

let camera_pos = Point3::new(0.0, 0.0, 0.0);
let camera_focal_len = 1.0;

let viewport_height = 2.0;
let viewport_width = viewport_height * (width as f64 / height as f64);

let pixel_delta_x = Vector3::new(viewport_width, 0.0, 0.0) / width as f64;
let pixel_delta_y = Vector3::new(0.0, -viewport_height, 0.0) / height as f64;
let pixel_pos_orig = camera_pos + Vector3::new(0.0, 0.0, -camera_focal_len)
- width as f64 / 2.0 * pixel_delta_x
- height as f64 / 2.0 * pixel_delta_y;
let camera = Camera::new(Point3::new(0.0, 0.0, 0.0), width, height, 1.0);

for y in 0..height {
for x in 0..width {
let pixel_pos = pixel_pos_orig + x as f64 * pixel_delta_x + y as f64 * pixel_delta_y;
let ray = Ray::new(camera_pos, pixel_pos - camera_pos);
let ray = camera.generate_ray(Point2::new(x, y));
let color: Srgb<f64> = Srgb::from_linear(ray_color(&ray));

let r = (255.999 * color.red) as u8;
Expand Down

0 comments on commit 8cdd343

Please sign in to comment.