use std::collections::VecDeque;
use f_office_paint::{LinearLimit, Resampler};
type Weights = Vec<Vec<(usize, f64)>>;
pub fn resample_by(
resampler: Resampler,
samples: &[u8],
own: (usize, usize),
channels: usize,
size: (usize, usize),
) -> Vec<u8> {
match resampler {
Resampler::Filter(limit) => resample(samples, own, channels, size, limit),
Resampler::CentrePixel => centre_pixels(samples, own, channels, size),
}
}
pub fn centre_pixels(
samples: &[u8],
own: (usize, usize),
channels: usize,
size: (usize, usize),
) -> Vec<u8> {
let under = |at: usize, from: usize, to: usize| (2 * at + 1) * from / (2 * to);
let mut out = Vec::with_capacity(size.0 * size.1 * channels);
for y in 0..size.1 {
let row = under(y, own.1, size.1) * own.0;
for x in 0..size.0 {
let start = (row + under(x, own.0, size.0)) * channels;
out.extend_from_slice(samples.get(start..start + channels).unwrap_or_default());
}
}
out
}
pub fn resample(
samples: &[u8],
own: (usize, usize),
channels: usize,
size: (usize, usize),
limit: LinearLimit,
) -> Vec<u8> {
let linear = limit.takes_linear(own);
let weights = |from: usize, to: usize| {
if linear {
linear_weights(from, to)
} else {
area_weights(from, to)
}
};
let (across, down) = (weights(own.0, size.0), weights(own.1, size.1));
passes(samples, own, channels, (&across, &down), linear)
}
pub fn resample_part_at_scale(
samples: &[u8],
own: (usize, usize),
channels: usize,
part: [usize; 4],
size: (usize, usize),
) -> Vec<u8> {
let [left, top, right, bottom] = part;
let (part_width, part_height) = (right.saturating_sub(left), bottom.saturating_sub(top));
let scaled = (
scaled_count(own.0, size.0, part_width),
scaled_count(own.1, size.1, part_height),
);
let first = passes(
samples,
own,
channels,
(
&area_weights(own.0, scaled.0),
&area_weights(own.1, scaled.1),
),
false,
);
let across = placed_weights(left, size.0, part_width, scaled.0);
let down = placed_weights(top, size.1, part_height, scaled.1);
passes(&first, scaled, channels, (&across, &down), true)
}
fn passes(
samples: &[u8],
own: (usize, usize),
channels: usize,
(across, down): (&Weights, &Weights),
linear: bool,
) -> Vec<u8> {
let row = own.0 * channels;
let mut pass_down = PassDown::new(down, own.1, across.len() * channels);
let mut across_row = vec![0.0; across.len() * channels];
for y in 0..own.1 {
let source = samples.get(y * row..(y + 1) * row).unwrap_or_default();
pass_across(source, (across, channels, linear), &mut across_row);
pass_down.take(y, &across_row);
}
pass_down.finish()
}
fn scaled_count(whole: usize, written: usize, part: usize) -> usize {
let part = part.max(1);
let doubled = whole.saturating_mul(written).saturating_mul(2);
(doubled.saturating_add(part) / part.saturating_mul(2)).max(1)
}
fn placed_weights(first: usize, to: usize, part: usize, from: usize) -> Weights {
let last = from.saturating_sub(1);
let start = index(first) * ratio(to, part);
(0..to)
.map(|x| {
let place = (start + index(x)).min(index(last));
let left = place.floor();
let share = place - left;
let left = whole(left).min(last);
vec![(left, 1.0 - share), ((left + 1).min(last), share)]
})
.collect()
}
fn pass_across(
source: &[u8],
(across, channels, linear): (&Weights, usize, bool),
row: &mut [f64],
) {
let pixels = row.chunks_exact_mut(channels.max(1));
for (taps, pixel) in across.iter().zip(pixels) {
for (c, sample) in pixel.iter_mut().enumerate() {
let value = taps
.iter()
.map(|&(at, w)| f64::from(source.get(at * channels + c).copied().unwrap_or(0)) * w)
.sum::<f64>();
*sample = if linear {
value
} else {
value.round_ties_even()
};
}
}
}
struct PassDown {
takers: Vec<Vec<(usize, f64)>>,
last: Vec<Option<usize>>,
open: VecDeque<Vec<f64>>,
written: usize,
line: usize,
out: Vec<u8>,
}
impl PassDown {
fn new(down: &Weights, rows: usize, line: usize) -> Self {
let mut takers = vec![Vec::new(); rows];
for (output, taps) in down.iter().enumerate() {
for &(at, w) in taps {
if let Some(taker) = takers.get_mut(at) {
taker.push((output, w));
}
}
}
Self {
takers,
last: down
.iter()
.map(|taps| taps.iter().map(|&(at, _)| at).max())
.collect(),
open: VecDeque::new(),
written: 0,
line,
out: Vec::with_capacity(down.len() * line),
}
}
fn take(&mut self, y: usize, row: &[f64]) {
for &(output, w) in self.takers.get(y).map_or(&[][..], Vec::as_slice) {
while self.written + self.open.len() <= output {
self.open.push_back(vec![-0.0; self.line]);
}
if let Some(sum) = self.open.get_mut(output - self.written) {
for (total, &value) in sum.iter_mut().zip(row) {
*total += value * w;
}
}
}
while let Some(&last) = self.last.get(self.written)
&& last.is_none_or(|at| at <= y)
{
self.write_next();
}
}
fn write_next(&mut self) {
match self.open.pop_front() {
Some(sum) => self.out.extend(sum.into_iter().map(level)),
None => self.out.extend(std::iter::repeat_n(0, self.line)),
}
self.written += 1;
}
fn finish(mut self) -> Vec<u8> {
while self.written < self.last.len() {
self.write_next();
}
self.out
}
}
fn level(value: f64) -> u8 {
let rounded = value.round_ties_even().clamp(0.0, 255.0);
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "clamped to 0..=255"
)]
let level = rounded as u8;
level
}
fn linear_weights(from: usize, to: usize) -> Weights {
let scale = ratio(from, to);
(0..to)
.map(|x| {
let place = index(x) * scale;
let left = place.floor();
let share = place - left;
let left = whole(left).min(from - 1);
vec![(left, 1.0 - share), ((left + 1).min(from - 1), share)]
})
.collect()
}
fn area_weights(from: usize, to: usize) -> Weights {
let scale = ratio(from, to);
(0..to)
.map(|x| {
let (low, high) = (index(x) * scale, index(x + 1) * scale);
let mut taps: Vec<(usize, f64)> = (whole(low.floor())..whole(high.ceil()).min(from))
.map(|at| {
let cover = high.min(index(at + 1)) - low.max(index(at));
(at, cover.max(0.0))
})
.collect();
let total: f64 = taps.iter().map(|&(_, w)| w).sum();
if total > 0.0 {
for tap in &mut taps {
tap.1 /= total;
}
}
taps
})
.collect()
}
fn ratio(from: usize, to: usize) -> f64 {
index(from) / index(to.max(1))
}
#[expect(
clippy::cast_precision_loss,
reason = "picture sizes stay far below 2^52"
)]
const fn index(i: usize) -> f64 {
i as f64
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "whole and non-negative"
)]
const fn whole(value: f64) -> usize {
value as usize
}
#[cfg(test)]
mod tests;