From ae2f086637691e62f58921caf3db2f23bbcada00 Mon Sep 17 00:00:00 2001 From: dengqn <434500374@qq.com> Date: Thu, 31 Jul 2025 15:31:52 +0800 Subject: [PATCH] 2.Output an Image --- .gitignore | 1 + Cargo.lock | 7 +++++++ Cargo.toml | 6 ++++++ src/image.rs | 36 ++++++++++++++++++++++++++++++++++++ src/main.rs | 10 ++++++++++ src/write_file_util.rs | 12 ++++++++++++ 6 files changed, 72 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 src/image.rs create mode 100644 src/main.rs create mode 100644 src/write_file_util.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..285b107 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ray-trace-w1" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..8ab0327 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "ray-trace-w1" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/image.rs b/src/image.rs new file mode 100644 index 0000000..0017c1e --- /dev/null +++ b/src/image.rs @@ -0,0 +1,36 @@ +/* +* -------width(i)------- +* | +* | +* height(j) +* | +* | +* ---------------------- +* +* ppm p3 format: +* +* P3 +* +* [width] [height] +* [max color] +* R1 G1 B1 +* R2 G2 B2 +* R3 G3 B3 +* ...xN +*/ +pub fn gen_gradient_ppm_p3(width: i32, height: i32) -> String { + let mut img_content = format!("P3\n{} {}\n255\n", width, height); + + for j in 0..height { + for i in 0..width { + let r = 256.0 * (i as f32 / (width-1) as f32); + let g = 256.0 * (j as f32 / (height-1) as f32); + let b = 256.0 * ((i+j) as f32 / (width + height - 2) as f32); + + img_content.push_str(format!("{} {} {}", r as u8, g as u8, b as u8).as_str()); + img_content.push('\n'); + } + } + + img_content +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..efcc1ad --- /dev/null +++ b/src/main.rs @@ -0,0 +1,10 @@ +use write_file_util::{write_image}; +use image::{gen_gradient_ppm_p3}; + +mod image; +mod write_file_util; + +fn main() { + let ppm_content = gen_gradient_ppm_p3(400, 225); + write_image(ppm_content, "./target/test.ppm".to_string()) +} diff --git a/src/write_file_util.rs b/src/write_file_util.rs new file mode 100644 index 0000000..ceca186 --- /dev/null +++ b/src/write_file_util.rs @@ -0,0 +1,12 @@ +use std::{fs::File, io::{BufWriter, Write}}; + +pub fn write_image(content: String, file_path: String) { + if let Ok(file) = File::create(file_path) { + let mut writer = BufWriter::new(file); + if let Err(e) = writer.write(content.as_bytes()) { + println!("写出失败:{:#}", e) + } + } else { + println!("PPM保存失败") + } +} \ No newline at end of file