Add canvas type.
This commit is contained in:
50
rtchallenge/src/canvas.rs
Normal file
50
rtchallenge/src/canvas.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use crate::tuples::{color, Color};
|
||||
|
||||
pub struct Canvas {
|
||||
pub height: usize,
|
||||
pub width: usize,
|
||||
pub pixels: Vec<Color>,
|
||||
}
|
||||
|
||||
fn canvas(width: usize, height: usize) -> Canvas {
|
||||
let pixels = vec![color(0., 0., 0.); width * height];
|
||||
Canvas {
|
||||
width,
|
||||
height,
|
||||
pixels,
|
||||
}
|
||||
}
|
||||
|
||||
impl Canvas {
|
||||
pub fn set(&mut self, x: usize, y: usize, c: Color) {
|
||||
self.pixels[x + y * self.width] = c;
|
||||
}
|
||||
pub fn get(&mut self, x: usize, y: usize) -> Color {
|
||||
self.pixels[x + y * self.width]
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::canvas;
|
||||
|
||||
use crate::tuples::color;
|
||||
|
||||
#[test]
|
||||
fn create_canvas() {
|
||||
let c = canvas(10, 20);
|
||||
assert_eq!(c.width, 10);
|
||||
assert_eq!(c.height, 20);
|
||||
let black = color(0., 0., 0.);
|
||||
for (i, p) in c.pixels.iter().enumerate() {
|
||||
assert_eq!(p, &black, "pixel {} not {:?}: {:?}", i, &black, p);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_to_canvas() {
|
||||
let mut c = canvas(10, 20);
|
||||
let red = color(1., 0., 0.);
|
||||
c.set(2, 3, red);
|
||||
assert_eq!(c.get(2, 3), red);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user