lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Raster publication of the frozen, outlined native scene. Geometry is
//! normalized by usvg and sampled by tiny-skia. Only coverage is sampled at
//! that point: authored opacity participates in source-over compositing before
//! the completed pixel is encoded as straight RGBA8.

use resvg::{tiny_skia as skia, usvg};
use std::fmt::Write as _;

use crate::{Error, Result};

const TILE: u32 = 256;
const OPACITY_ID: &str = "__lichtung_raster_opacity_";

type Pixel = [f64; 4];

#[derive(Clone, Copy)]
struct Opacity {
    fill: f64,
    stroke: f64,
    group: f64,
}

impl Default for Opacity {
    fn default() -> Self {
        Self {
            fill: 1.0,
            stroke: 1.0,
            group: 1.0,
        }
    }
}

impl Opacity {
    fn present(node: roxmltree::Node<'_, '_>) -> bool {
        ["fill-opacity", "stroke-opacity", "opacity"]
            .iter()
            .any(|attribute| node.has_attribute(*attribute))
    }

    fn read(node: roxmltree::Node<'_, '_>) -> Result<Self> {
        let coefficient = |attribute| -> Result<f64> {
            let Some(value) = node.attribute(attribute) else {
                return Ok(1.0);
            };
            let value = value
                .parse::<f64>()
                .map_err(|_| Error::Render("invalid opacity in the frozen native scene".into()))?;
            if !(0.0..=1.0).contains(&value) {
                return Err(Error::Render(
                    "invalid opacity in the frozen native scene".into(),
                ));
            }
            Ok(value)
        };
        let opacity = Self {
            fill: coefficient("fill-opacity")?,
            stroke: coefficient("stroke-opacity")?,
            group: coefficient("opacity")?,
        };
        // The native vocabulary has explicit path paints, and independently
        // composited groups. No inherited or CSS opacity is emitted.
        if (node.tag_name().name() == "g" && (opacity.fill < 1.0 || opacity.stroke < 1.0))
            || (node.tag_name().name() != "g" && opacity.group < 1.0)
        {
            return Err(Error::Render(
                "unsupported opacity in the frozen native scene".into(),
            ));
        }
        Ok(opacity)
    }
}

/// Geometry normalization keeps the source's paint identities. usvg's opacity
/// fields are binary32, so retain the original binary64 operands separately.
pub(super) struct RasterScene {
    tree: usvg::Tree,
    opacities: Vec<Opacity>,
    _opacity_storage: crate::operation::Scratch,
}

