Skip to main content

serge_native_cpu/
lib.rs

1//! `serge-native-cpu` — draws a [`ScenePrimitive`] list into a pixel buffer
2//! with `vello_cpu` (pinned, `docs/02-architecture.md` §3). It is the
3//! required fallback when no GPU device can be created, and what headless
4//! tests and CI snapshot (`docs/03-adapters-and-pipeline.md` §1.2).
5
6mod target;
7use serge_core::{Point, Rect, ScenePrimitive};
8use serge_native_text::Font;
9use serge_style::Color;
10use vello_cpu::kurbo::{self, Affine, BezPath, Shape, Stroke};
11
12use vello_cpu::peniko::Fill;
13use vello_cpu::peniko::color::{AlphaColor, Srgb};
14use vello_cpu::{Glyph, Pixmap, RenderContext, Resources};
15
16// Vello writes premultiplied RGBA directly into the allocation returned to the caller.
17fn raster_rgba(ctx: &mut RenderContext, resources: &mut Resources, background: Color) -> Vec<u8> {
18    let (width, height) = (ctx.width(), ctx.height());
19    let pixels = usize::from(width) * usize::from(height);
20    let mut rgba = vec![0; pixels.checked_mul(4).expect("frame exceeds address space")];
21    let view = vello_cpu::PixmapMut::new(width, height, &mut rgba).expect("exact frame length");
22    ctx.flush();
23    ctx.render_with(
24        view,
25        resources,
26        vello_cpu::RasterizerSettings {
27            target_init: vello_cpu::TargetInit::Clear(color(background)),
28            ..Default::default()
29        },
30    );
31    rgba
32}
33
34/// A rendered frame: premultiplied RGBA8, row-major.
35#[derive(Clone, Debug, PartialEq)]
36pub struct Frame {
37    /// Width in physical pixels.
38    pub width: u16,
39    /// Height in physical pixels.
40    pub height: u16,
41    /// Premultiplied RGBA, 4 bytes per pixel.
42    pub rgba: Vec<u8>,
43}
44
45impl Frame {
46    /// The pixel at `(x, y)` as premultiplied RGBA.
47    pub fn pixel(&self, x: u16, y: u16) -> [u8; 4] {
48        let i = (usize::from(y) * usize::from(self.width) + usize::from(x)) * 4;
49        [
50            self.rgba[i],
51            self.rgba[i + 1],
52            self.rgba[i + 2],
53            self.rgba[i + 3],
54        ]
55    }
56
57    /// `0x00RRGGBB` words for a window surface (alpha dropped; frames are
58    /// opaque because the background is drawn first).
59    pub fn to_xrgb(&self, out: &mut Vec<u32>) {
60        out.clear();
61        out.extend(
62            self.rgba
63                .as_chunks::<4>()
64                .0
65                .iter()
66                .map(|p| (u32::from(p[0]) << 16) | (u32::from(p[1]) << 8) | u32::from(p[2])),
67        );
68    }
69}
70
71/// A reusable CPU renderer.
72pub struct CpuRenderer {
73    ctx: RenderContext,
74    resources: Resources,
75}
76
77impl std::fmt::Debug for CpuRenderer {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("CpuRenderer").finish_non_exhaustive()
80    }
81}
82
83impl Default for CpuRenderer {
84    fn default() -> Self {
85        Self::new()
86    }
87}
88
89fn color(c: Color) -> AlphaColor<Srgb> {
90    AlphaColor::from_rgba8(c.r, c.g, c.b, c.a)
91}
92
93fn rect(r: Rect) -> kurbo::Rect {
94    kurbo::Rect::new(
95        f64::from(r.x),
96        f64::from(r.y),
97        f64::from(r.right()),
98        f64::from(r.bottom()),
99    )
100}
101
102fn pt(p: Point) -> kurbo::Point {
103    kurbo::Point::new(f64::from(p.x), f64::from(p.y))
104}
105
106/// The path through `points`, closed for a polygon.
107fn polyline(points: &[Point], close: bool) -> BezPath {
108    let mut path = BezPath::new();
109    for (i, p) in points.iter().enumerate() {
110        if i == 0 {
111            path.move_to(pt(*p));
112        } else {
113            path.line_to(pt(*p));
114        }
115    }
116    if close {
117        path.close_path();
118    }
119    path
120}
121
122/// A border's ring: the outer rounded rectangle and, inside it, the inner
123/// one (filled even-odd).
124fn border_path(r: Rect, width: f32, radius: f32) -> BezPath {
125    let mut path = kurbo::RoundedRect::from_rect(rect(r), f64::from(radius.max(0.0))).to_path(0.1);
126    if r.width > 2.0 * width && r.height > 2.0 * width {
127        let inner = kurbo::RoundedRect::from_rect(
128            rect(r.inset(width)),
129            f64::from((radius - width).max(0.0)),
130        );
131        path.extend(inner.path_elements(0.1));
132    }
133    path
134}
135
136/// How a `Line` is stroked.
137fn line_stroke(width: f32) -> Stroke {
138    Stroke::new(f64::from(width))
139        .with_caps(kurbo::Cap::Round)
140        .with_join(kurbo::Join::Round)
141}
142
143impl CpuRenderer {
144    /// A renderer.
145    pub fn new() -> CpuRenderer {
146        CpuRenderer {
147            ctx: RenderContext::new(1, 1),
148            resources: Resources::new(),
149        }
150    }
151
152    /// Draws `scene` (logical pixels) at `scale` physical pixels per logical
153    /// pixel into a `width` × `height` frame.
154    pub fn render(
155        &mut self,
156        scene: &[ScenePrimitive],
157        width: u16,
158        height: u16,
159        scale: f32,
160    ) -> Frame {
161        let (width, height) = (width.max(1), height.max(1));
162        let (background, scene) = target::background(scene, width, height, scale);
163        if scene.is_empty() {
164            self.ctx.reset();
165            return target::solid(width, height, background);
166        }
167        if self.ctx.width() != width || self.ctx.height() != height {
168            self.ctx = RenderContext::new(width, height);
169        } else {
170            self.ctx.reset();
171        }
172        let ctx = &mut self.ctx;
173        let base = Affine::scale(f64::from(scale));
174        ctx.set_transform(base);
175        for p in scene {
176            match p {
177                ScenePrimitive::ExternalTexture { key, rect: dest } => {
178                    let Some(slot) = serge_core::viewport::Slot::resolve(*key) else {
179                        continue;
180                    };
181                    let size = slot.extent();
182                    if size.byte_len().is_none() {
183                        continue;
184                    }
185                    if let (Ok(w), Ok(h), Some(bytes)) = (
186                        u16::try_from(size.width),
187                        u16::try_from(size.height),
188                        slot.rgba(),
189                    ) {
190                        let mut image = Pixmap::new(w, h);
191                        image.data_as_u8_slice_mut().copy_from_slice(&bytes);
192                        ctx.set_paint(vello_cpu::Image {
193                            image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(image)),
194                            sampler: Default::default(),
195                        });
196                        ctx.set_paint_transform(
197                            Affine::translate((f64::from(dest.x), f64::from(dest.y)))
198                                * Affine::scale_non_uniform(
199                                    f64::from(dest.width) / f64::from(w),
200                                    f64::from(dest.height) / f64::from(h),
201                                ),
202                        );
203                        ctx.fill_rect(&rect(*dest));
204                        ctx.reset_paint_transform();
205                        slot.presented(true);
206                    } else {
207                        ctx.set_paint(color(slot.fallback()));
208                        ctx.fill_rect(&rect(*dest));
209                        slot.presented(false);
210                    }
211                }
212                ScenePrimitive::Quad {
213                    rect: r,
214                    color: c,
215                    radius,
216                } => {
217                    ctx.set_paint(color(*c));
218                    if *radius > 0.0 {
219                        let rr = kurbo::RoundedRect::from_rect(rect(*r), f64::from(*radius));
220                        ctx.fill_path(&rr.to_path(0.1));
221                    } else {
222                        ctx.fill_rect(&rect(*r));
223                    }
224                }
225                ScenePrimitive::Border {
226                    rect: r,
227                    color: c,
228                    width: w,
229                    radius,
230                } => {
231                    // Inside the rectangle, like a CSS border: the outer
232                    // edge has `radius`, the inner one `radius - width`.
233                    if *w > 0.0 {
234                        ctx.set_paint(color(*c));
235                        ctx.set_fill_rule(Fill::EvenOdd);
236                        ctx.fill_path(&border_path(*r, *w, *radius));
237                        ctx.set_fill_rule(Fill::NonZero);
238                    }
239                }
240                ScenePrimitive::Line {
241                    points,
242                    color: c,
243                    width: w,
244                } => {
245                    ctx.set_paint(color(*c));
246                    ctx.set_stroke(line_stroke(*w));
247                    ctx.stroke_path(&polyline(points, false));
248                }
249                ScenePrimitive::Polygon { points, color: c } => {
250                    ctx.set_paint(color(*c));
251                    ctx.fill_path(&polyline(points, true));
252                }
253                ScenePrimitive::Glyphs {
254                    origin,
255                    font,
256                    size,
257                    color: c,
258                    glyphs,
259                } => {
260                    let Some(font) = font.0.downcast_ref::<Font>() else {
261                        continue;
262                    };
263                    ctx.set_paint(color(*c));
264                    ctx.set_transform(
265                        base * Affine::translate((f64::from(origin.x), f64::from(origin.y))),
266                    );
267                    let run = glyphs.iter().map(|g| Glyph {
268                        id: g.id,
269                        x: g.x,
270                        y: g.y,
271                    });
272                    let _ = ctx
273                        .glyph_run(&mut self.resources, font)
274                        .font_size(*size)
275                        .hint(true)
276                        .fill_glyphs(run);
277                    ctx.set_transform(base);
278                }
279                ScenePrimitive::PushClip(r) => ctx.push_clip_layer(&rect(*r).to_path(0.1)),
280                ScenePrimitive::PopClip => ctx.pop_layer(),
281            }
282        }
283        let rgba = raster_rgba(ctx, &mut self.resources, background);
284        Frame {
285            width,
286            height,
287            rgba,
288        }
289    }
290}
291
292/// A coverage mask in physical pixels: `rgba` is `width` × `height`
293/// premultiplied pixels, row-major, with its top-left corner at (`x`, `y`)
294/// in the frame. Drawn in white, so outline coverage is `(a, a, a, a)`;
295/// color glyphs (emoji) keep their colors.
296#[derive(Clone, Debug, PartialEq)]
297pub struct Mask {
298    /// Left edge in the frame.
299    pub x: i32,
300    /// Top edge in the frame.
301    pub y: i32,
302    /// Width in pixels.
303    pub width: u16,
304    /// Height in pixels.
305    pub height: u16,
306    /// Premultiplied RGBA, 4 bytes per pixel.
307    pub rgba: Vec<u8>,
308}
309
310impl Mask {
311    /// Whether any pixel is not gray-scale coverage (a color glyph).
312    pub fn has_color(&self) -> bool {
313        self.rgba
314            .as_chunks::<4>()
315            .0
316            .iter()
317            .any(|p| p[0] != p[3] || p[1] != p[3] || p[2] != p[3])
318    }
319}
320
321/// The largest mask side; bigger paths are clipped to it.
322const MAX_MASK: f64 = 8192.0;
323
324/// Rasterizes single paths and glyphs into coverage masks with the same
325/// rasterizer, strokes and transforms as [`CpuRenderer`], shifted by whole
326/// pixels. A renderer that composites the masks at their positions (the GPU
327/// path's atlases) therefore draws what the CPU path draws.
328pub struct MaskRasterizer {
329    ctx: RenderContext,
330    resources: Resources,
331}
332
333impl std::fmt::Debug for MaskRasterizer {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        f.debug_struct("MaskRasterizer").finish_non_exhaustive()
336    }
337}
338
339impl Default for MaskRasterizer {
340    fn default() -> Self {
341        Self::new()
342    }
343}
344
345impl MaskRasterizer {
346    /// A rasterizer.
347    pub fn new() -> MaskRasterizer {
348        MaskRasterizer {
349            ctx: RenderContext::new(1, 1),
350            resources: Resources::new(),
351        }
352    }
353
354    fn draw(
355        &mut self,
356        x: i32,
357        y: i32,
358        width: u16,
359        height: u16,
360        f: impl FnOnce(&mut RenderContext, &mut Resources),
361    ) -> Mask {
362        if self.ctx.width() != width || self.ctx.height() != height {
363            self.ctx = RenderContext::new(width, height);
364        } else {
365            self.ctx.reset();
366        }
367        self.ctx
368            .set_paint(AlphaColor::<Srgb>::from_rgba8(255, 255, 255, 255));
369        f(&mut self.ctx, &mut self.resources);
370        let rgba = raster_rgba(&mut self.ctx, &mut self.resources, Color::TRANSPARENT);
371        Mask {
372            x,
373            y,
374            width,
375            height,
376            rgba,
377        }
378    }
379
380    /// The coverage of a `Line` or `Polygon` drawn at `scale`; `None` for
381    /// other primitives and empty paths.
382    pub fn path(&mut self, p: &ScenePrimitive, scale: f32) -> Option<Mask> {
383        let (path, stroke) = match p {
384            ScenePrimitive::Line { points, width, .. } => {
385                (polyline(points, false), Some(line_stroke(*width)))
386            }
387            ScenePrimitive::Polygon { points, .. } => (polyline(points, true), None),
388            _ => return None,
389        };
390        let device = Affine::scale(f64::from(scale));
391        let mut b = (device * path.clone()).bounding_box();
392        let grow = stroke
393            .as_ref()
394            .map_or(0.0, |s| s.width * f64::from(scale) / 2.0)
395            + 1.0;
396        b = b.inflate(grow, grow);
397        if !(b.x0.is_finite() && b.y0.is_finite() && b.x1.is_finite() && b.y1.is_finite()) {
398            return None;
399        }
400        let (x0, y0) = (b.x0.floor(), b.y0.floor());
401        let w = (b.x1.ceil() - x0).clamp(0.0, MAX_MASK);
402        let h = (b.y1.ceil() - y0).clamp(0.0, MAX_MASK);
403        if w < 1.0 || h < 1.0 {
404            return None;
405        }
406        Some(
407            self.draw(x0 as i32, y0 as i32, w as u16, h as u16, |ctx, _| {
408                ctx.set_transform(Affine::translate((-x0, -y0)) * device);
409                match stroke {
410                    Some(s) => {
411                        ctx.set_stroke(s);
412                        ctx.stroke_path(&path);
413                    }
414                    None => ctx.fill_path(&path),
415                }
416            }),
417        )
418    }
419
420    /// One glyph of `font` at `size` logical pixels whose origin lands at
421    /// device position (`x`, `y`) — where [`CpuRenderer`] would draw it
422    /// (`scale × (run origin + glyph offset)`). `None` for an empty glyph.
423    pub fn glyph(
424        &mut self,
425        font: &Font,
426        size: f32,
427        id: u32,
428        scale: f32,
429        x: f64,
430        y: f64,
431    ) -> Option<Mask> {
432        let em = f64::from(size * scale);
433        // Room around the origin; the mask is cropped to the ink below.
434        let left = (em * 1.5).ceil() + 2.0;
435        let top = (em * 2.5).ceil() + 2.0;
436        let w = (left + em * 4.0 + 2.0).ceil().min(MAX_MASK);
437        let h = (top + em * 1.5 + 2.0).ceil().min(MAX_MASK);
438        let (fx, fy) = (x.floor(), y.floor());
439        let (dx, dy) = (x - fx, y - fy);
440        let full = self.draw(
441            fx as i32 - left as i32,
442            fy as i32 - top as i32,
443            w as u16,
444            h as u16,
445            |ctx, resources| {
446                // The CPU path's transform shape (scale, then translate) and
447                // the same fractional position: hinting rounds the device y
448                // the same way, shifted by whole pixels.
449                ctx.set_transform(
450                    Affine::translate((left + dx, top + dy)) * Affine::scale(f64::from(scale)),
451                );
452                let _ = ctx
453                    .glyph_run(resources, font)
454                    .font_size(size)
455                    .hint(true)
456                    .fill_glyphs(std::iter::once(Glyph { id, x: 0.0, y: 0.0 }));
457            },
458        );
459        crop(full)
460    }
461}
462
463/// `m` cropped to its non-empty pixels.
464fn crop(m: Mask) -> Option<Mask> {
465    let (w, h) = (usize::from(m.width), usize::from(m.height));
466    let ink = |x: usize, y: usize| m.rgba[(y * w + x) * 4 + 3] != 0;
467    let rows: Vec<usize> = (0..h).filter(|&y| (0..w).any(|x| ink(x, y))).collect();
468    let (&top, &bottom) = (rows.first()?, rows.last()?);
469    let cols: Vec<usize> = (0..w)
470        .filter(|&x| (top..=bottom).any(|y| ink(x, y)))
471        .collect();
472    let (&left, &right) = (cols.first()?, cols.last()?);
473    let (cw, ch) = (right - left + 1, bottom - top + 1);
474    let mut rgba = Vec::with_capacity(cw * ch * 4);
475    for y in top..=bottom {
476        rgba.extend_from_slice(&m.rgba[(y * w + left) * 4..(y * w + right + 1) * 4]);
477    }
478    Some(Mask {
479        x: m.x + left as i32,
480        y: m.y + top as i32,
481        width: cw as u16,
482        height: ch as u16,
483        rgba,
484    })
485}
486
487#[cfg(test)]
488mod frame_tests {
489    use super::*;
490
491    fn context() -> (RenderContext, Resources) {
492        let mut ctx = RenderContext::new(511, 251);
493        ctx.set_paint(AlphaColor::<Srgb>::from_rgba8(55, 123, 199, 101));
494        ctx.fill_rect(&kurbo::Rect::new(8.5, 10.0, 309.25, 180.5));
495        (ctx, Resources::new())
496    }
497
498    fn reference(ctx: &mut RenderContext, resources: &mut Resources) -> Vec<u8> {
499        ctx.flush();
500        let mut pixmap = Pixmap::new(ctx.width(), ctx.height());
501        ctx.render(&mut pixmap, resources);
502        pixmap
503            .data()
504            .iter()
505            .flat_map(|p| [p.r, p.g, p.b, p.a])
506            .collect()
507    }
508
509    #[test]
510    fn caller_owned_rgba_matches_vello_at_transparent_edges() {
511        let (mut ctx, mut resources) = context();
512        let expected = reference(&mut ctx, &mut resources);
513        let frame = raster_rgba(&mut ctx, &mut resources, Color::TRANSPARENT);
514        assert!(
515            frame
516                .as_chunks::<4>()
517                .0
518                .iter()
519                .any(|p| (1..101).contains(&p[3]))
520        );
521        assert_eq!(frame, expected);
522    }
523
524    #[test]
525    #[ignore = "timing comparison, run with --release --ignored --nocapture"]
526    fn benchmark_frame_buffer() {
527        let (mut ctx, mut resources) = context();
528        let mut samples = [Vec::new(), Vec::new()];
529        for trial in 0..21 {
530            for index in [trial % 2, 1 - trial % 2] {
531                let start = std::time::Instant::now();
532                for _ in 0..50 {
533                    let frame = if index == 0 {
534                        raster_rgba(&mut ctx, &mut resources, Color::TRANSPARENT)
535                    } else {
536                        reference(&mut ctx, &mut resources)
537                    };
538                    std::hint::black_box(frame);
539                }
540                samples[index].push(start.elapsed().as_nanos() / 50);
541            }
542        }
543        for (name, mut times) in ["borrowed RGBA", "owned Pixmap"].into_iter().zip(samples) {
544            times.sort_unstable();
545            println!(
546                "{name}: {} ns/frame ({}–{})",
547                times[10], times[0], times[20]
548            );
549        }
550    }
551}