Skip to content

Commit 8edeca7

Browse files
committed
Impl Mul by color for colors
This is needed for example to shade surfaces illuminated by a colored light source.
1 parent 7999c17 commit 8edeca7

File tree

1 file changed

+33
-10
lines changed

1 file changed

+33
-10
lines changed

core/src/math/color.rs

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
use core::{
44
array,
55
fmt::{self, Debug, Display, Formatter},
6+
iter::zip,
67
marker::PhantomData,
78
ops::{Add, Div, Index, IndexMut, Mul, Neg, Sub},
89
ops::{AddAssign, DivAssign, MulAssign, SubAssign},
@@ -632,13 +633,7 @@ impl<R: IndexMut<usize>, Sp> IndexMut<usize> for Color<R, Sp> {
632633
}
633634
}
634635

635-
//
636-
// Arithmetic trait impls
637-
//
638-
639-
//
640636
// Arithmetic traits
641-
//
642637

643638
/// The color += color operator.
644639
impl<R, D, Sp> AddAssign<D> for Color<R, Sp>
@@ -663,7 +658,7 @@ where
663658
}
664659
}
665660

666-
// The color *= scalar operator.
661+
/// The color *= scalar operator.
667662
impl<R, Sc, Sp> MulAssign<Sc> for Color<R, Sp>
668663
where
669664
Self: Linear<Scalar = Sc>,
@@ -673,8 +668,20 @@ where
673668
*self = Linear::mul(&*self, rhs);
674669
}
675670
}
676-
677-
// The color /= scalar operator.
671+
/// The color *= color operator.
672+
impl<Sc, Sp, const N: usize> MulAssign for Color<[Sc; N], Sp>
673+
where
674+
Self: Linear<Scalar = Sc>,
675+
Sc: Linear<Scalar = Sc>,
676+
{
677+
#[inline]
678+
fn mul_assign(&mut self, rhs: Self) {
679+
for (a, b) in zip(&mut self.0, rhs.0) {
680+
*a = (&*a).mul(b)
681+
}
682+
}
683+
}
684+
/// The color /= scalar operator.
678685
impl<R, Sp> DivAssign<f32> for Color<R, Sp>
679686
where
680687
Self: Linear<Scalar = f32>,
@@ -700,6 +707,20 @@ where
700707
}
701708
}
702709

710+
/// The color * color operator.
711+
impl<Sc, Sp, const N: usize> Mul for Color<[Sc; N], Sp>
712+
where
713+
Self: Linear<Scalar = Sc>,
714+
Sc: Linear<Scalar = Sc>,
715+
{
716+
type Output = Self;
717+
718+
#[inline]
719+
fn mul(mut self, rhs: Self) -> Self {
720+
self *= rhs;
721+
self
722+
}
723+
}
703724
/// The scalar * color operator.
704725
impl<R, Sp> Mul<Color<R, Sp>> for <Color<R, Sp> as Linear>::Scalar
705726
where
@@ -757,10 +778,12 @@ mod tests {
757778

758779
assert_eq!(lhs + rhs, rgb(0.625, 0.875, 1.125));
759780
assert_eq!(lhs - rhs, rgb(0.375, 0.375, 0.375));
781+
assert_eq!(-lhs, rgb(-0.5, -0.625, -0.75));
782+
783+
assert_eq!(lhs * rhs, rgb(0.0625, 0.15625, 0.28125));
760784
assert_eq!(lhs * 0.5, rgb(0.25, 0.3125, 0.375));
761785
assert_eq!(0.5 * lhs, rgb(0.25, 0.3125, 0.375));
762786
assert_eq!(lhs / 2.0, rgb(0.25, 0.3125, 0.375));
763-
assert_eq!(-lhs, rgb(-0.5, -0.625, -0.75));
764787
}
765788

766789
#[test]

0 commit comments

Comments
 (0)