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")?,
};
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)
}
}
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())
})?;
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 {
[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;
}
}
#[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) => {
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(),
)),
}
}
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,
)?;
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() {
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,
]
}
}
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() {
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() {
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]);
}
}