From 94eaa60fde9982a2b9dd8fe806d5e9f8953cc91f Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Sun, 7 Sep 2025 12:21:12 -0700 Subject: [PATCH] working filled triangles --- src/main.rs | 47 ++++++++++++++++------------------------------- 1 file changed, 16 insertions(+), 31 deletions(-) diff --git a/src/main.rs b/src/main.rs index 3403224..0f8d254 100644 --- a/src/main.rs +++ b/src/main.rs @@ -133,7 +133,6 @@ fn line_verts(mut a: Point2i, mut b: Point2i) -> Vec { let mut verts: Vec = Vec::new(); let step = (b.y - a.y) as f32 / (b.x - a.x) as f32; - let sign = step.signum() as i32; let mut y = a.y as f32; for x in (a.x)..b.x { let p = if is_steep { @@ -155,38 +154,24 @@ fn triangle_lines(a: Point2i, b: Point2i, c: Point2i, color: TGAColor, fb: &mut } fn triangle_filled(a: Point2i, b: Point2i, c: Point2i, color: TGAColor, fb: &mut TGAImage) { - let mut verts = line_verts(a, b); - verts.extend(line_verts(b, c)); - verts.extend(line_verts(c, a)); + let mut sorted = [a, b, c]; + sorted.sort_unstable_by(|a, b| a.y.cmp(&b.y)); + let [a, b, c] = sorted; - let mut lines: BTreeMap> = BTreeMap::new(); - for vert in verts.into_iter() { - lines - .entry(vert.y) - .and_modify(|e| { - e.push(vert.x); - e.sort_unstable(); - }) - .or_insert(vec![vert.x]); + let total_height = c.y - a.y; + + let segment_height = b.y - a.y; + for y in a.y..=b.y { + let dy = y - a.y; + let x1 = a.x + ((c.x - a.x) * dy) / total_height; + let x2 = a.x + ((b.x - a.x) * dy) / segment_height; + line(Point2i::new(x1, y), Point2i::new(x2, y), color, fb); } - let mut prev_y: Option = None; - for (y, xs) in lines.iter_mut() { - let len = xs.len(); - match len { - 0 => {} - 1 => fb.set(xs[0] as u32, *y as u32, color), - _ => { - let start = xs[0]; - let end = xs[len - 1]; - line(Point2i::new(start, *y), Point2i::new(end, *y), color, fb); - } - } - if let Some(prev) = prev_y { - if (y - prev).abs() > 1 { - dbg!(y); - } - } - prev_y = Some(*y) + let segment_height = c.y - b.y; + for y in b.y..=c.y { + let x1 = a.x + ((c.x - a.x) * (y - a.y)) / total_height; + let x2 = b.x + ((c.x - b.x) * (y - b.y)) / segment_height; + line(Point2i::new(x1, y), Point2i::new(x2, y), color, fb); } }