impl RasterScene {
    pub(super) fn parse(bytes: &[u8]) -> Result<Self> {
        let svg = std::str::from_utf8(bytes)
            .map_err(|error| Error::Render(format!("invalid frozen SVG: {error}").into()))?;
        let parse = |source: &str| {
            usvg::Tree::from_str(source, &usvg::Options::default()).map_err(|error| {
                Error::Render(format!("parse svg for png rasterization: {error}").into())
            })
        };
        if !svg.contains("opacity=") {
            return Ok(Self {
                tree: parse(svg)?,
                opacities: Vec::new(),
                _opacity_storage: crate::operation::scratch(0)?,
            });
        }
        let document = roxmltree::Document::parse(svg).map_err(|error| {
            Error::Render(format!("parse native opacity operands: {error}").into())
        })?;
        let mut count = 0_usize;
        for (index, node) in document.descendants().enumerate() {
            if index % 64 == 0 {
                crate::operation::checkpoint()?;
            }
            crate::operation::work(1)?;
            if node
                .attribute("id")
                .is_some_and(|id| id.starts_with(OPACITY_ID))
            {
                return Err(Error::Render(
                    "reserved raster paint identity in native SVG".into(),
                ));
            }
            count += usize::from(Opacity::present(node));
        }
        if count == 0 {
            return Ok(Self {
                tree: parse(svg)?,
                opacities: Vec::new(),
                _opacity_storage: crate::operation::scratch(0)?,
            });
        }
        let opacity_storage =
            crate::operation::scratch(count as u128 * std::mem::size_of::<Opacity>() as u128)?;
        let mut opacities = Vec::new();
        opacities.try_reserve_exact(count).map_err(|error| {
            Error::Render(format!("raster opacity reservation: {error}").into())
        })?;
        // Add stable identifiers only to paint-bearing nodes. This scratch
        // document has identical geometry and paints to the frozen SVG; the
        // immutable outlined bytes themselves are never modified.
        let id_bytes = OPACITY_ID.len() + count.ilog10() as usize + 1 + " id=\"\"".len();
        let capacity = count
            .checked_mul(id_bytes)
            .and_then(|extra| svg.len().checked_add(extra))
            .ok_or_else(|| Error::Render("raster SVG identity storage overflow".into()))?;
        let _normalized_storage = crate::operation::scratch(capacity as u128)?;
        let mut normalized = String::new();
        normalized.try_reserve_exact(capacity).map_err(|error| {
            Error::Render(format!("raster SVG identity reservation: {error}").into())
        })?;
        let mut cursor = 0;
        for (index, node) in document.descendants().enumerate() {
            if index % 64 == 0 {
                crate::operation::checkpoint()?;
            }
            crate::operation::work(1)?;
            if !Opacity::present(node) {
                continue;
            }
            let index = opacities.len();
            opacities.push(Opacity::read(node)?);
            if let Some(id) = node.attribute_node("id") {
                let range = id.range_value();
                normalized.push_str(&svg[cursor..range.start]);
                write!(normalized, "{OPACITY_ID}{index}").expect("write to reserved string");
                cursor = range.end;
            } else {
                let end = node.range().start + 1 + node.tag_name().name().len();
                normalized.push_str(&svg[cursor..end]);
                write!(normalized, " id=\"{OPACITY_ID}{index}\"")
                    .expect("write to reserved string");
                cursor = end;
            }
        }
        normalized.push_str(&svg[cursor..]);
        drop(document);
        let tree = parse(&normalized)?;
        Ok(Self {
            tree,
            opacities,
            _opacity_storage: opacity_storage,
        })
    }

    pub(super) fn size(&self) -> skia::Size {
        self.tree.size()
    }

    fn opacity(&self, id: &str) -> Result<Opacity> {
        let Some(index) = id.strip_prefix(OPACITY_ID) else {
            return Ok(Opacity::default());
        };
        index
            .parse::<usize>()
            .ok()
            .and_then(|index| self.opacities.get(index).copied())
            .ok_or_else(|| Error::Render("unknown raster paint identity".into()))
    }
}

fn storage<T: Clone>(len: usize, value: T) -> Result<Vec<T>> {
    let mut result = Vec::new();
    result
        .try_reserve_exact(len)
        .map_err(|error| Error::Render(format!("raster sample reservation: {error}").into()))?;
    result.resize(len, value);
    Ok(result)
}

struct Tile {
    region: skia::IntRect,
    pixels: Vec<Pixel>,
    _storage: crate::operation::Scratch,
}

impl Tile {
    fn new(region: skia::IntRect) -> Result<Self> {
        let count = region.width() as usize * region.height() as usize;
        let storage_budget =
            crate::operation::scratch(count as u128 * std::mem::size_of::<Pixel>() as u128)?;
        Ok(Self {
            region,
            pixels: storage(count, [0.0; 4])?,
            _storage: storage_budget,
        })
    }

    fn composite(&mut self, source: &Self, mask: Option<&skia::Mask>, opacity: f64) {
        debug_assert_eq!(self.region, source.region);
        for (index, (pixel, sample)) in self.pixels.iter_mut().zip(&source.pixels).enumerate() {
            let coverage = mask.map_or(1.0, |mask| f64::from(mask.data()[index]) / 255.0);
            over(pixel, sample.map(|channel| channel * coverage * opacity));
        }
    }

