lichtung-plot 0.3.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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
//! 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 crate::output::{PixelFormat, PixelOptions, RowOrder};
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,
}

enum ImageSamples {
    Png(crate::composition::PngSamples),
    Svg(Box<ForeignSvg>),
}

struct ForeignSvg {
    tree: usvg::Tree,
    raster: std::sync::Mutex<Option<(skia::IntRect, skia::Pixmap)>>,
}

struct RasterImage {
    geometry: usvg::Tree,
    samples: ImageSamples,
}

impl RasterImage {
    fn prepare(href: &str) -> Result<Self> {
        let (mime, bytes) = crate::composition::read_data_uri(href)?;
        let samples = match mime.as_str() {
            "image/png" => ImageSamples::Png(crate::composition::png_samples(&bytes)?),
            "image/svg+xml" => ImageSamples::Svg(Box::new(ForeignSvg {
                tree: crate::composition::raster_svg(&bytes)?,
                raster: std::sync::Mutex::new(None),
            })),
            _ => {
                return Err(Error::Render(
                    format!("unsupported retained image MIME type {mime}").into(),
                ))
            }
        };
        let (width, height) = match &samples {
            ImageSamples::Png(png) => (f64::from(png.width), f64::from(png.height)),
            ImageSamples::Svg(svg) => (
                f64::from(svg.tree.size().width()),
                f64::from(svg.tree.size().height()),
            ),
        };
        // The parser resolves placement using the source's actual viewport.
        // Its image node is a geometry carrier; sampling is performed by the
        // retained resource below, with its own alpha and color interpretation.
        let svg = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\"><rect width=\"{width}\" height=\"{height}\"/></svg>");
        let geometry = usvg::Tree::from_str(&svg, &usvg::Options::default())
            .map_err(|error| Error::Render(format!("fixed image viewport: {error}").into()))?;
        Ok(Self { geometry, samples })
    }
}

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>,
    images: std::collections::HashMap<String, RasterImage>,
}

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 doc = roxmltree::Document::parse(svg).map_err(|error| {
            Error::Render(format!("parse native paint operands: {error}").into())
        })?;
        let mut opacities = Vec::new();
        let mut images = std::collections::HashMap::new();
        let mut edits = Vec::new();
        for (index, node) in doc.descendants().enumerate() {
            if index.is_multiple_of(64) {
                crate::operation::checkpoint()?;
            }
            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(),
                ));
            }
            if node.has_tag_name("image") {
                let id = node
                    .attribute("id")
                    .ok_or_else(|| Error::Render("native image has no frozen identity".into()))?;
                let href = node
                    .attribute_node("href")
                    .ok_or_else(|| Error::Render("native image has no retained source".into()))?;
                let image = RasterImage::prepare(href.value())?;
                if images.insert(id.to_owned(), image).is_some() {
                    return Err(Error::Render("duplicate native image identity".into()));
                }
                edits.push((href.range_value(), id.to_owned()));
            }
            if !Opacity::present(node) {
                continue;
            }
            let index = opacities.len();
            crate::data::source::reserve_source(&mut opacities, 1)?;
            opacities.push(Opacity::read(node)?);
            let id = format!("{OPACITY_ID}{index}");
            if let Some(attribute) = node.attribute_node("id") {
                edits.push((attribute.range_value(), id));
            } else {
                let end = node.range().start + 1 + node.tag_name().name().len();
                edits.push((end..end, format!(" id=\"{id}\"")));
            }
        }
        let normalized = if edits.is_empty() {
            std::borrow::Cow::Borrowed(svg)
        } else {
            edits.sort_by_key(|(range, _)| (range.start, range.end));
            let mut normalized = String::new();
            let mut cursor = 0;
            for (range, text) in edits {
                crate::data::source::reserve_source_string(
                    &mut normalized,
                    range.start - cursor + text.len(),
                )?;
                normalized.push_str(&svg[cursor..range.start]);
                normalized.push_str(&text);
                cursor = range.end;
            }
            normalized.push_str(&svg[cursor..]);
            std::borrow::Cow::Owned(normalized)
        };
        let options = usvg::Options {
            image_href_resolver: usvg::ImageHrefResolver {
                resolve_string: Box::new(|href, _| {
                    images
                        .get(href)
                        .map(|image| usvg::ImageKind::SVG(image.geometry.clone()))
                }),
                resolve_data: Box::new(|_, _, _| None),
            },
            ..Default::default()
        };
        let tree = usvg::Tree::from_str(&normalized, &options).map_err(|error| {
            Error::Render(format!("parse svg for png rasterization: {error}").into())
        })?;
        drop(options);
        Ok(Self {
            tree,
            opacities,
            images,
        })
    }
    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,
    viewport: skia::IntRect,
    pixels: Vec<Pixel>,
}

