eoc4: implement suggestion at the end of chapter 4

This commit is contained in:
Bill Thiede 2021-07-16 17:12:48 -07:00
parent af5e61136c
commit 5df2917668

View File

@ -0,0 +1,48 @@
use std::f32::consts::PI;
use anyhow::Result;
use rtchallenge::{
canvas::Canvas,
matrices::Matrix4x4,
tuples::{Color, Tuple},
};
fn draw_dot(c: &mut Canvas, x: usize, y: usize) {
let red = Color::new(1., 0., 0.);
c.set(x.saturating_sub(1), y.saturating_sub(1), red);
c.set(x, y.saturating_sub(1), red);
c.set(x + 1, y.saturating_sub(1), red);
c.set(x.saturating_sub(1), y, red);
c.set(x, y, red);
c.set(x + 1, y, red);
c.set(x.saturating_sub(1), y + 1, red);
c.set(x, y + 1, red);
c.set(x + 1, y + 1, red);
}
fn main() -> Result<()> {
let w = 200;
let h = w;
let mut c = Canvas::new(w, h);
let t = Matrix4x4::translate(0., 0.75, 0.);
let p = Tuple::point(0., 0., 0.);
let rot_hour = Matrix4x4::rotation_z(-PI / 6.);
let mut p = t * p;
let w = w as f32;
let h = h as f32;
let h_w = w / 2.0;
let h_h = h / 2.0;
for _ in 0..12 {
let x = (h_w + h_w * p.x) as usize;
// Y-axis is 0 at the top, and h at the bottom, flip it.
let y = (h - (h_h + h_h * p.y)) as usize;
draw_dot(&mut c, x, y);
p = rot_hour * p;
}
let path = "/tmp/eoc4.png";
println!("saving output to {}", path);
c.write_to_file(path)?;
Ok(())
}