Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Render sphere hits #10

Merged
merged 1 commit into from
Jul 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified output.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 15 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,20 +281,21 @@ pub fn posunit_to_unit(value: f32) -> f32 {

pub struct Radians(pub f32);

pub fn render(width: usize, height: usize) -> Image {
pub fn render(spheres: &[Sphere], camera: &Camera, width: usize, height: usize) -> Image {
let mut image = Image::new(width, height);
let max = (width * height) as f32;
for i in 0..width {
for j in 0..height {
image.set_color(
i,
j,
Color::new(
i as f32 / width as f32,
j as f32 / height as f32,
i as f32 * j as f32 / max,
),
// -1s here because we want to provide x and y coordinates between 0 and 1 inclusive
let ray = camera.screen_ray(
i as f32 / (width - 1) as f32,
j as f32 / (height - 1) as f32,
);
let intersection = closest_intersection(&spheres, &ray);
let color = match intersection {
Intersection::None => Color::new_black(),
Intersection::Hit(_) => Color::new_red(),
};
image.set_color(i, j, color);
}
}
image
Expand Down Expand Up @@ -390,4 +391,8 @@ impl Color {
pub fn new_black() -> Color {
Self::new(0.0, 0.0, 0.0)
}

pub fn new_red() -> Color {
Self::new(1.0, 0.0, 0.0)
}
}
37 changes: 35 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use raytracer::{image_to_file, render};
use raytracer::{image_to_file, render, Camera, Radians, Sphere, Vector};
use std::env;
use std::fs::File;
use std::io::{self, Write};
Expand All @@ -20,6 +20,39 @@ fn main() {
_ => Box::new(File::create(filename).expect("Cannot open file for writing")),
};

let image = render(200, 100);
let spheres = [
Sphere {
center: Vector {
x: 0.0,
y: 0.0,
z: -5.0,
},
radius: 1.0,
},
Sphere {
center: Vector {
x: -3.0,
y: 1.0,
z: -5.0,
},
radius: 1.0,
},
Sphere {
center: Vector {
x: 5.0,
y: 1.0,
z: -10.0,
},
radius: 1.0,
},
];
let camera = Camera {
position: Vector::zero(),
forward: -Vector::unitz(),
up: Vector::unity(),
aspect_ratio: 4.0 / 3.0,
fovx: Radians(90.0f32.to_radians()),
};
let image = render(&spheres, &camera, 800, 600);
image_to_file(&image, &mut file);
}