    fn paint(
        &mut self,
        region: skia::IntRect,
        samples: &skia::Pixmap,
        solid: Option<usvg::Color>,
        opacity: f64,
    ) {
        let width = self.region.width() as usize;
        let x = usize::try_from(region.x() - self.region.x()).expect("cropped raster region");
        let y = usize::try_from(region.y() - self.region.y()).expect("cropped raster region");
        let span = region.width() as usize;
        for (row, samples) in samples.pixels().chunks_exact(span).enumerate() {
            let start = (y + row) * width + x;
            for (pixel, sample) in self.pixels[start..start + span].iter_mut().zip(samples) {
                let alpha = f64::from(sample.alpha()) / 255.0 * opacity;
                let color = if let Some(color) = solid {
                    [
                        f64::from(color.red) / 255.0 * alpha,
                        f64::from(color.green) / 255.0 * alpha,
                        f64::from(color.blue) / 255.0 * alpha,
                    ]
                } else {
                    // Gradient channels are already premultiplied by sampled
                    // coverage. Their stop colors are opaque device RGB samples.
                    [sample.red(), sample.green(), sample.blue()]
                        .map(|value| f64::from(value) / 255.0 * opacity)
                };
                over(pixel, [color[0], color[1], color[2], alpha]);
            }
        }
    }
}

fn over(destination: &mut Pixel, source: Pixel) {
    let remaining = 1.0 - source[3];
    for (destination, source) in destination.iter_mut().zip(source) {
        *destination = source + *destination * remaining;
    }
}

/// All region coordinates are bounded by the admitted raster viewport.
#[expect(
    clippy::cast_precision_loss,
    reason = "the admitted pixel viewport is at most 32768 on either axis"
)]
fn local_transform(region: skia::IntRect, transform: skia::Transform) -> skia::Transform {
    transform.post_translate(-(region.x() as f32), -(region.y() as f32))
}

#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    reason = "floor/ceil bounds are clipped to the admitted, exactly representable tile coordinates"
)]
fn crop(
    bounds: skia::Rect,
    transform: skia::Transform,
    region: skia::IntRect,
) -> Option<skia::IntRect> {
    let bounds = bounds.transform(transform)?;
    let left = (bounds.left().floor() - 2.0).max(region.left() as f32);
    let top = (bounds.top().floor() - 2.0).max(region.top() as f32);
    let right = (bounds.right().ceil() + 2.0).min(region.right() as f32);
    let bottom = (bounds.bottom().ceil() + 2.0).min(region.bottom() as f32);
    if right <= left || bottom <= top {
        return None;
    }
    skia::IntRect::from_ltrb(left as i32, top as i32, right as i32, bottom as i32)
}

fn fill_rule(rule: usvg::FillRule) -> skia::FillRule {
    match rule {
        usvg::FillRule::NonZero => skia::FillRule::Winding,
        usvg::FillRule::EvenOdd => skia::FillRule::EvenOdd,
    }
}

fn coverage_paint(
    source: &usvg::Paint,
    antialias: bool,
) -> Result<(skia::Paint<'static>, Option<usvg::Color>)> {
    let mut paint = skia::Paint {
        anti_alias: antialias,
        ..skia::Paint::default()
    };
    match source {
        usvg::Paint::Color(color) => {
            // Rasterize coverage with opaque ink; retain RGB and opacity
            // independently so even full-coverage pixels aren't prequantized.
            paint.set_color_rgba8(0, 0, 0, 255);
            Ok((paint, Some(*color)))
        }
        usvg::Paint::LinearGradient(gradient) => {
            let stops = gradient
                .stops()
                .iter()
                .map(|stop| {
                    if stop.opacity().get() < 1.0 {
                        return Err(Error::Render(
                            "native color gradient requires opaque stops".into(),
                        ));
                    }
                    let color = stop.color();
                    Ok(skia::GradientStop::new(
                        stop.offset().get(),
                        skia::Color::from_rgba8(color.red, color.green, color.blue, 255),
                    ))
                })
                .collect::<Result<Vec<_>>>()?;
            let spread = match gradient.spread_method() {
                usvg::SpreadMethod::Pad => skia::SpreadMode::Pad,
                usvg::SpreadMethod::Reflect => skia::SpreadMode::Reflect,
                usvg::SpreadMethod::Repeat => skia::SpreadMode::Repeat,
            };
            paint.shader = skia::LinearGradient::new(
                (gradient.x1(), gradient.y1()).into(),
                (gradient.x2(), gradient.y2()).into(),
                stops,
                spread,
                gradient.transform(),
            )
            .ok_or_else(|| Error::Render("invalid frozen linear gradient".into()))?;
            Ok((paint, None))
        }
        _ => Err(Error::Render(
            "unsupported paint in the frozen native raster scene".into(),
        )),
    }
}

