alpha2-render 0.9.0

Render graph and effect registry for alpha2.
Documentation
use std::sync::Arc;

use super::blend::{premultiplied_in_blend_space, summed};
use super::composite::{
    CompositeSettings, DecodedRows, LayerInput, PreparedLayer, RowCache, prepared_layers,
};
use super::frames::FramePool;
use super::half;
use super::image::{CpuImage, PixelBox};
use super::workers::Workers;
use crate::{BlendMode, BlendSpace, LayerTransform, RenderError};

const TRANSPARENT: [u16; 4] = [0; 4];

#[derive(Copy, Clone)]
enum Total {
    Nothing,
    OnePlacement { source: [f32; 4] },
    InBlendSpace { premultiplied: [f32; 4] },
}

impl Total {
    #[inline]
    fn add(&mut self, source: [f32; 4], linear_light: bool) {
        if source[3] <= 0.0 {
            return;
        }
        let mut premultiplied = match *self {
            Self::Nothing => {
                *self = Self::OnePlacement { source };
                return;
            }
            Self::OnePlacement { source: first } => {
                premultiplied_in_blend_space(first, linear_light)
            }
            Self::InBlendSpace { premultiplied } => premultiplied,
        };
        let added = premultiplied_in_blend_space(source, linear_light);
        for channel in 0..4 {
            premultiplied[channel] += added[channel];
        }
        *self = Self::InBlendSpace { premultiplied };
    }

    #[inline]
    fn stored(self, placement: &PreparedLayer<'_>, linear_light: bool) -> [u16; 4] {
        match self {
            Self::Nothing => TRANSPARENT,
            Self::OnePlacement { source } => {
                placement.composite_source(TRANSPARENT, source, linear_light)
            }
            Self::InBlendSpace { premultiplied } => {
                half::store4_nearest(summed(premultiplied, linear_light))
            }
        }
    }
}

struct BandState {
    caches: Vec<RowCache>,
    decoded: Option<DecodedRows>,
    totals: Vec<Total>,
}

pub(crate) fn sum(
    workers: &Workers,
    frames: &Arc<FramePool>,
    image: &CpuImage,
    placements: &[LayerTransform],
    settings: CompositeSettings,
) -> Result<CpuImage, RenderError> {
    let layers = placements
        .iter()
        .map(|placement| LayerInput {
            image,
            visual: *placement,
            blend_mode: BlendMode::Normal,
        })
        .collect::<Vec<_>>();
    let prepared = prepared_layers(&layers, settings)?;
    let bounds = prepared.iter().fold(PixelBox::EMPTY, |union, placement| {
        union.union(placement.bounds)
    });
    let Some(any_placement) = prepared.first().filter(|_| !bounds.is_empty()) else {
        return Ok(CpuImage::transparent(settings.size));
    };
    let mut pixels = frames.take(bounds.pixels());
    let width = bounds.width as usize;
    let linear_light = settings.blend_space == BlendSpace::LinearLight;
    let new_state = || BandState {
        caches: prepared.iter().map(|_| RowCache::default()).collect(),
        decoded: DecodedRows::read_by(&prepared),
        totals: vec![Total::Nothing; width],
    };
    let row_work_pixels = width
        + prepared
            .iter()
            .map(PreparedLayer::row_work_pixels)
            .sum::<usize>();
    let draw_band = |state: &mut BandState, first_row: usize, band: &mut [[u16; 4]]| {
        let BandState {
            caches,
            decoded,
            totals,
        } = state;
        for cache in caches.iter_mut() {
            cache.reset();
        }
        if let Some(decoded) = decoded {
            decoded.reset();
        }
        for (index, line) in band.chunks_mut(width).enumerate() {
            #[expect(clippy::cast_possible_truncation, reason = "a row of a render target")]
            let y = bounds.y + (first_row + index) as u32;
            totals.fill(Total::Nothing);
            for (placement, cache) in prepared.iter().zip(caches.iter_mut()) {
                placement.sample_row(y, cache, decoded.as_mut(), |x, color| {
                    totals[(x - bounds.x) as usize].add(placement.at_opacity(color), linear_light);
                });
            }
            for (pixel, total) in line.iter_mut().zip(totals.iter()) {
                *pixel = total.stored(any_placement, linear_light);
            }
        }
    };
    workers.weighted_bands_with(&mut pixels, width, row_work_pixels, new_state, draw_band);
    Ok(CpuImage::pooled(settings.size, bounds, pixels, frames))
}