impl Tile {
    fn new(region: skia::IntRect, viewport: skia::IntRect) -> Result<Self> {
        let count = region.width() as usize * region.height() as usize;
        crate::operation::check()?;
        Ok(Self {
            region,
            viewport,
            pixels: storage(count, [0.0; 4])?,
        })
    }

    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();
    crate::operation::check()?;
    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::check()?;
            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::check()?;
            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()?;
        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 view_mask(
    placement: &usvg::Image,
    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 image viewport coverage".into()))?;
    mask.fill_path(
        &skia::PathBuilder::from_rect(placement.bounding_box()),
        skia::FillRule::Winding,
        true,
        local_transform(region, transform),
    );
    Ok(mask)
}

#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "source indices are clamped to the validated PNG sample dimensions"
)]
fn png_sample(png: &crate::composition::PngSamples, x: f64, y: f64, nearest: bool) -> Pixel {
    let at = |x: f64, y: f64| {
        let x = x.clamp(0., f64::from(png.width - 1)) as usize;
        let y = y.clamp(0., f64::from(png.height - 1)) as usize;
        let [red, green, blue, alpha] =
            png.rgba[y * png.width as usize + x].map(|value| f64::from(value) / 65535.);
        [red * alpha, green * alpha, blue * alpha, alpha]
    };
    if nearest {
        return at(x.floor(), y.floor());
    }
    let x = x - 0.5;
    let y = y - 0.5;
    let left = x.floor();
    let top = y.floor();
    let dx = x - left;
    let dy = y - top;
    let mut result = [0.; 4];
    for (sx, wx) in [(left, 1. - dx), (left + 1., dx)] {
        for (sy, wy) in [(top, 1. - dy), (top + 1., dy)] {
            for (destination, sample) in result.iter_mut().zip(at(sx, sy)) {
                *destination += sample * wx * wy;
            }
        }
    }
    result
}

#[expect(
    clippy::cast_precision_loss,
    reason = "actual target pixel coordinates are bounded by the raster device"
)]
fn draw_png_image(
    png: &crate::composition::PngSamples,
    placement: &usvg::Image,
    transform: skia::Transform,
    tile: &mut Tile,
    mask: &skia::Mask,
) -> Result<()> {
    let inverse = transform
        .invert()
        .ok_or_else(|| Error::Render("image transform is singular on the raster device".into()))?;
    let nearest = placement.rendering_mode() == usvg::ImageRendering::CrispEdges;
    let width = tile.region.width() as usize;
    for (index, (pixel, coverage)) in tile.pixels.iter_mut().zip(mask.data()).enumerate() {
        if *coverage == 0 {
            continue;
        }
        let mut point = skia::Point::from_xy(
            tile.region.x() as f32 + (index % width) as f32 + 0.5,
            tile.region.y() as f32 + (index / width) as f32 + 0.5,
        );
        inverse.map_point(&mut point);
        let sample = png_sample(png, f64::from(point.x), f64::from(point.y), nearest);
        let coverage = f64::from(*coverage) / 255.;
        over(pixel, sample.map(|channel| channel * coverage));
    }
    Ok(())
}

fn draw_image(
    image: &RasterImage,
    placement: &usvg::Image,
    transform: skia::Transform,
    tile: &mut Tile,
) -> Result<()> {
    if !placement.is_visible() {
        return Ok(());
    }
    let transform = transform.pre_concat(placement.abs_transform());
    let mask = view_mask(placement, transform, tile.region)?;
    match &image.samples {
        ImageSamples::Png(png) => draw_png_image(png, placement, transform, tile, &mask),
        ImageSamples::Svg(svg) => draw_foreign_svg(svg, placement, transform, tile, &mask),
    }
}

