this is max colors allowed by the user, not just max in the current (candidate/low-quality) palette
(mut self, max_colors: PalLen, fixed_colors: &[f_pixel])
| 262 | |
| 263 | // this is max colors allowed by the user, not just max in the current (candidate/low-quality) palette |
| 264 | pub(crate) fn with_fixed_colors(mut self, max_colors: PalLen, fixed_colors: &[f_pixel]) -> Self { |
| 265 | if fixed_colors.is_empty() { |
| 266 | return self; |
| 267 | } |
| 268 | |
| 269 | // if using low quality, there's a chance mediancut won't create enough colors in the palette |
| 270 | let max_fixed_colors = fixed_colors.len().min(max_colors as usize); |
| 271 | if self.len() < max_fixed_colors { |
| 272 | let needs_extra = max_fixed_colors - self.len(); |
| 273 | self.colors.extend(fixed_colors.iter().copied().take(needs_extra)); |
| 274 | self.pops.extend(std::iter::repeat(PalPop::new(0.)).take(needs_extra)); |
| 275 | debug_assert_eq!(self.len(), max_fixed_colors); |
| 276 | } |
| 277 | |
| 278 | // since the fixed colors were in the histogram, expect them to be in the palette, |
| 279 | // and change closest existing one to be exact fixed |
| 280 | for (i, fixed_color) in fixed_colors.iter().enumerate().take(self.len()) { |
| 281 | let (best_idx, _) = self.colors.iter().enumerate().skip(i).min_by_key(|(_, pal_color)| { |
| 282 | // not using Nearest, because creation of the index may take longer than naive search once |
| 283 | OrdFloat::new(pal_color.diff(fixed_color)) |
| 284 | }).expect("logic bug in fixed colors, please report a bug"); |
| 285 | debug_assert!(best_idx >= i); |
| 286 | self.swap(i, best_idx); |
| 287 | self.set(i, *fixed_color, self.pops[i].to_fixed()); |
| 288 | } |
| 289 | |
| 290 | debug_assert!(self.colors.iter().zip(fixed_colors).all(|(p, f)| p == f)); |
| 291 | debug_assert!(self.pops.iter().take(fixed_colors.len()).all(|pop| pop.is_fixed())); |
| 292 | self |
| 293 | } |
| 294 | |
| 295 | #[inline(always)] |
| 296 | pub(crate) fn len(&self) -> usize { |