use super::PlannedCall;
use crate::layout::{InkExtent, PaintBatch, PaintBatchRef, Rect};
use crate::render::coordinates::CanonicalPoint;
use crate::render::primitives::{CanonicalMarkers, CanonicalPlannedText};
use crate::render::svg_backend::{CountBuffer, SvgSerializer};
use crate::{Error, Result};
pub(super) struct PaintCapture {
pub reference: PaintBatchRef,
pub start: usize,
pub end: usize,
}
fn bounds(points: impl IntoIterator<Item = (f64, f64)>, outset: f64) -> Result<InkExtent> {
let mut points = points.into_iter();
let Some((x, y)) = points.next() else {
return Ok(InkExtent::Empty);
};
let mut edges = [x, y, x, y];
for (index, (x, y)) in points.enumerate() {
if index.is_multiple_of(1024) {
crate::operation::check()?;
}
edges[0] = edges[0].min(x);
edges[1] = edges[1].min(y);
edges[2] = edges[2].max(x);
edges[3] = edges[3].max(y);
}
let width = edges[2] - edges[0] + 2.0 * outset;
let height = edges[3] - edges[1] + 2.0 * outset;
if width <= 0.0 || height <= 0.0 {
return Ok(InkExtent::Empty);
}
Ok(InkExtent::Bounds(Rect::new(
edges[0] - outset,
edges[1] - outset,
width,
height,
)?))
}
fn coordinates(points: &[CanonicalPoint]) -> impl Iterator<Item = (f64, f64)> + '_ {
points
.iter()
.map(|point| (point.x.value(), point.y.value()))
}
fn stroke(paint: crate::Color, width: f64) -> f64 {
if paint.get_alpha() > 0.0 {
width
} else {
0.0
}
}
#[expect(
clippy::cast_precision_loss,
reason = "frozen glyph bounds are exact spatial quanta"
)]
fn text_extent(text: &CanonicalPlannedText, clip: Rect) -> Result<InkExtent> {
let text = &text.0;
if text.suppressed || text.text.style.paint.get_alpha() == 0.0 {
return Ok(InkExtent::Empty);
}
let clip = if let Some(local) = text.clip {
let Some(clip) = clip.intersection(Rect::from_canonical(local)?) else {
return Ok(InkExtent::Empty);
};
clip
} else {
clip
};
let center = text.center.value();
let (sin, cos) = text.rotation_sin_cos;
let mut ink = InkExtent::Empty;
for (line, placed) in text.text.lines.iter().zip(&text.lines) {
let Some(extent) = line.ink_quanta else {
continue;
};
let origin = placed.origin.value();
let left = origin.x + extent.left as f64 / 1024.;
let right = origin.x + extent.right as f64 / 1024.;
let top = origin.y - extent.top as f64 / 1024.;
let bottom = origin.y - extent.bottom as f64 / 1024.;
let corners = [(left, top), (left, bottom), (right, top), (right, bottom)];
ink = ink.union(
bounds(
corners.map(|(x, y)| {
let x = x - center.x;
let y = y - center.y;
(center.x + x * cos - y * sin, center.y + x * sin + y * cos)
}),
0.,
)?
.clipped(clip),
);
}
Ok(ink)
}
fn path_extents<'a>(
paths: impl IntoIterator<Item = &'a [CanonicalPoint]>,
outset: f64,
clip: Rect,
) -> Result<InkExtent> {
let mut ink = InkExtent::Empty;
for (index, path) in paths.into_iter().enumerate() {
if index.is_multiple_of(1024) {
crate::operation::check()?;
}
ink = ink.union(bounds(coordinates(path), outset)?.clipped(clip));
}
Ok(ink)
}
fn extent(call: &PlannedCall, viewport: Rect, clip: Rect) -> Result<InkExtent> {
use crate::render::backend::SurfaceRole;
Ok(match call {
PlannedCall::Surface {
bounds,
paint,
role,
} => {
if paint.get_alpha() == 0.0 {
InkExtent::Empty
} else if *role == SurfaceRole::CanvasRoot {
InkExtent::Bounds(viewport)
} else {
InkExtent::Bounds(Rect::from_canonical(*bounds)?)
}
}
PlannedCall::Scatter(scatter) => {
let stroke = scatter
.outline
.map_or(0., |(paint, width)| stroke(paint, width.value()));
if scatter.color.get_alpha() == 0.0 && stroke == 0.0 {
InkExtent::Empty
} else {
match &scatter.markers {
CanonicalMarkers::Circles { points, radius } => path_extents(
points.iter().map(std::slice::from_ref),
radius.value() + stroke / 2.,
clip,
)?,
CanonicalMarkers::Triangles(triangles) => path_extents(
triangles.iter().map(<[CanonicalPoint; 3]>::as_slice),
stroke * crate::render::backend::POLYGON_MITER_LIMIT / 2.,
clip,
)?,
}
}
}
PlannedCall::Line { points, style } => {
let stroke = stroke(style.color, style.width.value());
if stroke == 0.0 {
InkExtent::Empty
} else {
path_extents(points.windows(2), stroke / 2., clip)?
}
}
PlannedCall::Polygon { points, style } => {
let stroke = if points.windows(2).any(|pair| pair[0] != pair[1]) {
stroke(style.stroke, style.stroke_width.value())
} else {
0.
};
if stroke == 0.0
&& (style.color.get_alpha() == 0.0
|| !crate::render::geometry::polygon_has_positive_area(points)?)
{
InkExtent::Empty
} else {
bounds(
coordinates(points),
stroke * crate::render::backend::POLYGON_MITER_LIMIT / 2.,
)?
}
}
PlannedCall::LinearGradient(gradient) => {
InkExtent::Bounds(Rect::from_canonical(gradient.bounds)?)
}
PlannedCall::PlannedText(text) => text_extent(&text.canonical, clip)?,
PlannedCall::RoundedRect(rounded) => {
let stroke = stroke(rounded.stroke, rounded.stroke_width.value());
if rounded.bounds.width.units() == 0
|| rounded.bounds.height.units() == 0
|| (rounded.color.get_alpha() == 0.0 && stroke == 0.0)
{
InkExtent::Empty
} else {
let rect = Rect::from_canonical(rounded.bounds)?;
bounds(
[
(rect.left(), rect.top()),
(rect.left() + rect.width(), rect.top() + rect.height()),
],
stroke / 2.,
)?
}
}
PlannedCall::PlannedBracket(bracket) => {
let canonical = &bracket.canonical;
let stroke = stroke(canonical.color, canonical.width.value());
let path = if stroke == 0.0 {
InkExtent::Empty
} else {
bounds(coordinates(&canonical.points), stroke / 2.)?
};
path.union(text_extent(&canonical.text, clip)?)
}
PlannedCall::Fixed(content) => content.ink(),
_ => InkExtent::Empty,
})
}
fn batch_geometry(calls: &[PlannedCall], viewport: Rect) -> Result<(InkExtent, Vec<Rect>)> {
let mut ink = InkExtent::Empty;
let mut clips = Vec::new();
let mut stack = vec![Some(viewport)];
for (index, call) in calls.iter().enumerate() {
if index.is_multiple_of(64) {
crate::operation::checkpoint()?;
}
match call {
PlannedCall::BeginClip(clip) => {
let rect = Rect::from_canonical(*clip)?;
crate::data::source::reserve_source(&mut clips, 1)?;
clips.push(rect);
let effective = stack
.last()
.copied()
.flatten()
.and_then(|prior| prior.intersection(rect));
crate::data::source::reserve_source(&mut stack, 1)?;
stack.push(effective);
}
PlannedCall::EndClip => {
stack.pop();
}
_ => {
if let PlannedCall::Fixed(content) = call {
crate::data::source::reserve_source(&mut clips, 1)?;
clips.push(content.frame);
}
let text_clip = match call {
PlannedCall::PlannedText(text) => text.canonical.0.clip,
PlannedCall::PlannedBracket(bracket) => bracket.canonical.text.0.clip,
_ => None,
};
if let Some(clip) = text_clip {
crate::data::source::reserve_source(&mut clips, 1)?;
clips.push(Rect::from_canonical(clip)?);
}
if let Some(clip) = stack.last().copied().flatten() {
ink = ink.union(extent(call, viewport, clip)?.clipped(clip));
}
}
}
}
if stack.len() != 1 {
return Err(Error::Render("paint batch has unclosed clip scopes".into()));
}
Ok((ink, clips))
}
fn emit_calls(calls: &[PlannedCall], serializer: &mut SvgSerializer<CountBuffer>) -> Result<()> {
for call in calls {
call.emit_svg(serializer)?;
#[cfg(test)]
serializer.overflow_count_after_text_for_test();
}
Ok(())
}
pub(super) fn emit(
calls: &[PlannedCall],
captures: &[PaintCapture],
serializer: &mut SvgSerializer<CountBuffer>,
viewport: Option<Rect>,
) -> Result<Vec<PaintBatch>> {
let Some(viewport) = viewport else {
emit_calls(calls, serializer)?;
return Ok(Vec::new());
};
let mut batches = Vec::new();
crate::data::source::reserve_source(&mut batches, captures.len())?;
let mut cursor = 0;
for capture in captures {
if cursor != capture.start || serializer.paint_scope_depth() != 0 {
return Err(Error::Render(
"native paint inventory has an unclosed or unowned range".into(),
));
}
let before = serializer.paint_offsets();
let batch_calls = &calls[capture.start..capture.end];
emit_calls(batch_calls, serializer)?;
cursor = capture.end;
if serializer.paint_scope_depth() != 0 {
return Err(Error::Render(
"native paint batch leaves a scope open".into(),
));
}
let (ink, clips) = batch_geometry(batch_calls, viewport)?;
if ink == InkExtent::Empty {
continue;
}
let after = serializer.paint_offsets();
let mut changed = (0..before.len()).filter(|&index| before[index] != after[index]);
let buffer = changed
.next()
.ok_or_else(|| Error::Render("painted batch produced no native paint range".into()))?;
if changed.next().is_some() {
return Err(Error::Render(
"paint batch crosses reordered native emission buffers".into(),
));
}
batches.push(PaintBatch {
reference: capture.reference.clone(),
clips,
ink,
buffer,
range: before[buffer]..after[buffer],
});
}
if cursor != calls.len() {
return Err(Error::Render(
"native paint inventory omitted final drawing calls".into(),
));
}
Ok(batches)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::render::{
coordinates::{CanonicalBox, CanonicalCoordinate, CanonicalRoundedBox},
primitives::{CanonicalFillStyle, CanonicalScatter},
};
use crate::Color;
fn point(x: i64, y: i64) -> CanonicalPoint {
CanonicalPoint {
x: CanonicalCoordinate::from_quanta(x * 1024),
y: CanonicalCoordinate::from_quanta(y * 1024),
}
}
#[test]
fn individually_clipped_markers_do_not_manufacture_an_ink_extent() {
let viewport = Rect::new(0., 0., 100., 100.).unwrap();
let call = PlannedCall::Scatter(CanonicalScatter {
markers: CanonicalMarkers::Circles {
points: vec![point(-10, 50), point(110, 50)],
radius: CanonicalCoordinate::from_quanta(1024),
},
color: Color::rgb(0, 0, 0),
outline: None,
});
assert_eq!(
batch_geometry(&[call], viewport).unwrap().0,
InkExtent::Empty
);
}
#[test]
fn retraced_polygon_and_degenerate_rectangle_have_no_ink() {
let viewport = Rect::new(0., 0., 100., 100.).unwrap();
let black = Color::rgb(0, 0, 0);
let fill = PlannedCall::Polygon {
points: vec![point(10, 10), point(90, 90), point(50, 50)],
style: CanonicalFillStyle {
color: black,
stroke: black,
stroke_width: CanonicalCoordinate::from_quanta(0),
},
};
assert_eq!(extent(&fill, viewport, viewport).unwrap(), InkExtent::Empty);
let zero = CanonicalCoordinate::from_quanta(0);
let rounded = PlannedCall::RoundedRect(CanonicalRoundedBox {
bounds: CanonicalBox {
x: zero,
y: zero,
width: CanonicalCoordinate::from_quanta(10 * 1024),
height: zero,
},
radius: zero,
stroke_width: CanonicalCoordinate::from_quanta(1024),
color: black,
stroke: black,
});
assert_eq!(
extent(&rounded, viewport, viewport).unwrap(),
InkExtent::Empty
);
}
}