Skip to main content

vello_cpu/filter/
context.rs

1// Copyright 2026 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use alloc::sync::Arc;
5use alloc::vec::Vec;
6use vello_common::pixmap::Pixmap;
7
8#[derive(Debug, Default)]
9pub(crate) struct FilterContext {
10    /// The rendered pixmaps for each filter layer.
11    layers: Vec<Option<Arc<Pixmap>>>,
12    scratch: ScratchBuffer,
13}
14
15impl FilterContext {
16    pub(crate) fn new(num_layers: usize) -> Self {
17        Self {
18            layers: (0..num_layers).map(|_| None).collect(),
19            scratch: ScratchBuffer::new(),
20        }
21    }
22
23    pub(crate) fn scratch(&mut self) -> &mut ScratchBuffer {
24        &mut self.scratch
25    }
26
27    pub(crate) fn set_layer(&mut self, id: usize, pixmap: Pixmap) {
28        if id >= self.layers.len() {
29            self.layers.resize_with(id + 1, || None);
30        }
31        self.layers[id] = Some(Arc::new(pixmap));
32    }
33
34    pub(crate) fn filter_layer(&self, id: usize) -> Option<Arc<Pixmap>> {
35        self.layers.get(id).and_then(Option::as_ref).cloned()
36    }
37}
38
39#[derive(Debug, Default)]
40pub(crate) struct ScratchBuffer {
41    scratch_buffer: Option<Pixmap>,
42}
43
44impl ScratchBuffer {
45    pub(crate) fn new() -> Self {
46        Self::default()
47    }
48
49    pub(crate) fn get_scratch_buffer(&mut self, width: u16, height: u16) -> &mut Pixmap {
50        match &mut self.scratch_buffer {
51            None => {
52                self.scratch_buffer = Some(Pixmap::new(width, height));
53            }
54            Some(buf) if buf.width() < width || buf.height() < height => {
55                buf.resize(width, height);
56            }
57            Some(_) => {}
58        }
59
60        self.scratch_buffer.as_mut().unwrap()
61    }
62}