Skip to content

Instantly share code, notes, and snippets.

@SharpCoder
Created March 14, 2022 16:19
Show Gist options
  • Select an option

  • Save SharpCoder/13c0172c73ccdd9971551d37e3c3fba1 to your computer and use it in GitHub Desktop.

Select an option

Save SharpCoder/13c0172c73ccdd9971551d37e3c3fba1 to your computer and use it in GitHub Desktop.
pub fn get_color(&mut self, time: u64) -> Color {
// Take the current time we are interested in (typically
// system uptime in milliseconds) and modulus it by
// the total time of our gradient so we end up with
// a point between 0 and the total_time.
let normalized_time = time % self.total_time;
// The internal representation for this builder pattern
// is a linked-list, so do some sanity checks.
if self.root.is_none() {
return self.color;
} else {
// Now we want to find which portion of the gradient we
// care about. Pre-seed the color we are going to return
// based on the root color
let mut color = self.color;
let mut ptr = self.root.unwrap();
let mut elapsed = 0;
// Iterate over each node in the linked-list until
// we find the target node that our color will fall between.
while elapsed + unsafe { (*ptr).time } < normalized_time {
color = unsafe { (*ptr).color };
elapsed += unsafe { (*ptr).time };
ptr = unsafe { (*ptr).next.unwrap() };
}
let next_color = unsafe { (*ptr).color };
let duration = unsafe { (*ptr).time };
// Now is the math part. Use interpolation for
// r -> r, g -> g, b -> b in order to compute
// a new color that represents the transition
// between our current color and the
// color we want to be transitioning to.
let r = interpolate(
color.r as u32,
next_color.r as u32,
normalized_time - elapsed, duration);
let g = interpolate(
color.g as u32,
next_color.g as u32,
normalized_time - elapsed, duration);
let b = interpolate(
color.b as u32,
next_color.b as u32,
normalized_time - elapsed, duration);
// Finally, return the rgb of the new computed color.
return rgb(r as u8, g as u8, b as u8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment