From edc148544989e29f0b822d47a941be771d88e531 Mon Sep 17 00:00:00 2001 From: stickynotememo Date: Fri, 16 Jan 2026 12:28:04 +1100 Subject: [PATCH] Triangle functionality --- src/points.rs | 7 +++++++ src/render.rs | 25 +++++++++++++++++++++++-- src/scene.rs | 2 +- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/points.rs b/src/points.rs index 358597e..02de27f 100644 --- a/src/points.rs +++ b/src/points.rs @@ -7,6 +7,7 @@ pub struct Point2D { pub x: f64, pub y: f64 } + #[derive(Debug, Clone, Copy)] pub struct Point3D { pub x: f64, pub y: f64, pub z: f64 @@ -118,4 +119,10 @@ impl Point2D { + f64::powf(p2.y.max(p1.y) - p1.y.min(p2.y), 2.0)) as f64, ) } + + pub fn gradient(self, p2: &Point2D) -> f64 { + let p1 = self; + + (p2.y - p1.y) / (p2.x - p1.x) + } } diff --git a/src/render.rs b/src/render.rs index 435ff7e..a1e1733 100644 --- a/src/render.rs +++ b/src/render.rs @@ -1,5 +1,5 @@ use crate::consts::*; -use crate::points::Point2D; +use crate::points::{Point2D, Point3D}; use crate::Scene; type Pixel = u32; @@ -62,8 +62,29 @@ pub fn render(scene: &Scene, buf: &mut [u32]) { } } - for faces in &obj.faces { + for (p0, p1, p2) in &obj.faces { + + let (p0, p1, p2) = (p0.to_screen_coordinates(), p1.to_screen_coordinates(), p2.to_screen_coordinates()); + // Finds the leftmost and rightmost points on the triangle and only iterates over them. + let horizontal_range = p0.x.min(p1.x.min(p2.x)) as usize..=p0.x.max(p1.x.max(p2.x)) as usize; + let vertical_range = p0.y.min(p1.y.min(p2.y)) as usize..=p0.y.max(p1.y.max(p2.y)) as usize; + + for x in horizontal_range.clone() { + for y in vertical_range.clone() { + let p = Point2D{x: x as f64, y: y as f64}; + + let area = 0.5 *(-p1.y*p2.x + p0.y*(-p1.x + p2.x) + p0.x*(p1.y - p2.y) + p1.x*p2.y); + let s = 1.0/(2.0*area)*(p0.y*p2.x - p0.x*p2.y + (p2.y - p0.y)*p.x + (p0.x - p2.x)*p.y); + let t = 1.0/(2.0*area)*(p0.x*p1.y - p0.y*p1.x + (p0.y - p1.y)*p.x + (p1.x - p0.x)*p.y); + + if s > 0.0 && t > 0.0 && 1.0 - s - t > 0.0 { + // dbg!(p); + *index_buffer(buf, p) = to_rgb((255, 255, 255)); + }; + } + } + } } diff --git a/src/scene.rs b/src/scene.rs index 1a35fa9..86b085a 100644 --- a/src/scene.rs +++ b/src/scene.rs @@ -6,7 +6,7 @@ use crate::points::Scene; pub fn set_scene(dt: Duration, scene: &mut Scene) { for obj in scene { for vertex in obj.vertices.iter_mut() { - vertex.z += 1.0; + // vertex.z += 1.0; } obj.update();