環境
- 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
總結
將三種顏色封裝到了三維的向量中。原書定義了很多的工具方法,之後用到了再定義。