Add canvas type.
This commit is contained in:
parent
42455d593e
commit
d8f91a823e
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);
|
||||
}
|
||||
}
|
||||
@ -1 +1,2 @@
|
||||
pub mod canvas;
|
||||
pub mod tuples;
|
||||
|
||||
@ -125,12 +125,12 @@ pub fn cross(a: Tuple, b: Tuple) -> Tuple {
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
struct Color {
|
||||
pub struct Color {
|
||||
red: f32,
|
||||
green: f32,
|
||||
blue: f32,
|
||||
}
|
||||
fn color(red: f32, green: f32, blue: f32) -> Color {
|
||||
pub fn color(red: f32, green: f32, blue: f32) -> Color {
|
||||
Color { red, green, blue }
|
||||
}
|
||||
impl Add for Color {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user