use std::sync::Arc;
use super::blend::composite as blend;
use super::frames::FramePool;
use super::half;
use super::image::{CpuImage, PixelBox, Texels};
use super::workers::Workers;
use crate::{BlendMode, BlendSpace, Color, LayerTransform, RenderError, RenderSize};
const NEARLY_OPAQUE: f32 = 1.0 - 1.0 / 256.0;
pub(crate) struct LayerInput<'a> {
pub(crate) image: &'a CpuImage,
pub(crate) visual: LayerTransform,
pub(crate) blend_mode: BlendMode,
}
#[derive(Copy, Clone)]
pub(crate) struct CompositeSettings {
pub(crate) size: RenderSize,
pub(crate) background: Option<Color>,
pub(crate) blend_space: BlendSpace,
pub(crate) max_filter_samples: u32,
}
pub(crate) fn composite(
workers: &Workers,
frames: &Arc<FramePool>,
layers: &[LayerInput<'_>],
settings: CompositeSettings,
) -> Result<CpuImage, RenderError> {
let size = settings.size;
let prepared = prepared_layers(layers, settings)?;
let background =
crate::composite::stored_background(settings.background, wgpu::TextureFormat::Rgba16Float);
let bounds = if settings.background.is_some() {
PixelBox::whole(size)
} else {
prepared
.iter()
.fold(PixelBox::EMPTY, |union, layer| union.union(layer.bounds))
};
if bounds.is_empty() {
return Ok(CpuImage::transparent(size));
}
let fill = half::store4(background);
let mut pixels = frames.take(bounds.pixels());
let width = bounds.width as usize;
let linear_light = settings.blend_space == BlendSpace::LinearLight;
let new_caches = || {
prepared
.iter()
.map(|_| RowCache::default())
.collect::<Vec<_>>()
};
let row_work_pixels = width
+ prepared
.iter()
.map(PreparedLayer::row_work_pixels)
.sum::<usize>();
let draw_band = |caches: &mut Vec<RowCache>, first_row: usize, band: &mut [[u16; 4]]| {
band.fill(fill);
for cache in caches.iter_mut() {
cache.reset();
}
for (index, line) in band.chunks_mut(width).enumerate() {
#[allow(clippy::cast_possible_truncation)]
let y = bounds.y + (first_row + index) as u32;
for (layer, cache) in prepared.iter().zip(caches.iter_mut()) {
layer.draw_row(y, bounds, line, cache, linear_light);
}
}
};
workers.weighted_bands_with(&mut pixels, width, row_work_pixels, new_caches, draw_band);
Ok(CpuImage::pooled(size, bounds, pixels, frames))
}
pub(super) fn prepared_layers<'a>(
layers: &[LayerInput<'a>],
settings: CompositeSettings,
) -> Result<Vec<PreparedLayer<'a>>, RenderError> {
for layer in layers {
crate::composite::validate_visual(layer.visual)?;
}
Ok(layers
.iter()
.filter(|layer| {
!crate::composite::is_degenerate(layer.visual)
&& !crate::composite::is_invisible(layer.visual)
})
.filter_map(|layer| {
let bounds = crate::composite::layer_bounds(layer.visual, settings.size)?;
let bounds = PixelBox {
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height,
};
let bounds = bounds.intersect(content_bounds(layer, settings.size)?);
(!bounds.is_empty()).then(|| PreparedLayer::new(layer, bounds, settings))
})
.collect())
}
fn content_bounds(layer: &LayerInput<'_>, size: RenderSize) -> Option<PixelBox> {
let image = layer.image;
let content = image.bounds();
if content.is_empty() {
return None;
}
let source = image.size();
if content == PixelBox::whole(source) {
return Some(PixelBox::whole(size));
}
let visual = layer.visual;
let (width, height) = (f64::from(size.width), f64::from(size.height));
let texel = (f64::from(visual.scale[0]).abs() * width / f64::from(source.width))
.max(f64::from(visual.scale[1]).abs() * height / f64::from(source.height));
let margin = 4.0 + 2.0 * texel.max(1.0);
let (turn_sin, turn_cos) = libm::sincos(f64::from(visual.rotation_degrees).to_radians());
let corner = |u: f64, v: f64| {
let x = (u - f64::from(visual.anchor[0])) * f64::from(visual.scale[0]) * width;
let y = (v - f64::from(visual.anchor[1])) * f64::from(visual.scale[1]) * height;
(
f64::from(visual.position[0]) * width + turn_cos * x - turn_sin * y,
f64::from(visual.position[1]) * height + turn_sin * x + turn_cos * y,
)
};
let (u0, u1) = (
f64::from(content.x) / f64::from(source.width),
f64::from(content.right()) / f64::from(source.width),
);
let (v0, v1) = (
f64::from(content.y) / f64::from(source.height),
f64::from(content.bottom()) / f64::from(source.height),
);
let corners = [
corner(u0, v0),
corner(u1, v0),
corner(u0, v1),
corner(u1, v1),
];
let fold = |pick: fn(&(f64, f64)) -> f64, extreme: fn(f64, f64) -> f64, start: f64| {
corners.iter().map(pick).fold(start, extreme)
};
let left = (fold(|c| c.0, f64::min, f64::INFINITY) - margin)
.floor()
.max(0.0);
let top = (fold(|c| c.1, f64::min, f64::INFINITY) - margin)
.floor()
.max(0.0);
let right = (fold(|c| c.0, f64::max, f64::NEG_INFINITY) + margin)
.ceil()
.min(width);
let bottom = (fold(|c| c.1, f64::max, f64::NEG_INFINITY) + margin)
.ceil()
.min(height);
if !(right > left && bottom > top) {
return None;
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Some(PixelBox {
x: left as u32,
y: top as u32,
width: (right - left) as u32,
height: (bottom - top) as u32,
})
}
#[derive(Default)]
struct AxisTaps {
spans: Vec<(u32, u32)>,
taps: Vec<(u32, f32)>,
}
impl AxisTaps {
fn taps(&self, position: usize) -> &[(u32, f32)] {
let (start, end) = self.spans[position];
&self.taps[start as usize..end as usize]
}
fn most_taps(&self) -> usize {
self.spans
.iter()
.map(|(start, end)| (end - start) as usize)
.max()
.unwrap_or(0)
}
fn reach(&self) -> Option<(u32, u32)> {
let first = self.taps.iter().map(|(index, _)| *index).min()?;
let last = self.taps.iter().map(|(index, _)| *index).max()?;
Some((first, last))
}
}
#[derive(Default)]
pub(super) struct RowCache {
rows: Vec<(u32, Vec<[f32; 4]>)>,
decoded: Vec<[f32; 4]>,
spare: Vec<Vec<[f32; 4]>>,
}
impl RowCache {
pub(super) fn reset(&mut self) {
self.spare
.extend(self.rows.drain(..).map(|(_, filtered)| filtered));
}
fn forget_rows_outside(&mut self, taps: &[(u32, f32)]) {
let mut index = 0;
while index < self.rows.len() {
if taps.iter().any(|(row, _)| *row == self.rows[index].0) {
index += 1;
} else {
self.spare.push(self.rows.swap_remove(index).1);
}
}
}
fn ensure(
&mut self,
row: u32,
image: &CpuImage,
columns: &AxisTaps,
shared: Option<&mut DecodedRows>,
) {
if self.rows.iter().any(|(held, _)| *held == row) {
return;
}
let Some((first, last)) = columns.reach() else {
return;
};
let (decoded, decoded_from) = if let Some(shared) = shared {
let decoded_from = shared.first;
(shared.row(image, row), decoded_from)
} else {
self.decoded.resize((last - first + 1) as usize, [0.0; 4]);
image.decode_row(row, first, &mut self.decoded);
(self.decoded.as_slice(), first)
};
let mut filtered = self.spare.pop().unwrap_or_default();
filtered.clear();
filtered.extend((0..columns.spans.len()).map(|column| {
let mut sum = [0.0_f32; 4];
for &(texel, weight) in columns.taps(column) {
let value = decoded[(texel - decoded_from) as usize];
for channel in 0..4 {
sum[channel] += value[channel] * weight;
}
}
sum
}));
self.rows.push((row, filtered));
}
fn row(&self, row: u32) -> &[[f32; 4]] {
self.rows
.iter()
.find(|(held, _)| *held == row)
.map_or(&[], |(_, filtered)| filtered.as_slice())
}
}
const SHARED_DECODED_BYTES: usize = 4 * 1024 * 1024;
pub(super) struct DecodedRows {
first: u32,
width: usize,
most_rows: usize,
rows: Vec<(u32, Vec<[f32; 4]>)>,
oldest: usize,
}
impl DecodedRows {
pub(super) fn read_by(layers: &[PreparedLayer<'_>]) -> Option<Self> {
let (first, last) = layers
.iter()
.filter_map(|layer| match &layer.sampler {
Sampler::Separable { columns, .. } => columns.reach(),
Sampler::General(_) => None,
})
.reduce(|(first, last), (other_first, other_last)| {
(first.min(other_first), last.max(other_last))
})?;
let width = (last - first + 1) as usize;
Some(Self {
first,
width,
most_rows: (SHARED_DECODED_BYTES / (width * size_of::<[f32; 4]>())).clamp(8, 256),
rows: Vec::new(),
oldest: 0,
})
}
pub(super) fn reset(&mut self) {
for (row, _) in &mut self.rows {
*row = u32::MAX;
}
}
fn row(&mut self, image: &CpuImage, row: u32) -> &[[f32; 4]] {
let held = self.rows.iter().position(|(held, _)| *held == row);
let index = held.unwrap_or_else(|| {
let index = if self.rows.len() < self.most_rows {
self.rows.push((row, vec![[0.0; 4]; self.width]));
self.rows.len() - 1
} else {
let index = self.oldest;
self.oldest = (self.oldest + 1) % self.most_rows;
index
};
let (held, decoded) = &mut self.rows[index];
*held = row;
image.decode_row(row, self.first, decoded);
index
});
&self.rows[index].1
}
}
enum Sampler {
Separable { columns: AxisTaps, rows: AxisTaps },
General(General),
}
struct General {
position_y: f32,
anchor: [f32; 2],
scale: [f32; 2],
cosine: f32,
sine: f32,
output: [f32; 2],
gate_footprint: [f32; 2],
footprint: [f32; 2],
turned_columns: Vec<TurnedColumn>,
sample_steps: Vec<SampleStep>,
samples: f32,
}
#[derive(Copy, Clone)]
struct TurnedColumn {
along_x: f32,
along_y: f32,
}
#[derive(Copy, Clone)]
struct SampleStep {
across_columns: [f32; 2],
across_rows: [f32; 2],
}
pub(super) struct PreparedLayer<'a> {
image: &'a CpuImage,
texels: Texels<'a>,
halves: &'static [f32; 65_536],
blend_mode: BlendMode,
opacity: f32,
pub(super) bounds: PixelBox,
sampler: Sampler,
}
#[inline]
fn coverage(position: f32, footprint: f32) -> f32 {
let width = footprint.max(0.000_000_1);
let half_width = width * 0.5;
let past_the_end = position + half_width - 1.0;
let before_the_start = half_width - position;
if past_the_end <= 0.0 && before_the_start <= 0.0 {
return 1.0;
}
let cut = past_the_end.max(0.0) + before_the_start.max(0.0);
(1.0 - cut / width).clamp(0.0, 1.0)
}
const MOST_AXIS_SAMPLES: usize = 8;
const MOST_AXIS_TAPS: usize = 2 * MOST_AXIS_SAMPLES;
#[allow(clippy::cast_precision_loss)]
fn filter_grid(dx: [f32; 2], dy: [f32; 2], dimensions: [f32; 2], budget: u32) -> [f32; 2] {
let length = |v: [f32; 2]| (v[0] * v[0] + v[1] * v[1]).sqrt();
let wanted_x = (length([dx[0] * dimensions[0], dx[1] * dimensions[1]]) - 0.0001)
.ceil()
.clamp(1.0, MOST_AXIS_SAMPLES as f32);
let wanted_y = (length([dy[0] * dimensions[0], dy[1] * dimensions[1]]) - 0.0001)
.ceil()
.clamp(1.0, MOST_AXIS_SAMPLES as f32);
let budget = (budget as f32).clamp(1.0, 64.0);
let nx = wanted_x.min(budget);
let ny = wanted_y.min((budget / nx).floor().max(1.0));
[nx, ny]
}
impl<'a> PreparedLayer<'a> {
#[allow(clippy::cast_precision_loss)]
fn new(layer: &LayerInput<'a>, bounds: PixelBox, settings: CompositeSettings) -> Self {
let visual = layer.visual;
let output = [settings.size.width as f32, settings.size.height as f32];
let dimensions = [
layer.image.size().width as f32,
layer.image.size().height as f32,
];
let angle = visual.rotation_degrees.to_radians();
let (sine, cosine) = (libm::sinf(angle), libm::cosf(angle));
let scale = visual.scale;
let dx = [cosine / output[0] / scale[0], -sine / output[1] / scale[1]];
let dy = [sine / output[0] / scale[0], cosine / output[1] / scale[1]];
let grid = filter_grid(dx, dy, dimensions, settings.max_filter_samples);
let footprint = [
dx[0].abs() / grid[0] + dy[0].abs() / grid[1],
dx[1].abs() / grid[0] + dy[1].abs() / grid[1],
];
let sampler = if sine == 0.0 {
Sampler::Separable {
columns: axis_taps(
bounds.x..bounds.right(),
output[0],
visual.position[0],
scale[0],
visual.anchor[0],
dx[0],
grid[0],
footprint[0],
dimensions[0],
),
rows: axis_taps(
bounds.y..bounds.bottom(),
output[1],
visual.position[1],
scale[1],
visual.anchor[1],
dy[1],
grid[1],
footprint[1],
dimensions[1],
),
}
} else {
Sampler::General(General::new(
visual,
(cosine, sine),
output,
[dx, dy],
grid,
footprint,
bounds.x..bounds.right(),
))
};
Self {
image: layer.image,
texels: layer.image.texels(),
halves: half::table(),
blend_mode: layer.blend_mode,
opacity: visual.opacity,
bounds,
sampler,
}
}
fn draw_row(
&self,
y: u32,
bounds: PixelBox,
line: &mut [[u16; 4]],
cache: &mut RowCache,
linear_light: bool,
) {
self.sample_row(y, cache, None, |x, color| {
let out = &mut line[(x - bounds.x) as usize];
*out = self.composite_source(*out, self.at_opacity(color), linear_light);
});
}
#[inline]
pub(super) fn sample_row(
&self,
y: u32,
cache: &mut RowCache,
shared: Option<&mut DecodedRows>,
put: impl FnMut(u32, [f32; 4]),
) {
if y < self.bounds.y || y >= self.bounds.bottom() {
return;
}
match &self.sampler {
Sampler::Separable { columns, rows } => {
self.sample_separable_row(columns, rows, y, cache, shared, put);
}
Sampler::General(general) => general.sample_row(&self.texels, self.bounds.x, y, put),
}
}
#[inline]
fn sample_separable_row(
&self,
columns: &AxisTaps,
rows: &AxisTaps,
y: u32,
cache: &mut RowCache,
mut shared: Option<&mut DecodedRows>,
mut put: impl FnMut(u32, [f32; 4]),
) {
let first = self.bounds.x;
let row_taps = rows.taps((y - self.bounds.y) as usize);
if row_taps.is_empty() {
return;
}
cache.forget_rows_outside(row_taps);
for &(row, _) in row_taps {
cache.ensure(row, self.image, columns, shared.as_deref_mut());
}
let mut lines: [(&[[f32; 4]], f32); MOST_AXIS_TAPS] = [(&[], 0.0); MOST_AXIS_TAPS];
for (slot, &(row, weight)) in lines.iter_mut().zip(row_taps) {
*slot = (cache.row(row), weight);
}
let lines = &lines[..row_taps.len().min(MOST_AXIS_TAPS)];
for x in first..self.bounds.right() {
let column = (x - first) as usize;
if columns.spans[column].0 == columns.spans[column].1 {
continue;
}
let mut color = [0.0_f32; 4];
for &(filtered, row_weight) in lines {
let value = filtered[column];
for channel in 0..4 {
color[channel] += value[channel] * row_weight;
}
}
put(x, color);
}
}
pub(super) fn row_work_pixels(&self) -> usize {
let taps = match &self.sampler {
Sampler::Separable { columns, rows } => {
columns.most_taps().max(1) * rows.most_taps().max(1)
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a filter grid of at most 8 by 8"
)]
Sampler::General(general) => general.samples as usize * 4,
};
self.bounds.width as usize * taps
}
#[inline]
pub(super) fn at_opacity(&self, color: [f32; 4]) -> [f32; 4] {
color.map(|value| value * self.opacity)
}
#[inline(always)]
#[allow(clippy::inline_always)]
pub(super) fn composite_source(
&self,
backdrop: [u16; 4],
source: [f32; 4],
linear_light: bool,
) -> [u16; 4] {
if source[3] <= 0.0 {
return backdrop;
}
if self.blend_mode == BlendMode::Normal && source[3] >= NEARLY_OPAQUE {
let below = backdrop.map(|bits| self.halves[usize::from(bits)]);
let rest = 1.0 - source[3].min(1.0);
return [
half::store_nearest((source[0] + below[0] * rest).clamp(0.0, 1.0)),
half::store_nearest((source[1] + below[1] * rest).clamp(0.0, 1.0)),
half::store_nearest((source[2] + below[2] * rest).clamp(0.0, 1.0)),
half::store_nearest((source[3] + below[3] * rest).min(1.0)),
];
}
self.blend_pixel(backdrop, source, linear_light)
}
#[inline(never)]
fn blend_pixel(&self, backdrop: [u16; 4], source: [f32; 4], linear_light: bool) -> [u16; 4] {
half::store4_nearest(blend(
backdrop.map(|bits| self.halves[usize::from(bits)]),
source,
self.blend_mode,
linear_light,
))
}
}
#[allow(clippy::too_many_arguments, clippy::cast_precision_loss)]
fn axis_taps(
range: std::ops::Range<u32>,
output: f32,
position: f32,
scale: f32,
anchor: f32,
derivative: f32,
grid: f32,
footprint: f32,
dimension: f32,
) -> AxisTaps {
let mut taps = AxisTaps::default();
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let (samples, last) = (grid as u32, dimension as i64 - 1);
for pixel in range {
#[allow(clippy::cast_possible_truncation)]
let start = taps.taps.len() as u32;
let uv = (pixel as f32 + 0.5) / output;
let source = (uv - position) * output / output / scale + anchor;
if coverage(source, derivative.abs()) <= 0.0 {
taps.spans.push((start, start));
continue;
}
for sample in 0..samples {
let offset = (sample as f32 + 0.5) / grid - 0.5;
let point = source + derivative * offset;
let weight = coverage(point, footprint) / grid;
if weight <= 0.0 {
continue;
}
let texel = point * dimension - 0.5;
let origin = texel.floor();
let fraction = texel - origin;
#[allow(clippy::cast_possible_truncation)]
let origin = origin as i64;
for (index, tap_weight) in [(origin, 1.0 - fraction), (origin + 1, fraction)] {
if tap_weight <= 0.0 {
continue;
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let index = index.clamp(0, last) as u32;
let weight = weight * tap_weight;
match taps.taps[start as usize..]
.iter_mut()
.find(|(existing, _)| *existing == index)
{
Some((_, existing)) => *existing += weight,
None => taps.taps.push((index, weight)),
}
}
}
#[allow(clippy::cast_possible_truncation)]
taps.spans.push((start, taps.taps.len() as u32));
}
taps
}
impl General {
#[expect(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "pixel columns and a filter grid of at most 8 by 8"
)]
fn new(
visual: LayerTransform,
(cosine, sine): (f32, f32),
output: [f32; 2],
[dx, dy]: [[f32; 2]; 2],
grid: [f32; 2],
footprint: [f32; 2],
columns: std::ops::Range<u32>,
) -> Self {
let turned_columns = columns
.map(|x| {
let u = (x as f32 + 0.5) / output[0];
let pixel_offset = (u - visual.position[0]) * output[0];
TurnedColumn {
along_x: cosine * pixel_offset,
along_y: -sine * pixel_offset,
}
})
.collect();
let (nx, ny) = (grid[0] as u32, grid[1] as u32);
let sample_steps = (0..ny)
.flat_map(|row| (0..nx).map(move |column| (column, row)))
.map(|(column, row)| {
let offset = [
(column as f32 + 0.5) / grid[0] - 0.5,
(row as f32 + 0.5) / grid[1] - 0.5,
];
SampleStep {
across_columns: [dx[0] * offset[0], dx[1] * offset[0]],
across_rows: [dy[0] * offset[1], dy[1] * offset[1]],
}
})
.collect();
Self {
position_y: visual.position[1],
anchor: visual.anchor,
scale: visual.scale,
cosine,
sine,
output,
gate_footprint: [dx[0].abs() + dy[0].abs(), dx[1].abs() + dy[1].abs()],
footprint,
turned_columns,
sample_steps,
samples: grid[0] * grid[1],
}
}
#[inline]
#[expect(clippy::cast_precision_loss, reason = "a pixel row")]
fn sample_row(
&self,
image: &Texels<'_>,
first_column: u32,
y: u32,
mut put: impl FnMut(u32, [f32; 4]),
) {
let v = (y as f32 + 0.5) / self.output[1];
let pixel_offset = (v - self.position_y) * self.output[1];
let (across_x, across_y) = (self.sine * pixel_offset, self.cosine * pixel_offset);
let one_sample = self.sample_steps.len() == 1;
for (x, turned) in (first_column..).zip(&self.turned_columns) {
let rotated = [turned.along_x + across_x, turned.along_y + across_y];
let source = [
rotated[0] / self.output[0] / self.scale[0] + self.anchor[0],
rotated[1] / self.output[1] / self.scale[1] + self.anchor[1],
];
let gate = coverage(source[0], self.gate_footprint[0])
* coverage(source[1], self.gate_footprint[1]);
if gate <= 0.0 {
continue;
}
let mut color = [0.0_f32; 4];
for step in &self.sample_steps {
let point = [
source[0] + step.across_columns[0] + step.across_rows[0],
source[1] + step.across_columns[1] + step.across_rows[1],
];
let weight =
coverage(point[0], self.footprint[0]) * coverage(point[1], self.footprint[1]);
if weight <= 0.0 {
continue;
}
let sample = image.sample(point[0], point[1]);
for channel in 0..4 {
color[channel] += sample[channel] * weight;
}
}
put(
x,
if one_sample {
color
} else {
color.map(|value| value / self.samples)
},
);
}
}
}
#[cfg(test)]
mod tests {
use super::{CompositeSettings, LayerInput, PreparedLayer, RowCache, coverage, filter_grid};
use crate::cpu::image::{CpuImage, PixelBox, Texels};
use crate::cpu::kernels::builtin_interval_coverage;
use crate::{BlendMode, BlendSpace, LayerTransform, RenderSize};
#[expect(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "pixel coordinates and a filter grid of at most 8 by 8"
)]
fn shader_loop_sample(
image: &Texels<'_>,
visual: LayerTransform,
output: [f32; 2],
dimensions: [f32; 2],
budget: u32,
(x, y): (u32, u32),
) -> Option<[f32; 4]> {
let angle = visual.rotation_degrees.to_radians();
let (sine, cosine) = (libm::sinf(angle), libm::cosf(angle));
let scale = visual.scale;
let dx = [cosine / output[0] / scale[0], -sine / output[1] / scale[1]];
let dy = [sine / output[0] / scale[0], cosine / output[1] / scale[1]];
let grid = filter_grid(dx, dy, dimensions, budget);
let footprint = [
dx[0].abs() / grid[0] + dy[0].abs() / grid[1],
dx[1].abs() / grid[0] + dy[1].abs() / grid[1],
];
let uv = [(x as f32 + 0.5) / output[0], (y as f32 + 0.5) / output[1]];
let pixel_offset = [
(uv[0] - visual.position[0]) * output[0],
(uv[1] - visual.position[1]) * output[1],
];
let rotated = [
cosine * pixel_offset[0] + sine * pixel_offset[1],
-sine * pixel_offset[0] + cosine * pixel_offset[1],
];
let source = [
rotated[0] / output[0] / scale[0] + visual.anchor[0],
rotated[1] / output[1] / scale[1] + visual.anchor[1],
];
let gate = coverage(source[0], dx[0].abs() + dy[0].abs())
* coverage(source[1], dx[1].abs() + dy[1].abs());
if gate <= 0.0 {
return None;
}
let (nx, ny) = (grid[0] as u32, grid[1] as u32);
let mut color = [0.0_f32; 4];
for row in 0..ny {
for column in 0..nx {
let offset = [
(column as f32 + 0.5) / grid[0] - 0.5,
(row as f32 + 0.5) / grid[1] - 0.5,
];
let point = [
source[0] + dx[0] * offset[0] + dy[0] * offset[1],
source[1] + dx[1] * offset[0] + dy[1] * offset[1],
];
let weight = coverage(point[0], footprint[0]) * coverage(point[1], footprint[1]);
if weight <= 0.0 {
continue;
}
let sample = image.sample(point[0], point[1]);
for channel in 0..4 {
color[channel] += sample[channel] * weight;
}
}
}
let samples = grid[0] * grid[1];
Some(color.map(|value| value / samples))
}
#[test]
#[expect(clippy::cast_precision_loss, reason = "small picture sizes")]
fn a_rotated_layers_rows_hold_the_shaders_per_pixel_loop_bit_for_bit() {
let size = RenderSize::new(77, 51).expect("size");
let picture = RenderSize::new(40, 28).expect("size");
let pixels = (0..picture.width * picture.height)
.flat_map(|index| {
let (x, y) = (index % picture.width, index / picture.width);
let alpha = u8::try_from(55 + (x * 5) % 200).expect("u8");
let level = u8::try_from((x * 7 + y * 13) % 256).expect("u8");
[level, 255 - level, u8::try_from(y * 9).expect("u8"), 255]
.map(|value| {
u8::try_from(u16::from(value) * u16::from(alpha) / 255).expect("u8")
})
.into_iter()
.take(3)
.chain([alpha])
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
let image = CpuImage::from_premultiplied_rgba8(picture, &pixels).expect("picture");
let texels = image.texels();
let output = [size.width as f32, size.height as f32];
let dimensions = [picture.width as f32, picture.height as f32];
let turned = |position, scale, rotation_degrees| LayerTransform {
position,
anchor: [0.4, 0.55],
scale,
rotation_degrees,
opacity: 1.0,
};
let visuals = [
turned([0.5, 0.5], [1.0, 1.0], 17.0),
turned([0.3, 0.6], [0.31, 0.27], -40.0),
turned([0.7, 0.2], [0.07, 0.11], 123.0),
turned([0.02, 0.95], [-0.6, 0.4], 200.0),
turned([0.5, 0.5], [2.3, 1.7], 5.0),
turned([0.5, 0.5], [0.5, 0.5], 90.0),
turned([0.45, 0.5], [0.12, 0.9], 0.25),
];
for visual in visuals {
for budget in [1, 6, 16, 64] {
let settings = CompositeSettings {
size,
background: None,
blend_space: BlendSpace::LinearLight,
max_filter_samples: budget,
};
let layer = LayerInput {
image: &image,
visual,
blend_mode: BlendMode::Normal,
};
let prepared = PreparedLayer::new(&layer, PixelBox::whole(size), settings);
let mut sampled = 0;
for y in 0..size.height {
let mut row = vec![None; size.width as usize];
prepared.sample_row(y, &mut RowCache::default(), None, |x, color| {
row[x as usize] = Some(color.map(f32::to_bits));
});
for x in 0..size.width {
let expected =
shader_loop_sample(&texels, visual, output, dimensions, budget, (x, y))
.map(|color| color.map(f32::to_bits));
assert_eq!(
row[x as usize], expected,
"{visual:?} x{budget} at {x}, {y}"
);
sampled += usize::from(expected.is_some());
}
}
assert!(sampled > 0, "{visual:?} reaches nothing");
}
}
}
fn clipped_interval(position: f32, footprint: f32) -> f32 {
let width = footprint.max(0.000_000_1);
let lower = (position - width * 0.5).max(0.0);
let upper = (position + width * 0.5).min(1.0);
((upper - lower) / width).clamp(0.0, 1.0)
}
#[test]
fn coverage_is_one_inside_and_the_clipped_interval_at_power_of_two_sizes() {
for side in [1_u16, 2, 4, 64, 256, 1024, 4096] {
for scale in [0.125_f32, 0.25, 0.5, 1.0, 2.0, 8.0] {
let footprint = 1.0 / f32::from(side) / scale;
for step in 0..=side * 8 + 128 {
let position = (f32::from(step) - 64.0) / (8.0 * f32::from(side));
let expected = clipped_interval(position, footprint);
for actual in [
coverage(position, footprint),
builtin_interval_coverage(position, footprint),
] {
assert_eq!(
actual.to_bits(),
expected.to_bits(),
"side {side}, scale {scale}, position {position}"
);
}
}
}
}
for side in [5_u16, 90, 160, 1080, 1920] {
let footprint = 1.0 / f32::from(side);
for pixel in 1..side - 1 {
let position = (f32::from(pixel) + 0.5) / f32::from(side);
assert_eq!(coverage(position, footprint), 1.0, "{pixel} of {side}");
assert_eq!(builtin_interval_coverage(position, footprint), 1.0);
}
}
}
}