fn draw_foreign_svg(
    svg: &ForeignSvg,
    placement: &usvg::Image,
    transform: skia::Transform,
    tile: &mut Tile,
    mask: &skia::Mask,
) -> Result<()> {
    let mut cache = svg
        .raster
        .lock()
        .map_err(|_| Error::Render("embedded SVG raster cache poisoned".into()))?;
    if cache.is_none() {
        let Some(region) = crop(placement.bounding_box(), transform, tile.viewport) else {
            return Ok(());
        };
        let mut samples = skia::Pixmap::new(region.width(), region.height())
            .ok_or_else(|| Error::Render("allocate embedded SVG device region".into()))?;
        // Filters and masks can depend on adjacent samples. Render the actual
        // visible device region once, rather than introducing tile edges inside
        // the foreign document's compositing program.
        crate::operation::check()?;
        resvg::render(
            &svg.tree,
            local_transform(region, transform),
            &mut samples.as_mut(),
        );
        *cache = Some((region, samples));
    }
    let (region, samples) = cache.as_ref().expect("prepared foreign image");
    let Some(overlap) = tile.region.intersect(region) else {
        return Ok(());
    };
    let tile_width = tile.region.width() as usize;
    let sample_width = region.width() as usize;
    for y in overlap.top()..overlap.bottom() {
        let tile_row = usize::try_from(y - tile.region.top()).expect("tile row") * tile_width;
        let sample_row = usize::try_from(y - region.top()).expect("image row") * sample_width;
        for x in overlap.left()..overlap.right() {
            let index = tile_row + usize::try_from(x - tile.region.left()).expect("tile column");
            let source = sample_row + usize::try_from(x - region.left()).expect("image column");
            let sample = samples.pixels()[source];
            let coverage = f64::from(mask.data()[index]) / 255.;
            over(
                &mut tile.pixels[index],
                [sample.red(), sample.green(), sample.blue(), sample.alpha()]
                    .map(|channel| f64::from(channel) / 255. * coverage),
            );
        }
    }
    Ok(())
}
fn group(
    scene: &RasterScene,
    source: &usvg::Group,
    transform: skia::Transform,
    tile: &mut Tile,
) -> Result<()> {
    if let Some(image) = scene.images.get(source.id()) {
        let [usvg::Node::Image(placement)] = source.children() else {
            return Err(Error::Render(
                "native image lost its isolated placement".into(),
            ));
        };
        return draw_image(image, placement, transform, tile);
    }
    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, tile.viewport)?;
    children(scene, source, transform, &mut layer)?;
    crate::operation::check()?;
    let mask = source
        .clip_path()
        .map(|clip| {
            clip_mask(
                clip,
                transform.pre_concat(source.abs_transform()),
                tile.region,
            )
        })
        .transpose()?;
    crate::operation::check()?;
    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::check()?;
        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 samples are clamped and rounded to the complete byte range"
)]
fn sample_byte(value: f64) -> u8 {
    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
}

fn rgba8(pixel: Pixel) -> [u8; 4] {
    let alpha = sample_byte(pixel[3]);
    if alpha == 0 {
        [0; 4]
    } else {
        [
            sample_byte(pixel[0] / pixel[3]),
            sample_byte(pixel[1] / pixel[3]),
            sample_byte(pixel[2] / pixel[3]),
            alpha,
        ]
    }
}

fn write_pixel(destination: &mut [u8], pixel: Pixel, format: PixelFormat) -> Result<()> {
    match format {
        PixelFormat::Rgba8 => destination.copy_from_slice(&rgba8(pixel)),
        PixelFormat::Rgb8 => {
            if pixel[3] < 1.0 {
                return Err(Error::Render(
                    "RGB8 cannot represent residual transparency; supply an opaque matte".into(),
                ));
            }
            destination.copy_from_slice(&rgba8(pixel)[..3]);
        }
        PixelFormat::PremultipliedRgba8 | PixelFormat::PremultipliedBgra8 => {
            let mut samples = pixel.map(sample_byte);
            if format == PixelFormat::PremultipliedBgra8 {
                samples.swap(0, 2);
            }
            destination.copy_from_slice(&samples);
        }
    }
    Ok(())
}

/// 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,
    options: &PixelOptions,
) -> Result<Vec<u8>> {
    let width = size.width() as usize;
    let height = size.height() as usize;
    let format = options.format.unwrap_or_default();
    let channels = format.channels();
    let order = options.row_order.unwrap_or_default();
    let paper = options.matte.map_or([0.; 4], |matte| {
        [
            f64::from(matte.red()) / 255.,
            f64::from(matte.green()) / 255.,
            f64::from(matte.blue()) / 255.,
            1.,
        ]
    });
    let count = width
        .checked_mul(height)
        .and_then(|count| count.checked_mul(channels))
        .ok_or_else(|| Error::Render("raster sample count overflow".into()))?;
    crate::operation::check()?;
    let mut result = storage(count, 0_u8)?;
    let viewport = skia::IntRect::from_xywh(0, 0, size.width(), size.height())
        .expect("admitted raster viewport");
    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, viewport)?;
            if options.matte.is_some() {
                tile.pixels.fill(paper);
            }
            children(scene, scene.tree.root(), transform, &mut tile)?;
            let span = region.width() as usize;
            crate::operation::check()?;
            for (row, pixels) in tile.pixels.chunks_exact(span).enumerate() {
                let row = y as usize + row;
                let stored_row = match order {
                    RowOrder::TopDown => row,
                    RowOrder::BottomUp => height - 1 - row,
                };
                let start = (stored_row * width + x as usize) * channels;
                for (destination, pixel) in result[start..start + span * channels]
                    .chunks_exact_mut(channels)
                    .zip(pixels)
                {
                    write_pixel(destination, *pixel, format)?;
                }
            }
        }
    }
    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(),
            &PixelOptions::default(),
        )
        .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]);
    }
}