diff options
author | lamp | 2024-01-21 13:44:51 +0000 |
---|---|---|
committer | lamp | 2024-01-21 13:44:51 +0000 |
commit | c0fc3926e06acddcc02ef086fbda688d4709e5ba (patch) | |
tree | e9f752758a49bedf1936003a7a2cd883e7d8e3cf /src/display/image.rs | |
parent | 78ddaff5855bf8446adef9e18eb0d7b7ddcee52a (diff) |
refactor display backends, add pixelflut backend
Diffstat (limited to 'src/display/image.rs')
-rw-r--r-- | src/display/image.rs | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/src/display/image.rs b/src/display/image.rs new file mode 100644 index 0000000..77d8c83 --- /dev/null +++ b/src/display/image.rs @@ -0,0 +1,68 @@ +use std::io::Write; + +use crate::vec3::Color; +use crate::display::{Display, Pixel}; + +pub struct Image { + width: usize, + height: usize, + data: Vec<Pixel>, +} + +impl Image { + pub fn new(width: usize, height: usize) -> Image { + let data = vec![ + Pixel { + color: Color { + x: 0.0, + y: 0.0, + z: 0.0 + }, + sample_count: 0 + }; + width * height + ]; + Image { + width, + height, + data, + } + } +} + +impl Display for Image { + fn add_sample(&mut self, x: usize, y: usize, color: Color) { + self.data + .get_mut((y * self.width) + x) + .unwrap() + .update(color); + } + + fn maybe_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.data.get((y * self.width) + x).unwrap(); + let mut r = pixel.color.x; + let mut g = pixel.color.y; + let mut b = pixel.color.z; + + // Divide by the number of samples and perform gamma correction for gamma 2 + let scale = 1.0 / pixel.sample_count as f64; + r = (r * scale).sqrt(); + g = (g * scale).sqrt(); + b = (b * scale).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(); + } + } + } + fn maybe_update(&mut self) {} +} |