Skip to content

Commit

Permalink
Merge pull request #338 from therealprof/color-level-up
Browse files Browse the repository at this point in the history
Allow Triangles to carry a color and transfer that to the vertices du…
  • Loading branch information
hannobraun authored Mar 14, 2022
2 parents 643f39a + a76229c commit ab776f1
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 8 deletions.
11 changes: 6 additions & 5 deletions src/graphics/vertices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,19 @@ impl From<&Vec<Triangle<3>>> for Vertices {
let [a, b, c] = triangle.points();

let normal = (b - a).cross(&(c - a)).normalize();
let color = triangle.color();

mesh.push((a, normal));
mesh.push((b, normal));
mesh.push((c, normal));
mesh.push((a, normal, color));
mesh.push((b, normal, color));
mesh.push((c, normal, color));
}

let vertices = mesh
.vertices()
.map(|(vertex, normal)| Vertex {
.map(|(vertex, normal, color)| Vertex {
position: vertex.into(),
normal: normal.into(),
color: [1.0, 0.0, 0.0, 1.0],
color: color.map(|v| f32::from(v) / 255.0),
})
.collect();

Expand Down
41 changes: 38 additions & 3 deletions src/math/triangle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,25 @@ use super::{Point, Scalar};

/// A triangle
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Triangle<const D: usize>([Point<D>; 3]);
pub struct Triangle<const D: usize> {
points: [Point<D>; 3],
color: [u8; 4],
}

impl<const D: usize> Triangle<D> {
/// Access the triangle's points
pub fn points(&self) -> [Point<D>; 3] {
self.0
self.points
}

/// Return the specified color of the triangle in RGBA
pub fn color(&self) -> [u8; 4] {
self.color
}

/// Set a new color for the particular triangle
pub fn set_color(&mut self, color: [u8; 4]) {
self.color = color;
}
}

Expand All @@ -27,7 +40,10 @@ impl<const D: usize> From<[Point<D>; 3]> for Triangle<D> {

// A triangle is not valid if it doesn't span any area
if area != Scalar::from(0.0) {
Self(points)
Self {
points,
color: [255, 0, 0, 255],
}
} else {
panic!("Invalid Triangle specified");
}
Expand Down Expand Up @@ -72,4 +88,23 @@ mod tests {
let c = Point::from([2.0, 2.0, 2.0]);
let _triangle = Triangle::from([a, b, c]);
}

#[test]
fn triangle_default_color() {
let a = Point::from([0.0, 0.0]);
let b = Point::from([1.0, 1.0]);
let c = Point::from([1.0, 2.0]);
let triangle = Triangle::from([a, b, c]);
assert_eq!(triangle.color(), [255, 0, 0, 255]);
}

#[test]
fn triangle_set_color() {
let a = Point::from([0.0, 0.0]);
let b = Point::from([1.0, 1.0]);
let c = Point::from([1.0, 2.0]);
let mut triangle = Triangle::from([a, b, c]);
triangle.set_color([1, 2, 3, 4]);
assert_eq!(triangle.color(), [1, 2, 3, 4]);
}
}

0 comments on commit ab776f1

Please sign in to comment.