/// One path may carry independent fill and stroke paints. Rasterize them
/// separately, preserving the authored paint order and exact opacity.
fn path(
    path: &usvg::Path,
    transform: skia::Transform,
    tile: &mut Tile,
    region: skia::IntRect,
    opacity: Opacity,
) -> Result<()> {
    if !path.is_visible() {
        return Ok(());
    }
    let transform = local_transform(region, transform).pre_concat(path.abs_transform());
    let antialias = path.rendering_mode().use_shape_antialiasing();
    let area = region.width() as usize * region.height() as usize;
    let _coverage = crate::operation::scratch(area as u128 * 4)?;
    let mut samples = skia::Pixmap::new(region.width(), region.height())
        .ok_or_else(|| Error::Render("allocate raster coverage samples".into()))?;
    for stroke in match path.paint_order() {
        usvg::PaintOrder::FillAndStroke => [false, true],
        usvg::PaintOrder::StrokeAndFill => [true, false],
    } {
        samples.fill(skia::Color::TRANSPARENT);
        let (color, opacity) = if stroke {
            let Some(stroke) = path.stroke() else {
                continue;
            };
            if opacity.stroke >= 1.0 && stroke.opacity().get() < 1.0 {
                return Err(Error::Render("untracked native stroke opacity".into()));
            }
            let (paint, color) = coverage_paint(stroke.paint(), antialias)?;
            crate::operation::work(area)?;
            samples.stroke_path(path.data(), &paint, &stroke.to_tiny_skia(), transform, None);
            (color, opacity.stroke)
        } else {
            let Some(fill) = path.fill() else { continue };
            if opacity.fill >= 1.0 && fill.opacity().get() < 1.0 {
                return Err(Error::Render("untracked native fill opacity".into()));
            }
            let (paint, color) = coverage_paint(fill.paint(), antialias)?;
            crate::operation::work(area)?;
            samples.fill_path(path.data(), &paint, fill_rule(fill.rule()), transform, None);
            (color, opacity.fill)
        };
        tile.paint(region, &samples, color, opacity);
    }
    Ok(())
}

fn clip_children(
    group: &usvg::Group,
    transform: skia::Transform,
    mask: &mut skia::Mask,
) -> Result<()> {
    for node in group.children() {
        crate::operation::checkpoint()?;
        crate::operation::work(1)?;
        match node {
            usvg::Node::Path(path) if path.is_visible() => {
                if let Some(fill) = path.fill() {
                    mask.fill_path(
                        path.data(),
                        fill_rule(fill.rule()),
                        path.rendering_mode().use_shape_antialiasing(),
                        transform.pre_concat(path.abs_transform()),
                    );
                }
            }
            usvg::Node::Path(_) => {}
            usvg::Node::Group(group) if group.clip_path().is_none() => {
                clip_children(group, transform, mask)?;
            }
            _ => {
                return Err(Error::Render(
                    "unsupported clip in the frozen native raster scene".into(),
                ))
            }
        }
    }
    Ok(())
}

