diff options
author | lamp | 2023-12-18 15:21:13 +0000 |
---|---|---|
committer | lamp | 2023-12-18 15:21:13 +0000 |
commit | b3bb54ca9cdcca60adb401fd69278a12d8fd367a (patch) | |
tree | eacc3ffb2f15268c9f7f0b5127de6e2b06dfc8d2 /src/image.rs |
init
Diffstat (limited to 'src/image.rs')
-rw-r--r-- | src/image.rs | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/image.rs b/src/image.rs new file mode 100644 index 0000000..365596b --- /dev/null +++ b/src/image.rs @@ -0,0 +1,62 @@ +use std::io::Write; + +use crate::vec3::Color; + +pub struct Image { + width: usize, + height: usize, + data: Vec<Color>, +} + +impl Image { + pub fn new(width: usize, height: usize) -> Image { + let data = vec![ + Color { + x: 0.0, + y: 0.0, + z: 0.0 + }; + width * height + ]; + Image { + width, + height, + data, + } + } + + pub fn set(&mut self, x: usize, y: usize, color: &Color) -> Result<(), ()> { + *self.data.get_mut(y * self.width + x).ok_or(())? = color.clone(); + Ok(()) + } + + pub fn get(&self, x: usize, y: usize) -> Option<&Color> { + self.data.get(y * self.width + x) + } + + pub fn write(&self, output: &mut impl Write) { + output.write_fmt(format_args!("P3\n{} {}\n255\n", self.width, self.height)).unwrap(); + for y in (0..self.height).rev() { + for x in 0..self.width { + let pixel = self.get(x, y).unwrap(); + let mut r = pixel.x; + let mut g = pixel.y; + let mut b = pixel.z; + + // Divide by the number of samples and perform gamma correction for gamma 2 + r = r.sqrt(); + g = g.sqrt(); + b = b.sqrt(); + + output + .write_fmt(format_args!( + "{} {} {}\n", + (256.0 * r.clamp(0.0, 0.999)) as u32, + (256.0 * g.clamp(0.0, 0.999)) as u32, + (256.0 * b.clamp(0.0, 0.999)) as u32, + )) + .unwrap(); + } + } + } +} |