环境
- Time 2022-11-14
- WSL-Ubuntu 22.04
- Rust 1.65.0
前言
说明
参考:https://raytracing.github.io/books/RayTracingInOneWeekend.html
目标
将之前定义的三种颜色,封装到一个三维的向量中,保持原有的逻辑不变。
main.rs
use crate::vector3::Color;
mod vector3;
fn main() {
// 图片的宽和高
const WIDTH: u64 = 256;
const HEIGHT: u64 = 256;
// 输出图片,第一行输出 P3,表示像素图
let mut content = String::from("P3");
// 输出宽和高,和最大颜色值
content.push_str(&format!("\n{WIDTH} {HEIGHT}\n255\n"));
for j in (0..HEIGHT).rev() {
// 进度
eprintln!("Scan lines remaining: {j}");
for i in 0..WIDTH {
let r = i as f64 / (WIDTH - 1) as f64; // Red
let g = j as f64 / (HEIGHT - 1) as f64; // Green
let color = Color::new(r, g, 0.25);
content.push_str(&color.format_str());
}
}
println!("{}", content);
eprintln!("Done.");
}
vector3.rs
pub type Color = Vector3;
#[derive(Default)]
pub struct Vector3 {
x: f64,
y: f64,
z: f64,
}
impl Vector3 {
pub fn new(x: f64, y: f64, z: f64) -> Self {
Self { x, y, z }
}
pub fn format_str(self) -> String {
let x = (255.999 * self.x) as u64;
let y = (255.999 * self.y) as u64;
let z = (255.999 * self.z) as u64;
format!("{x} {y} {z}\n")
}
}
输出
cargo run > image.ppm
总结
将三种颜色封装到了三维的向量中。原书定义了很多的工具方法,之后用到了再定义。