From 635585dd0990f1d4308f7c412542d4199359a279 Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Fri, 5 Sep 2025 15:43:03 -0700 Subject: [PATCH] line drawing works well, room for optimization --- src/main.rs | 25 ++++++++++++++++++------- src/point.rs | 4 ++-- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 9bfb53a..ee06e20 100644 --- a/src/main.rs +++ b/src/main.rs @@ -57,13 +57,24 @@ fn main() { .unwrap(); } -fn line(a: Point, b: Point, fb: &mut TGAImage, color: TGAColor) { - let mut t = 0.0; - let step = 0.02; - while t < 1.0 { - let x = (a.x as f32 + (b.x - a.x) as f32 * t).round_ties_even() as u32; +fn line(mut a: Point, mut b: Point, fb: &mut TGAImage, color: TGAColor) { + let is_steep = (a.x - b.x).abs() < (a.y - b.y).abs(); + if is_steep { + std::mem::swap(&mut a.x, &mut a.y); + std::mem::swap(&mut b.x, &mut b.y); + } + if a.x > b.x { + std::mem::swap(&mut a.x, &mut b.x); + std::mem::swap(&mut a.y, &mut b.y); + } + + for x in (a.x)..b.x { + let t = (x - a.x) as f32 / (b.x - a.x) as f32; let y = (a.y as f32 + (b.y - a.y) as f32 * t).round_ties_even() as u32; - fb.set(x, y, color); - t += step; + if is_steep { + fb.set(y, x as u32, color); + } else { + fb.set(x as u32, y, color); + } } } diff --git a/src/point.rs b/src/point.rs index 7c51252..fbcc517 100644 --- a/src/point.rs +++ b/src/point.rs @@ -31,8 +31,8 @@ impl Sub for Point { fn sub(self, rhs: Self) -> Self::Output { Self { - x: self.x.saturating_sub(rhs.x), - y: self.y.saturating_sub(rhs.y), + x: self.x - rhs.x, + y: self.y - rhs.y, } } }