fn clip_mask(
    clip: &usvg::ClipPath,
    transform: skia::Transform,
    region: skia::IntRect,
) -> Result<skia::Mask> {
    let mut mask = skia::Mask::new(region.width(), region.height())
        .ok_or_else(|| Error::Render("allocate raster clip coverage".into()))?;
    clip_children(
        clip.root(),
        local_transform(region, transform).pre_concat(clip.transform()),
        &mut mask,
    )?;
    // Native nested clipping is represented by separate isolated groups.
    if clip.clip_path().is_some() {
        return Err(Error::Render(
            "unexpected chained clip definition in native scene".into(),
        ));
    }
    Ok(mask)
}

fn group(
    scene: &RasterScene,
    source: &usvg::Group,
    transform: skia::Transform,
    tile: &mut Tile,
) -> Result<()> {
    if source.mask().is_some()
        || !source.filters().is_empty()
        || source.blend_mode() != usvg::BlendMode::Normal
    {
        return Err(Error::Render(
            "unsupported group effect in the frozen native raster scene".into(),
        ));
    }
    let opacity = scene.opacity(source.id())?.group;
    if opacity >= 1.0 && source.opacity().get() < 1.0 {
        return Err(Error::Render("untracked native group opacity".into()));
    }
    if !source.should_isolate() && opacity >= 1.0 {
        return children(scene, source, transform, tile);
    }
    let mut layer = Tile::new(tile.region)?;
    children(scene, source, transform, &mut layer)?;
    let area = tile.region.width() as usize * tile.region.height() as usize;
    let _mask_storage = crate::operation::scratch(if source.clip_path().is_some() {
        area as u128
    } else {
        0
    })?;
    let mask = source
        .clip_path()
        .map(|clip| {
            clip_mask(
                clip,
                transform.pre_concat(source.abs_transform()),
                tile.region,
            )
        })
        .transpose()?;
    crate::operation::work(area)?;
    tile.composite(&layer, mask.as_ref(), opacity);
    Ok(())
}

fn children(
    scene: &RasterScene,
    source: &usvg::Group,
    transform: skia::Transform,
    tile: &mut Tile,
) -> Result<()> {
    for (index, node) in source.children().iter().enumerate() {
        if index % 64 == 0 {
            crate::operation::checkpoint()?;
        }
        crate::operation::work(1)?;
        let Some(region) = crop(node.abs_stroke_bounding_box(), transform, tile.region) else {
            continue;
        };
        match node {
            usvg::Node::Path(value) => {
                path(value, transform, tile, region, scene.opacity(value.id())?)?;
            }
            usvg::Node::Group(value) => group(scene, value, transform, tile)?,
            _ => {
                return Err(Error::Render(
                    "raster publication requires the outlined native scene".into(),
                ))
            }
        }
    }
    Ok(())
}

#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "final straight samples are clamped and rounded to the complete byte range"
)]
fn rgba8(pixel: Pixel) -> [u8; 4] {
    let sample = |value: f64| {
        let value = value.clamp(0.0, 1.0);
        let scaled = value * 255.0;
        let mut rounded = scaled.round_ties_even();
        if scaled.fract().to_bits() == 0.5_f64.to_bits() {
            // A rounded multiply can create a false tie. The fused residual
            // recovers which side of the half-byte the represented value lies.
            let residual = value.mul_add(255.0, -scaled);
            if residual < 0.0 {
                rounded = scaled.floor();
            } else if residual > 0.0 {
                rounded = scaled.ceil();
            }
        }
        rounded as u8
    };
    let alpha = sample(pixel[3]);
    if alpha == 0 {
        [0; 4]
    } else {
        [
            sample(pixel[0] / pixel[3]),
            sample(pixel[1] / pixel[3]),
            sample(pixel[2] / pixel[3]),
            alpha,
        ]
    }
}

