Ensure that transparent colours always come first

This commit is contained in:
Gwilym Inzani 2024-09-25 11:40:54 +01:00
parent 7b6556b381
commit c834e2907d

View file

@ -62,12 +62,15 @@ impl Palette16 {
self.colours.iter() self.colours.iter()
} }
fn union_length(&self, other: &Palette16) -> usize { fn with_transparent(&self, transparent_colour: Colour) -> Self {
self.colours let mut new_colours = self.colours.clone();
let transparent_colour_index = new_colours
.iter() .iter()
.chain(&other.colours) .position(|&c| c == transparent_colour)
.collect::<HashSet<_>>() .expect("Could not find tranparent colour in palette");
.len() new_colours.swap(0, transparent_colour_index);
Self::from(&new_colours)
} }
fn is_satisfied_by(&self, other: &Palette16) -> bool { fn is_satisfied_by(&self, other: &Palette16) -> bool {
@ -140,16 +143,17 @@ impl Palette16Optimiser {
} }
pub fn optimise_palettes(&self) -> Result<Palette16OptimisationResults, DoesNotFitError> { pub fn optimise_palettes(&self) -> Result<Palette16OptimisationResults, DoesNotFitError> {
let transparent_colour = self
.transparent_colour
.unwrap_or_else(|| Colour::from_rgb(255, 0, 255, 0));
let palettes_to_optimise = self let palettes_to_optimise = self
.palettes .palettes
.iter() .iter()
.cloned() .cloned()
.map(|mut palette| { .map(|mut palette| {
// ensure each palette we're creating the covering for has the transparent colour in it // ensure each palette we're creating the covering for has the transparent colour in it
palette.add_colour( palette.add_colour(transparent_colour);
self.transparent_colour
.unwrap_or_else(|| Colour::from_rgb(255, 0, 255, 0)),
);
palette palette
}) })
.collect::<HashSet<Palette16>>() .collect::<HashSet<Palette16>>()
@ -168,7 +172,7 @@ impl Palette16Optimiser {
.iter() .iter()
.map(|packed_palette| { .map(|packed_palette| {
let colours = packed_palette.unique_symbols(&palettes_to_optimise); let colours = packed_palette.unique_symbols(&palettes_to_optimise);
Palette16::from(colours) Palette16::from(colours).with_transparent(transparent_colour)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -214,8 +218,8 @@ mod test {
use super::*; use super::*;
quickcheck! { quickcheck! {
fn less_than_256_colours_always_fits(palettes: Vec<Palette16>) -> bool { fn less_than_256_colours_always_fits(palettes: Vec<Palette16>, transparent_colour: Colour) -> bool {
let mut optimiser = Palette16Optimiser::new(None); let mut optimiser = Palette16Optimiser::new(Some(transparent_colour));
for palette in palettes.clone().into_iter().take(16) { for palette in palettes.clone().into_iter().take(16) {
optimiser.add_palette(palette); optimiser.add_palette(palette);
} }
@ -229,6 +233,10 @@ mod test {
if !palette.is_satisfied_by(optimised_palette) { if !palette.is_satisfied_by(optimised_palette) {
return false; return false;
} }
if optimised_palette.colour_index(transparent_colour) != 0 {
return false;
}
} }
true true