Skip to main content

devpage_design/cpu/
mod.rs

1//! The `vello_cpu` backend — an adapter of [`crate::display::Target`]: any
2//! area of a display list painted into a pixmap, and a tile's straight-alpha
3//! pixels, for the server's tiles, the PNG and a browser without WebGPU.
4
5use std::collections::HashMap;
6
7use kurbo::{Affine, BezPath, Rect as KRect, Shape};
8use peniko::{BlendMode, Compose, ImageBrush, Mix};
9use vello_cpu::{Pixmap, RenderContext, Resources};
10
11use crate::display::List;
12use crate::display::{Draw, Paint};
13#[cfg(test)]
14use crate::scene::{Scene, Theme};
15use crate::tiles::{TILE, tile_rect};
16
17/// The `vello_cpu` backend of [`crate::display::paint`].
18pub struct Cpu<'a> {
19    /// The context it draws into.
20    pub ctx: &'a mut RenderContext,
21    /// Each image painted so far, by its blob's id, so an image drawn twice is
22    /// converted once.
23    pub sources: HashMap<u64, vello_cpu::ImageSource>,
24    /// What `vello_cpu` keeps while it draws glyphs and renders: its caches.
25    pub resources: Resources,
26}
27
28impl crate::display::Target for Cpu<'_> {
29    fn draw(&mut self, draw: &Draw, t: Affine) {
30        let ctx = &mut *self.ctx;
31        ctx.set_transform(t);
32        match draw {
33            Draw::Fill(path, paint) => {
34                match paint {
35                    Paint::Solid(c) => ctx.set_paint(*c),
36                    Paint::Gradient(g) => ctx.set_paint(g.clone()),
37                    Paint::Image(data, place) => {
38                        let image = self
39                            .sources
40                            .entry(data.data.id())
41                            .or_insert_with(|| vello_cpu::ImageSource::from_peniko_image_data(data))
42                            .clone();
43                        ctx.set_paint(ImageBrush {
44                            image,
45                            sampler: Default::default(),
46                        });
47                        ctx.set_paint_transform(*place);
48                    }
49                }
50                ctx.fill_path(path);
51                ctx.reset_paint_transform();
52            }
53            Draw::Stroke(path, width, c) => {
54                ctx.set_paint(*c);
55                ctx.set_stroke(kurbo::Stroke::new(*width as f64));
56                ctx.stroke_path(path);
57            }
58            Draw::Glyphs(font, size, c, coords, glyphs) => {
59                ctx.set_paint(*c);
60                let _ = ctx
61                    .glyph_run(&mut self.resources, font)
62                    .font_size(*size)
63                    .normalized_coords(coords)
64                    .hint(true)
65                    .fill_glyphs(glyphs.iter().map(|g| vello_cpu::Glyph {
66                        id: g.id,
67                        x: g.x,
68                        y: g.y,
69                    }));
70            }
71        }
72    }
73    fn push_clip(&mut self, path: &BezPath, t: Affine) {
74        self.ctx.set_transform(t);
75        self.ctx.push_clip_layer(path);
76    }
77    fn push_layer(
78        &mut self,
79        blend: crate::display::Blend,
80        bounds: Option<&BezPath>,
81        t: Affine,
82        area: KRect,
83    ) {
84        let whole;
85        let bounds = match bounds {
86            Some(b) => {
87                self.ctx.set_transform(t);
88                b
89            }
90            None => {
91                self.ctx.set_transform(Affine::IDENTITY);
92                whole = area.to_path(0.1);
93                &whole
94            }
95        };
96        match blend {
97            crate::display::Blend::Opacity(o) => {
98                self.ctx.push_layer(Some(bounds), None, Some(o), None, None)
99            }
100            crate::display::Blend::Add => self.ctx.push_layer(
101                Some(bounds),
102                Some(BlendMode::new(Mix::Normal, Compose::Plus)),
103                None,
104                None,
105                None,
106            ),
107        }
108    }
109    fn pop(&mut self) {
110        self.ctx.pop_layer();
111    }
112}
113
114/// Paints `area` of `list` — in the design's coordinates, whole pixels at
115/// `scale` — with `vello_cpu`: one tile, band or whole drawing.
116pub fn paint_area(list: &crate::display::List, area: KRect, scale: f64) -> Pixmap {
117    // Whole pixels, the last partly covered one included — but not one a
118    // rounding error leaves past a tile's exact edge.
119    let side = |v: f64| ((v * scale - 1e-6).ceil().clamp(1.0, u16::MAX as f64)) as u16;
120    let (w, h) = (side(area.width()), side(area.height()));
121    let mut ctx = RenderContext::new(w, h);
122    let mut cpu = Cpu {
123        ctx: &mut ctx,
124        sources: HashMap::new(),
125        resources: Resources::default(),
126    };
127    crate::display::paint(list, area, scale, &mut cpu);
128    let mut resources = std::mem::take(&mut cpu.resources);
129    ctx.flush();
130    let mut pixmap = Pixmap::new(w, h);
131    ctx.render(&mut pixmap, &mut resources);
132    pixmap
133}
134
135#[cfg(test)]
136impl crate::render::Renderer {
137    /// The scene's whole drawing painted with `vello_cpu` at `scale`.
138    pub fn paint(&mut self, scene: &Scene, theme: Theme, scale: f32) -> Pixmap {
139        let d = self.drawing(scene, theme, None).expect("drawable");
140        let a = d.area();
141        let area = KRect::new(
142            a.x as f64,
143            a.y as f64,
144            (a.x + a.width) as f64,
145            (a.y + a.height) as f64,
146        );
147        paint_area(&d.list, area, scale as f64)
148    }
149}
150
151/// A tile's pixels, straight RGBA, `TILE` a side.
152pub fn tile(list: &List, scale: f64, col: u32, row: u32) -> Vec<u8> {
153    let pixmap = paint_area(list, tile_rect(list, scale, col, row), scale);
154    let mut rgba = pixmap.data_as_u8_slice().to_vec();
155    unpremultiply(&mut rgba);
156    rgba
157}
158
159/// A strip of the drawing at 1×, straight RGBA: `TILE` pixels wide at tile
160/// column `col`, `rows` tall from pixel row `y` — a piece of a PNG band too
161/// wide for whole tiles.
162pub fn strip(list: &List, col: u32, y: u32, rows: u32) -> Vec<u8> {
163    let (x0, y0) = (list.area.x as f64, list.area.y as f64);
164    let area = KRect::new(
165        x0 + (col * TILE) as f64,
166        y0 + y as f64,
167        x0 + ((col + 1) * TILE) as f64,
168        y0 + (y + rows) as f64,
169    );
170    let mut rgba = paint_area(list, area, 1.0).data_as_u8_slice().to_vec();
171    unpremultiply(&mut rgba);
172    rgba
173}
174
175/// Straight alpha from premultiplied, rounding as the PNG encoder does.
176pub fn unpremultiply(rgba: &mut [u8]) {
177    for px in rgba.as_chunks_mut::<4>().0 {
178        let a = px[3] as u32;
179        if a != 0 && a != 255 {
180            for c in &mut px[..3] {
181                *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
182            }
183        }
184    }
185}