/// Tile-local premultiplied binary64 compositing bounds working storage by
/// the actual tile and isolated-group depth, rather than the entire page.
pub(super) fn render(
    scene: &RasterScene,
    transform: skia::Transform,
    size: skia::IntSize,
) -> Result<Vec<u8>> {
    let width = size.width() as usize;
    let count = width
        .checked_mul(size.height() as usize)
        .and_then(|count| count.checked_mul(4))
        .ok_or_else(|| Error::Render("raster sample count overflow".into()))?;
    crate::operation::memory(count as u128)?;
    let mut result = storage(count, 0_u8)?;
    for y in (0..size.height()).step_by(TILE as usize) {
        for x in (0..size.width()).step_by(TILE as usize) {
            crate::operation::checkpoint()?;
            let region = skia::IntRect::from_xywh(
                i32::try_from(x).expect("admitted raster width"),
                i32::try_from(y).expect("admitted raster height"),
                TILE.min(size.width() - x),
                TILE.min(size.height() - y),
            )
            .expect("nonempty raster tile");
            let mut tile = Tile::new(region)?;
            children(scene, scene.tree.root(), transform, &mut tile)?;
            let span = region.width() as usize;
            crate::operation::work(tile.pixels.len())?;
            for (row, pixels) in tile.pixels.chunks_exact(span).enumerate() {
                let start = ((y as usize + row) * width + x as usize) * 4;
                for (destination, pixel) in result[start..start + span * 4]
                    .chunks_exact_mut(4)
                    .zip(pixels)
                {
                    destination.copy_from_slice(&rgba8(*pixel));
                }
            }
        }
    }
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn isolated_group_opacity_applies_after_children_and_across_tiles() {
        // Actual normalized SVG paths, including a real clip crossing the
        // device's tile boundary. The publication accumulator is the same one
        // used by Output::png.
        let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="520" height="20">
          <defs><clipPath id="clip"><rect x="250" y="0" width="30" height="20"/></clipPath></defs>
          <g opacity="0.5" clip-path="url(#clip)">
            <rect x="240" y="2" width="40" height="16" fill="#B43214"/>
            <rect x="255" y="2" width="40" height="16" fill="#B43214"/>
          </g>
          <rect x="340" y="2" width="40" height="16" fill="#B43214" fill-opacity="0.5"/>
          <rect x="350" y="2" width="40" height="16" fill="#B43214" fill-opacity="0.5"/>
          <g id="precise" opacity="0.49999999999999994">
            <rect x="400" y="2" width="20" height="16" fill="#B43214"/>
            <rect x="405" y="2" width="20" height="16" fill="#B43214"/>
          </g>
          <rect x="440" y="2" width="20" height="16" fill="#B43214" fill-opacity="0.49999999999999994"/>
          <path d="M 480 2 L 480 18" fill="none" stroke="#B43214" stroke-width="8" stroke-opacity="0.49999999999999994"/>
        </svg>"##;
        let scene = RasterScene::parse(svg.as_bytes()).unwrap();
        let pixels = render(
            &scene,
            skia::Transform::identity(),
            skia::IntSize::from_wh(520, 20).unwrap(),
        )
        .unwrap();
        let at = |x: usize| &pixels[(10 * 520 + x) * 4..(10 * 520 + x + 1) * 4];
        assert_eq!(at(249), &[0, 0, 0, 0]);
        assert_eq!(at(251), &[180, 50, 20, 128]);
        assert_eq!(at(260), &[180, 50, 20, 128]);
        assert_eq!(at(280), &[0, 0, 0, 0]);
        assert_eq!(at(345), &[180, 50, 20, 128]);
        assert_eq!(at(355), &[180, 50, 20, 191]);
        assert_eq!(at(412), &[180, 50, 20, 127]);
        assert_eq!(at(450), &[180, 50, 20, 127]);
        assert_eq!(at(480), &[180, 50, 20, 127]);
    }

    #[test]
    fn final_sampling_disambiguates_a_rounded_half_byte() {
        // This represented alpha is just below 1.5/255, although the
        // ordinary binary64 multiply rounds its product to exactly 1.5.
        let alpha = 1.5 / 255.0;
        assert_eq!(rgba8([alpha, alpha, alpha, alpha]), [255, 255, 255, 1]);
        assert_eq!(rgba8([0.5, 0.5, 0.5, 0.5]), [255, 255, 255, 128]);
    }
}