🦀
RustでRayTracing (チャプター7)
チャプター7はAntialiasingをするプログラムを書くところでした。
pixelの付近をサンプリングして平均を取るってしてたんですねー。
100回サンプリングしてるんで、処理時間が大幅に増えました。
計算自体は独立してるので、並列化すれば速くなりそうですね。
並列化は全部実装してからやろうと思います。
f32にclampするとunstableって出たんで、minとmaxで実装しました。
あと表示するところでのみ、色の表現をi32にしました。
チャプター7ではCameraを抽象化してましたが、段階的にバージョンアップするのはいいですね。
今回のコードをのせておきます。
use std::fmt;
use rand;
use cgmath::prelude::*;
use cgmath::{Vector3, vec3, dot};
type Color = Vector3<i32>;
pub struct HitRecord {
pub p: Vector3<f32>,
pub normal: Vector3<f32>,
pub t: f32,
pub front_face: bool
}
impl HitRecord {
pub fn set_face_normal(&mut self, ray: &Ray, outward_normal: Vector3<f32>) {
self.front_face = dot(ray.direction, outward_normal) < 0.0;
self.normal = if self.front_face {
outward_normal
} else {
-outward_normal
}
}
}
pub trait HitTable {
fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<HitRecord>;
}
pub struct HitTableList {
list: Vec<Box<dyn HitTable>>
}
impl HitTableList {
pub fn new() -> Self {
HitTableList {
list: vec![],
}
}
pub fn push(&mut self, hitable: impl HitTable + 'static) {
self.list.push(Box::new(hitable))
}
pub fn clear(&mut self) {
self.list.clear()
}
}
impl HitTable for HitTableList {
fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
let mut closest_so_far = t_max;
let mut hit_anything: Option<HitRecord> = None;
for h in self.list.iter() {
if let Some(hit) = h.hit(ray, t_min, closest_so_far) {
closest_so_far = hit.t;
hit_anything = Some(hit);
}
}
hit_anything
}
}
pub struct Sphere {
center: Vector3<f32>,
radius: f32,
}
impl Sphere {
pub fn new(center: Vector3<f32>, radius: f32) -> Self {
Sphere {center, radius}
}
}
impl HitTable for Sphere {
fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
let oc = ray.origin - self.center;
let a = length_squared(ray.direction);
let half_b = dot(oc, ray.direction);
let c = length_squared(oc) - self.radius * self.radius;
let discriminant = half_b.powi(2) - a * c;
if discriminant > 0.0 {
let sqrtd = discriminant.sqrt();
// Find the nearest root that lies in the acceptable range.
let mut root = (- half_b - sqrtd) / a;
if root < t_min || t_max < root {
root = (- half_b + sqrtd) / a;
if root < t_min || t_max < root {
return None
}
}
let p = ray.at(root);
let outward_normal = (p - self.center) / self.radius;
// set face normal
let front_face = dot(ray.direction, outward_normal) < 0.0;
let normal = if front_face {outward_normal} else {-outward_normal};
return Some(HitRecord{t: root, p: p, normal: normal, front_face: front_face});
}
None
}
}
pub struct Camera {
pub origin: Vector3<f32>,
pub horizontal: Vector3<f32>,
pub vertical: Vector3<f32>,
pub lower_left_corner: Vector3<f32>,
}
impl Camera {
pub fn new() -> Self {
const aspect_ratio: f32 = 16.0 / 9.0;
const viewport_height: f32 = 2.0;
let viewport_width = aspect_ratio * viewport_height;
let focal_length = 1.0;
let origin: Vector3<f32> = Vector3::zero();
let horizontal: Vector3<f32> = vec3(viewport_width, 0.0, 0.0);
let vertical: Vector3<f32> = vec3(0.0, viewport_height, 0.0);
let lower_left_corner = origin - horizontal / 2.0 - vertical / 2.0 - vec3(0.0, 0.0, focal_length);
Camera {
origin,
horizontal,
vertical,
lower_left_corner
}
}
pub fn get_ray(&self, u: f32, v: f32) -> Ray {
Ray::new(self.origin, self.lower_left_corner + u * self.horizontal + v * self.vertical - self.origin)
}
}
pub fn write_color(pixel_color: Vector3<f32>, samples_per_pixel: i32) {
let scale = 1.0 / samples_per_pixel as f32;
let color:Color = pixel_color.map(|e| 256.0 * (e * scale).min(0.999).max(0.0)).cast().unwrap();
println!("{} {} {}", color.x, color.y, color.z);
}
pub struct Ray {
pub origin: Vector3<f32>,
pub direction: Vector3<f32>
}
impl Ray {
pub fn new(o:Vector3<f32>, d:Vector3<f32>) -> Self {
Ray{origin: o, direction: d}
}
pub fn at(&self, t: f32) -> Vector3<f32> {
self.origin + self.direction * t
}
}
impl fmt::Debug for Ray {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({:?}, {:?})", self.origin, self.direction)
}
}
fn ray_color(ray: &Ray, world: &dyn HitTable) -> Vector3<f32>
{
const white: Vector3<f32> = vec3(1.0, 1.0, 1.0);
const blue: Vector3<f32> = vec3(0.5, 0.7, 1.0);
if let Some(hit) = world.hit(ray, 0.0, f32::INFINITY) {
return 0.5 * (hit.normal + white);
}
let unit_direction = ray.direction.normalize();
let t = 0.5 * (unit_direction.y + 1f32);
let rgb = white.lerp(blue, t);
return rgb
}
fn length_squared(v: Vector3<f32>) -> f32 {
v.x * v.x + v.y * v.y + v.z * v.z
}
fn hit_sphere(center: Vector3<f32>, radius: f32, ray:&Ray) -> f32 {
let oc = ray.origin - center;
let a = length_squared(ray.direction);
let half_b = dot(oc, ray.direction);
let c = length_squared(oc) - radius * radius;
let discriminant = half_b * half_b - a * c;
if discriminant < 0.0 {
return -1.0;
}
else {
return (- half_b - discriminant.sqrt()) / a;
}
}
fn main() {
// Image
const aspect_ratio: f32 = 16.0 / 9.0;
const image_width: i32 = 400;
const image_height: i32 = (image_width as f32 / aspect_ratio) as i32;
const samples_per_pixel: i32 = 100;
// World
let mut world = HitTableList::new();
world.push(Sphere::new(vec3(0.0, 0.0, -1.0), 0.5));
world.push(Sphere::new(vec3(0.0, -100.5, -1.0), 100.0));
// Camera
let camera = Camera::new();
// Render
println!("P3\n {} {} \n255", image_width, image_height);
for j in (0..image_height).rev() {
for i in 0..image_width {
let mut pixel_color: Vector3<f32> = Vector3::zero();
for s in 0..samples_per_pixel {
let u = (i as f32 + rand::random::<f32>()) / (image_width - 1) as f32;
let v = (j as f32 + rand::random::<f32>()) / (image_height - 1) as f32;
let r = camera.get_ray(u, v);
pixel_color += ray_color(&r, &world);
}
write_color(pixel_color, samples_per_pixel);
}
}
}
Discussion