From 51e5506cd8674a30d515902697833288b35e893e Mon Sep 17 00:00:00 2001 From: Tangent 128 Date: Sun, 17 Mar 2019 01:04:03 -0400 Subject: [PATCH] Add linear_gradient() helper --- hello_gradient/src/main.rs | 22 ++++++++++------------ lights/src/rgb.rs | 4 ++++ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/hello_gradient/src/main.rs b/hello_gradient/src/main.rs index 49913b5..43978d5 100644 --- a/hello_gradient/src/main.rs +++ b/hello_gradient/src/main.rs @@ -1,12 +1,13 @@ #![no_std] #![no_main] +use core::iter::repeat; use lights::{ gamma::GammaCorrector, PixelIterator, rgb::{ - blend, gray, + linear_gradient, Rgb } }; @@ -22,17 +23,14 @@ fn main() -> ! { let teal = Rgb(0, 75, 150); let purple = Rgb(75, 0, 150); - let mut gradient = (0..16u8).map( - |x| blend(red, yellow, gray(x * 16)) - ).chain((0..16u8).map( - |x| blend(yellow, green, gray(x * 16)) - )).chain((0..16u8).map( - |x| blend(green, teal, gray(x * 16)) - )).chain((0..16u8).map( - |x| blend(teal, purple, gray(x * 16)) - )).chain((0..16u8).map( - |x| blend(purple, red, gray(x * 16)) - )).cycle(); + let segment_length = 11; + + let mut gradient = linear_gradient(red, yellow, segment_length) + .chain(linear_gradient(yellow, green, segment_length)) + .chain(linear_gradient(green, teal, segment_length)) + .chain(linear_gradient(teal, purple, segment_length)) + .chain(linear_gradient(purple, gray(0), segment_length)) + .chain(repeat(gray(255)).take(60)).cycle(); loop { gradient.clone().take(20).render_to(&mut lights); diff --git a/lights/src/rgb.rs b/lights/src/rgb.rs index 2b37c9d..617b83e 100644 --- a/lights/src/rgb.rs +++ b/lights/src/rgb.rs @@ -60,3 +60,7 @@ pub const fn gray(gray: u8) -> Rgb { pub fn blend(a: Rgb, b: Rgb, mix: Rgb) -> Rgb { (a * Rgb(255 - mix.0, 255 - mix.1, 255 - mix.2)) + (b * mix) } + +pub fn linear_gradient(from: Rgb, to: Rgb, steps: usize) -> impl Iterator + Clone { + (0..steps).map(move |x| blend(from, to, gray((x * 255 / steps) as u8))) +}