use std::hash::Hasher;
use image::DynamicImage;
use rustc_hash::FxHasher;
use crate::{
algorithms::polygon::compute_convex_hull,
types::{
config::{SpriteConfig, TrimMode},
rect::SourceRect,
sprite::Sprite,
},
};
pub fn trim(sprite: &mut Sprite, config: &SpriteConfig) {
if matches!(config.trim_mode, TrimMode::None) {
return;
}
let rgba = match sprite.image.as_rgba8() {
Some(img) => img,
None => return,
};
let (img_w, img_h) = rgba.dimensions();
let Some((mut x1, mut y1, mut x2, mut y2)) = find_opaque_bounds(rgba, config.trim_threshold)
else {
return;
};
let m = config.trim_margin;
x1 = x1.saturating_sub(m);
y1 = y1.saturating_sub(m);
x2 = (x2 + m).min(img_w - 1);
y2 = (y2 + m).min(img_h - 1);
let tw = expand_to_divisor(x2 - x1 + 1, config.common_divisor_x).min(img_w - x1);
let th = expand_to_divisor(y2 - y1 + 1, config.common_divisor_y).min(img_h - y1);
sprite.trim_rect = Some(SourceRect {
x: x1 as i32,
y: y1 as i32,
w: tw,
h: th,
});
let cropped = image::imageops::crop_imm(rgba, x1, y1, tw, th).to_image();
if matches!(config.trim_mode, TrimMode::Polygon) {
sprite.polygon = Some(compute_convex_hull(&cropped, config.trim_threshold));
}
let mut h = FxHasher::default();
h.write(cropped.as_raw());
sprite.content_hash = h.finish();
sprite.image = DynamicImage::ImageRgba8(cropped);
}
fn find_opaque_bounds(img: &image::RgbaImage, threshold: u8) -> Option<(u32, u32, u32, u32)> {
let (w, h) = img.dimensions();
let mut x1 = u32::MAX;
let mut y1 = u32::MAX;
let mut x2 = 0u32;
let mut y2 = 0u32;
let mut found = false;
for y in 0..h {
for x in 0..w {
if img.get_pixel(x, y)[3] > threshold {
if !found {
x1 = x;
y1 = y;
x2 = x;
y2 = y;
found = true;
} else {
if x < x1 {
x1 = x;
}
if x > x2 {
x2 = x;
}
if y > y2 {
y2 = y;
}
}
}
}
}
if found { Some((x1, y1, x2, y2)) } else { None }
}
fn expand_to_divisor(size: u32, divisor: u32) -> u32 {
if divisor <= 1 {
return size;
}
let r = size % divisor;
if r == 0 { size } else { size + (divisor - r) }
}