299 lines
10 KiB
Rust
299 lines
10 KiB
Rust
use std::collections::HashMap;
|
||
use std::path::{Path, PathBuf};
|
||
|
||
use crate::champions::{card_portrait_path, file_names, save_image, valid_art_key};
|
||
use crate::{ChampionSource, Error, SourceError, Tracker};
|
||
use image::imageops::{self, FilterType};
|
||
use image::{DynamicImage, GrayImage};
|
||
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
pub struct Splash {
|
||
pub path: PathBuf,
|
||
pub focus: SplashFocus,
|
||
}
|
||
|
||
pub(crate) fn splashes_dir(portraits: &Path) -> PathBuf {
|
||
portraits.join("splashes")
|
||
}
|
||
|
||
/// A single rename publishes both the original JPEG and its focus: key.x.y.jpg.
|
||
pub(crate) fn cached_splashes(dir: &Path) -> HashMap<String, Splash> {
|
||
file_names(dir)
|
||
.filter_map(|name| {
|
||
let stem = name.to_str()?.strip_suffix(".jpg")?;
|
||
let (key, point) = stem.split_once('.')?;
|
||
let (x, y) = point.split_once('.')?;
|
||
let focus = SplashFocus {
|
||
x: x.parse().ok()?,
|
||
y: y.parse().ok()?,
|
||
};
|
||
(focus.x <= 100 && focus.y <= 100).then(|| {
|
||
(
|
||
key.to_owned(),
|
||
Splash {
|
||
path: dir.join(&name),
|
||
focus,
|
||
},
|
||
)
|
||
})
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
enum LoadingArt {
|
||
Template(GrayImage),
|
||
NotFound,
|
||
}
|
||
|
||
impl Tracker {
|
||
/// Notifies the worker when the catalog refresh ends (cached data is usable offline),
|
||
/// then reports each card and splash attempt while online.
|
||
pub fn refresh_champion_art(
|
||
&self,
|
||
catalog_ready: impl FnOnce(),
|
||
on_attempt: &mut dyn FnMut(bool),
|
||
) -> Result<(), Error> {
|
||
let catalog = self.refresh_champions();
|
||
catalog_ready();
|
||
catalog?;
|
||
let Some((source, portraits_dir)) = &self.champions else {
|
||
return Ok(());
|
||
};
|
||
let mut loading = HashMap::new();
|
||
if !self.download_cards(on_attempt, |key, image| {
|
||
let art = match image {
|
||
Some(image) => LoadingArt::Template(loading_template(image)),
|
||
None => LoadingArt::NotFound,
|
||
};
|
||
loading.insert(key.to_owned(), art);
|
||
})? {
|
||
return Ok(());
|
||
}
|
||
let dir = splashes_dir(portraits_dir);
|
||
std::fs::create_dir_all(&dir)
|
||
.map_err(|e| Error::Storage(format!("{} : {e}", dir.display())))?;
|
||
let cached = cached_splashes(&dir);
|
||
for champion in self.cached_champions()? {
|
||
let key = champion.key;
|
||
if !valid_art_key(&key) || cached.contains_key(&key) {
|
||
continue;
|
||
}
|
||
let saved = download_splash(
|
||
source.as_ref(),
|
||
&dir,
|
||
&key,
|
||
loading.remove(&key),
|
||
&card_portrait_path(portraits_dir, &key),
|
||
);
|
||
on_attempt(matches!(saved, Ok(true)));
|
||
if matches!(saved, Err(SourceError::Network(_))) {
|
||
break;
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
fn download_splash(
|
||
source: &dyn ChampionSource,
|
||
dir: &Path,
|
||
key: &str,
|
||
loading: Option<LoadingArt>,
|
||
card: &Path,
|
||
) -> Result<bool, SourceError> {
|
||
let template = match loading {
|
||
Some(LoadingArt::Template(template)) => Some(template),
|
||
Some(LoadingArt::NotFound) => None,
|
||
// Cards from earlier launches only contain the cropped art.
|
||
None if card.is_file() => match source.card_portrait(key) {
|
||
Ok(bytes) => {
|
||
let Some(art) = decode_jpeg(&bytes) else {
|
||
return Ok(false);
|
||
};
|
||
Some(loading_template(&art))
|
||
}
|
||
Err(SourceError::NotFound) => None,
|
||
Err(error) => return Err(error),
|
||
},
|
||
None => return Ok(false),
|
||
};
|
||
let jpeg = source.splash(key)?;
|
||
let Some(image) = decode_jpeg(&jpeg) else {
|
||
return Ok(false);
|
||
};
|
||
let focus = template.map_or(FALLBACK, |art| locate(&image, &art));
|
||
let path = dir.join(format!("{key}.{}.{}.jpg", focus.x, focus.y));
|
||
Ok(save_image(&path, &jpeg))
|
||
}
|
||
|
||
/// Point on the champion, in whole percentages from the splash's top left.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub struct SplashFocus {
|
||
pub x: u8,
|
||
pub y: u8,
|
||
}
|
||
|
||
const FALLBACK: SplashFocus = SplashFocus { x: 50, y: 30 };
|
||
|
||
/// Position and size of the full splash relative to the banner's image area.
|
||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||
pub struct BannerFrame {
|
||
pub left: f32,
|
||
pub top: f32,
|
||
pub width: f32,
|
||
pub height: f32,
|
||
}
|
||
|
||
impl SplashFocus {
|
||
pub fn banner_frame(self, area_width: f32, area_height: f32) -> BannerFrame {
|
||
const SPLASH_WIDTH: f32 = 1215.0;
|
||
const SPLASH_HEIGHT: f32 = 717.0;
|
||
const VISIBLE_WIDTH_FRACTION: f32 = 0.8;
|
||
let scale =
|
||
(area_width / (SPLASH_WIDTH * VISIBLE_WIDTH_FRACTION)).max(area_height / SPLASH_HEIGHT);
|
||
let width = SPLASH_WIDTH * scale;
|
||
let height = SPLASH_HEIGHT * scale;
|
||
let offset = |area: f32, size: f32, percent: u8| {
|
||
(area * 0.5 - size * f32::from(percent) / 100.0)
|
||
.max(area - size)
|
||
.min(0.0)
|
||
};
|
||
BannerFrame {
|
||
left: offset(area_width, width, self.x),
|
||
top: offset(area_height, height, self.y),
|
||
width,
|
||
height,
|
||
}
|
||
}
|
||
}
|
||
|
||
fn decode_jpeg(bytes: &[u8]) -> Option<DynamicImage> {
|
||
image::load_from_memory_with_format(bytes, image::ImageFormat::Jpeg).ok()
|
||
}
|
||
|
||
fn loading_template(image: &DynamicImage) -> GrayImage {
|
||
image.resize(64, 64, FilterType::CatmullRom).into_luma8()
|
||
}
|
||
|
||
/// Match the full loading art at 70–100% of splash height using zero-mean normalized correlation.
|
||
fn locate(image: &DynamicImage, template: &GrayImage) -> SplashFocus {
|
||
let (w, h) = template.dimensions();
|
||
let mut best = FALLBACK;
|
||
let mut best_score = 0.6;
|
||
let n = f64::from(w * h);
|
||
let sum: u32 = template.iter().map(|&v| u32::from(v)).sum();
|
||
let squares: u32 = template.iter().map(|&v| u32::from(v).pow(2)).sum();
|
||
let variance = f64::from(squares) - f64::from(sum).powi(2) / n;
|
||
if variance <= 0.0 {
|
||
return FALLBACK;
|
||
}
|
||
let splash = image.resize(160, 96, FilterType::CatmullRom).into_luma8();
|
||
for step in 14..=20 {
|
||
let sh = (h * 20 + step / 2) / step;
|
||
let sw = (sh as f32 * image.width() as f32 / image.height() as f32).round() as u32;
|
||
if sw < w || sw > 160 {
|
||
continue;
|
||
}
|
||
let splash = imageops::resize(&splash, sw, sh, FilterType::Triangle);
|
||
for y in 0..=sh - h {
|
||
for x in 0..=sw - w {
|
||
let mut window_sum = 0u32;
|
||
let mut window_squares = 0u32;
|
||
let mut dot = 0u32;
|
||
for (dy, row) in template.as_raw().chunks_exact(w as usize).enumerate() {
|
||
let start = (y as usize + dy) * sw as usize + x as usize;
|
||
for (&a, &b) in row.iter().zip(&splash.as_raw()[start..start + w as usize]) {
|
||
let b = u32::from(b);
|
||
window_sum += b;
|
||
window_squares += b * b;
|
||
dot += u32::from(a) * b;
|
||
}
|
||
}
|
||
let window_variance = f64::from(window_squares) - f64::from(window_sum).powi(2) / n;
|
||
if window_variance <= 0.0 {
|
||
continue;
|
||
}
|
||
let covariance = f64::from(dot) - f64::from(sum) * f64::from(window_sum) / n;
|
||
let score = covariance / (variance * window_variance).sqrt();
|
||
if score >= best_score {
|
||
best_score = score;
|
||
best = SplashFocus {
|
||
x: ((x as f32 + 0.5 * w as f32) * 100.0 / sw as f32).round() as u8,
|
||
y: ((y as f32 + 0.30 * h as f32) * 100.0 / sh as f32).round() as u8,
|
||
};
|
||
}
|
||
}
|
||
}
|
||
}
|
||
best
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use image::{GrayImage, Luma};
|
||
|
||
#[test]
|
||
fn unrelated_images_and_featureless_art_use_the_fixed_focus() {
|
||
let splash = GrayImage::from_fn(96, 60, |x, _| Luma([(x * 2) as u8]));
|
||
let stripes = GrayImage::from_fn(27, 40, |_, y| Luma([(y * 5) as u8]));
|
||
let flat = GrayImage::new(27, 40);
|
||
for card in [&stripes, &flat] {
|
||
assert_eq!(
|
||
locate(&DynamicImage::ImageLuma8(splash.clone()), card),
|
||
SplashFocus { x: 50, y: 30 }
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn the_banner_centres_the_focus_and_stops_at_each_edge() {
|
||
for (x, left) in [(5, 0.0), (50, -121.5), (95, -243.0)] {
|
||
let frame = SplashFocus { x, y: 30 }.banner_frame(972.0, 200.0);
|
||
assert_eq!(
|
||
(frame.left, frame.width, frame.height),
|
||
(left, 1215.0, 717.0)
|
||
);
|
||
assert!((frame.top + 115.1).abs() < 0.01);
|
||
}
|
||
let narrow = SplashFocus { x: 50, y: 95 }.banner_frame(100.0, 717.0);
|
||
assert_eq!(
|
||
(narrow.left, narrow.top, narrow.width, narrow.height),
|
||
(-557.5, 0.0, 1215.0, 717.0)
|
||
);
|
||
assert_eq!(
|
||
SplashFocus { x: 50, y: 0 }.banner_frame(972.0, 200.0).top,
|
||
0.0
|
||
);
|
||
assert_eq!(
|
||
SplashFocus { x: 50, y: 100 }.banner_frame(972.0, 200.0).top,
|
||
-517.0
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn locates_full_size_loading_art_at_both_ends_of_the_scale_range() {
|
||
let art = image::RgbImage::from_fn(308, 560, |x, y| {
|
||
let value = ((((x / 32) * 71) ^ ((y / 32) * 59)) % 150) as u8;
|
||
image::Rgb([value, 150 - value, value / 2])
|
||
});
|
||
let template = loading_template(&DynamicImage::ImageRgb8(art.clone()));
|
||
for (w, h, x, y, expected) in [
|
||
(276, 502, 735, 108, SplashFocus { x: 72, y: 36 }),
|
||
(394, 717, 180, 0, SplashFocus { x: 31, y: 30 }),
|
||
] {
|
||
let mut patch = imageops::resize(&art, w, h, FilterType::Triangle);
|
||
for pixel in patch.as_mut() {
|
||
*pixel += 60;
|
||
}
|
||
let mut splash = image::RgbImage::new(1215, 717);
|
||
imageops::replace(&mut splash, &patch, x, y);
|
||
let focus = locate(&DynamicImage::ImageRgb8(splash), &template);
|
||
assert!(
|
||
focus.x.abs_diff(expected.x) <= 1 && focus.y.abs_diff(expected.y) <= 1,
|
||
"{focus:?}, expected {expected:?}"
|
||
);
|
||
}
|
||
}
|
||
}
|