ft: 4: ray class + simpl gradient

This commit is contained in:
2026-04-15 12:11:04 +02:00
parent 8e96a0ba11
commit 67c1eb861d
3 changed files with 154 additions and 23 deletions

View File

@@ -1,31 +1,62 @@
#![feature(core_float_math)]
mod ray;
mod vec3;
use crate::vec3::Vec3;
use std::cmp::max;
use crate::ray::Ray;
use crate::vec3::{Colour, Vec3};
use log::info;
use pretty_env_logger;
fn ray_colour(r: &Ray) -> Colour {
let unit_dir = r.dir().get_unit();
let a = 0.5 * (unit_dir.y() + 1.);
(1.0 - a) * Colour::new(1., 1., 1.) + a * Colour::new(0.5, 0.7, 1.0)
}
fn main() {
let v = Vec3::rgb(255., 0., 255.);
// use structs so rust-analyzer can provide lsp
let v = Vec3::new(255., 0., 255.);
let _ = Ray::new(v.clone(), v.clone());
pretty_env_logger::init();
let image_width = 256;
let image_height = 256;
let aspect_ratio = 16. / 9.;
let image_width = 400;
let image_height = max(1, (image_width as f32 / aspect_ratio) as u32);
//camera
let focal_length = 1.;
let viewport_height = 2.;
let viewport_width = viewport_height * (image_width as f32 / image_height as f32);
let camera_center = Vec3::nil();
//viewport
let viewport_u = Vec3::new(viewport_width as f32, 0., 0.);
let viewport_v = Vec3::new(0., -viewport_height as f32, 0.);
let pixel_delta_u = viewport_u / image_width as f32;
let pixel_delta_v = viewport_v / image_height as f32;
let viewport_upper_left =
camera_center - Vec3::new(0., 0., focal_length) - viewport_u / 2 - viewport_v / 2;
let pixel00_loc = viewport_upper_left + 0.5 * (pixel_delta_u + pixel_delta_v);
let mut imgbuf = image::ImageBuffer::new(image_width, image_height);
// render
for j in 0..image_height {
info!("{}\tScanlines remaining.", (image_height - j));
for i in 0..image_width {
let rgb = Vec3::rgb(
i as f32 / (image_width - 1) as f32,
j as f32 / (image_height - 1) as f32,
0.0,
);
let pixel_center = pixel00_loc + (i * pixel_delta_u) + (j * pixel_delta_v);
let ray_dir = pixel_center - camera_center;
let r = Ray::new(camera_center, ray_dir);
let pixel = imgbuf.get_pixel_mut(i, j);
*pixel = rgb.output();
*pixel = ray_colour(&r).output();
}
}