use super::Precision;
use crate::{
layout::{InkExtent, Rect},
Result,
};
use kurbo::{Affine, BezPath, ParamCurve, ParamCurveExtrema, PathEl, PathSeg, Point, Shape, Vec2};
#[derive(Clone, Copy)]
pub(super) enum FillRule {
NonZero,
EvenOdd,
}
impl FillRule {
fn contains(self, path: &BezPath, point: Point) -> bool {
let winding = path.winding(point);
match self {
Self::NonZero => winding != 0,
Self::EvenOdd => winding % 2 != 0,
}
}
}
fn edges(rect: Rect) -> [f64; 4] {
[
rect.left(),
rect.top(),
rect.left() + rect.width(),
rect.top() + rect.height(),
]
}
pub(super) fn corners(rect: Rect) -> [Point; 4] {
let [left, top, right, bottom] = edges(rect);
[
Point::new(left, top),
Point::new(right, top),
Point::new(right, bottom),
Point::new(left, bottom),
]
}
fn point_in(rect: Rect, point: Point, strict: bool) -> bool {
let [left, top, right, bottom] = edges(rect);
if strict {
left < point.x && point.x < right && top < point.y && point.y < bottom
} else {
left <= point.x && point.x <= right && top <= point.y && point.y <= bottom
}
}
#[derive(Default)]
struct Bounds(Option<kurbo::Rect>);
impl Bounds {
fn point(&mut self, point: Point) {
self.0 = Some(
self.0
.map_or(kurbo::Rect::from_points(point, point), |bounds| {
bounds.union_pt(point)
}),
);
}
fn rect(&mut self, rect: kurbo::Rect) {
self.0 = Some(self.0.map_or(rect, |bounds| bounds.union(rect)));
}
fn extent(self) -> Result<InkExtent> {
let Some(rect) = self
.0
.filter(|rect| rect.width() > 0. && rect.height() > 0.)
else {
return Ok(InkExtent::Empty);
};
Ok(InkExtent::Bounds(Rect::new(
rect.x0,
rect.y0,
rect.width(),
rect.height(),
)?))
}
}
pub(super) fn close_for_fill(path: &BezPath) -> BezPath {
let mut closed = BezPath::new();
for contour in path.subpaths() {
if contour_is_linear(contour) {
continue;
}
for &element in contour {
closed.push(element);
}
if contour.last() != Some(&PathEl::ClosePath) {
closed.close_path();
}
}
closed
}
fn contour_is_linear(contour: &[PathEl]) -> bool {
use crate::numeric::binary::units;
let mut points = contour
.iter()
.flat_map(|element| match *element {
PathEl::MoveTo(point) | PathEl::LineTo(point) => [Some(point), None, None],
PathEl::QuadTo(control, end) => [Some(control), Some(end), None],
PathEl::CurveTo(first, second, end) => [Some(first), Some(second), Some(end)],
PathEl::ClosePath => [None; 3],
})
.flatten();
let Some(first) = points.next() else {
return true;
};
let Some(second) = points.find(|point| *point != first) else {
return true;
};
points.all(|point| {
if first.x.to_bits() == second.x.to_bits() {
return first.x.to_bits() == point.x.to_bits();
}
if first.y.to_bits() == second.y.to_bits() {
return first.y.to_bits() == point.y.to_bits();
}
if point == first || point == second {
return true;
}
if (second - first).cross(point - first) != 0. {
return false;
}
let determinant = || -> Result<bool> {
let x = units(first.x)?;
let y = units(first.y)?;
Ok((units(second.x)? - &x) * (units(point.y)? - &y)
== (units(second.y)? - &y) * (units(point.x)? - &x))
};
determinant().unwrap_or(false)
})
}
pub(super) fn path_bounds(path: &BezPath) -> Result<Option<Rect>> {
if !path.is_finite() {
return Ok(None);
}
let bounds = path.bounding_box();
Ok(Some(Rect::new(
bounds.x0,
bounds.y0,
bounds.width(),
bounds.height(),
)?))
}
fn roots(seg: PathSeg, axis: usize, value: f64) -> impl Iterator<Item = f64> {
let coordinate = |point: Point| if axis == 0 { point.x } else { point.y };
let polynomial = match seg {
PathSeg::Line(line) => {
let a = coordinate(line.p0) - value;
let b = coordinate(line.p1) - value;
[a, b - a, 0., 0.]
}
PathSeg::Quad(quad) => {
let a = coordinate(quad.p0) - value;
let b = coordinate(quad.p1) - value;
let c = coordinate(quad.p2) - value;
[a, 2. * (b - a), a - 2. * b + c, 0.]
}
PathSeg::Cubic(cubic) => {
let a = coordinate(cubic.p0) - value;
let b = coordinate(cubic.p1) - value;
let c = coordinate(cubic.p2) - value;
let d = coordinate(cubic.p3) - value;
[
a,
3. * (b - a),
3. * (a - 2. * b + c),
-a + 3. * b - 3. * c + d,
]
}
};
let [a, b, c, d] = polynomial;
kurbo::common::solve_cubic(a, b, c, d)
.into_iter()
.filter(|t| (0. ..=1.).contains(t))
}
fn segment_pieces(seg: PathSeg, clip: Rect, mut visit: impl FnMut(PathSeg, Point)) {
let [left, top, right, bottom] = edges(clip);
let mut split = Vec::with_capacity(14);
split.extend([0., 1.]);
for (axis, value) in [(0, left), (0, right), (1, top), (1, bottom)] {
split.extend(roots(seg, axis, value));
}
split.sort_by(f64::total_cmp);
split.dedup_by(|a, b| a.to_bits() == b.to_bits());
for interval in split.windows(2) {
let middle = seg.eval(f64::midpoint(interval[0], interval[1]));
if point_in(clip, middle, false) {
visit(seg.subsegment(interval[0]..interval[1]), middle);
}
}
}
pub(super) fn covers_rect(path: &BezPath, rule: FillRule, clip: Rect) -> Result<Option<bool>> {
for (index, seg) in path.segments().enumerate() {
if index.is_multiple_of(64) {
crate::operation::checkpoint()?;
}
let mut crosses = false;
segment_pieces(seg, clip, |_, middle| {
crosses |= point_in(clip, middle, true);
});
if crosses {
return Ok(None);
}
}
let [left, top, right, bottom] = edges(clip);
Ok(Some(rule.contains(
path,
Point::new(f64::midpoint(left, right), f64::midpoint(top, bottom)),
)))
}
fn witness(path: &BezPath, rule: FillRule, axis: usize, value: f64, clip: Rect) -> Result<bool> {
let [left, top, right, bottom] = edges(clip);
let (low, high) = if axis == 0 {
(top, bottom)
} else {
(left, right)
};
let mut events = vec![low, high];
for (index, seg) in path.segments().enumerate() {
if index.is_multiple_of(256) {
crate::operation::check()?;
}
for t in roots(seg, axis, value) {
let point = seg.eval(t);
let other = if axis == 0 { point.y } else { point.x };
if low < other && other < high {
crate::data::source::reserve_source(&mut events, 1)?;
events.push(other);
}
}
}
events.sort_by(f64::total_cmp);
for pair in events.windows(2) {
let middle = f64::midpoint(pair[0], pair[1]);
if middle > pair[0] && middle < pair[1] {
let point = if axis == 0 {
Point::new(value, middle)
} else {
Point::new(middle, value)
};
if rule.contains(path, point) {
return Ok(true);
}
}
}
Ok(false)
}
fn proves_extreme(
path: &BezPath,
rule: FillRule,
axis: usize,
edge: f64,
opposite: f64,
clip: Rect,
precision: Precision,
) -> Result<bool> {
let low = edge < opposite;
if precision == Precision::Continuous {
let probe = if low {
edge.next_up()
} else {
edge.next_down()
};
if !(edge.min(opposite) < probe && probe < edge.max(opposite)) {
return Ok(false);
}
return witness(path, rule, axis, probe, clip);
}
let quantum = if low {
((edge * 1024.).floor() + 1.) / 1024.
} else {
((edge * 1024.).ceil() - 1.) / 1024.
};
let boundary = if low {
quantum.min(opposite)
} else {
quantum.max(opposite)
};
let mut probe = f64::midpoint(edge, boundary);
while probe > edge.min(boundary) && probe < edge.max(boundary) {
crate::operation::check()?;
if witness(path, rule, axis, probe, clip)? {
return Ok(true);
}
let next = f64::midpoint(edge, probe);
if next.to_bits() == probe.to_bits() {
break;
}
probe = next;
}
Ok(false)
}
type ExactPoint = [num_bigint::BigInt; 2];
fn exact(point: Point) -> Result<ExactPoint> {
use crate::numeric::binary::units;
Ok([units(point.x)?, units(point.y)?])
}
fn difference(left: &ExactPoint, right: &ExactPoint) -> ExactPoint {
[&left[0] - &right[0], &left[1] - &right[1]]
}
fn cross(left: &ExactPoint, right: &ExactPoint) -> num_bigint::BigInt {
&left[0] * &right[1] - &left[1] * &right[0]
}
enum Locus {
Line {
origin: ExactPoint,
direction: ExactPoint,
},
Parabola {
origin: ExactPoint,
quadratic: ExactPoint,
linear: ExactPoint,
determinant: num_bigint::BigInt,
},
}
impl Locus {
fn new(segment: PathSeg) -> Result<Option<Self>> {
Ok(match segment {
PathSeg::Line(line) if line.p0 != line.p1 => {
let origin = exact(line.p0)?;
let direction = difference(&exact(line.p1)?, &origin);
Some(Self::Line { origin, direction })
}
PathSeg::Quad(quad) => {
let origin = exact(quad.p0)?;
let middle = exact(quad.p1)?;
let end = exact(quad.p2)?;
let linear = difference(&middle, &origin).map(|value| value * 2);
let quadratic =
difference(&difference(&end, &middle), &difference(&middle, &origin));
let determinant = cross(&quadratic, &linear);
(determinant.sign() != num_bigint::Sign::NoSign).then_some(Self::Parabola {
origin,
quadratic,
linear,
determinant,
})
}
_ => None,
})
}
fn contains(&self, point: &ExactPoint, denominator: u32) -> bool {
match self {
Self::Line { origin, direction } => {
let delta = difference(point, &origin.clone().map(|value| value * denominator));
cross(&delta, direction).sign() == num_bigint::Sign::NoSign
}
Self::Parabola {
origin,
quadratic,
linear,
determinant,
} => {
let delta = difference(point, &origin.clone().map(|value| value * denominator));
let parameter = cross(quadratic, &delta);
determinant * cross(&delta, linear) * denominator == ¶meter * ¶meter
}
}
}
fn distinct(&self, other: PathSeg) -> Result<bool> {
for point in [other.start(), other.end()] {
if !self.contains(&exact(point)?, 1) {
return Ok(true);
}
}
let (points, weights, denominator) = match other {
PathSeg::Line(line) => ([line.p0, line.p1, line.p1, line.p1], [1, 1, 0, 0], 2),
PathSeg::Quad(quad) => ([quad.p0, quad.p1, quad.p2, quad.p2], [1, 2, 1, 0], 4),
PathSeg::Cubic(cubic) => ([cubic.p0, cubic.p1, cubic.p2, cubic.p3], [1, 3, 3, 1], 8),
};
let mut sum = ExactPoint::default();
for (point, weight) in points.into_iter().zip(weights) {
let [x, y] = exact(point)?;
sum[0] += x * weight;
sum[1] += y * weight;
}
Ok(!self.contains(&sum, denominator))
}
}
fn control_bounds(segment: PathSeg) -> kurbo::Rect {
let mut bounds = kurbo::Rect::from_points(segment.start(), segment.end());
match segment {
PathSeg::Line(_) => {}
PathSeg::Quad(quad) => bounds = bounds.union_pt(quad.p1),
PathSeg::Cubic(cubic) => bounds = bounds.union_pt(cubic.p1).union_pt(cubic.p2),
}
bounds
}
fn may_coincide(first: kurbo::Rect, second: kurbo::Rect) -> bool {
(first.width() == 0. || (first.x0.max(second.x0) < first.x1.min(second.x1)))
&& (first.height() == 0. || (first.y0.max(second.y0) < first.y1.min(second.y1)))
}
fn unique_boundary(path: &BezPath, index: usize, segment: PathSeg) -> Result<bool> {
let Some(locus) = Locus::new(segment)? else {
return Ok(false);
};
let bounds = control_bounds(segment);
for (other_index, other) in path.segments().enumerate() {
if index == other_index || !may_coincide(bounds, control_bounds(other)) {
continue;
}
crate::operation::check()?;
if !locus.distinct(other)? {
return Ok(false);
}
}
Ok(true)
}
fn supported_extreme(
path: &BezPath,
axis: usize,
edge: f64,
low: bool,
clip: Rect,
) -> Result<bool> {
for (index, segment) in path.segments().enumerate() {
let mut reaches = false;
segment_pieces(segment, clip, |part, middle| {
if !point_in(clip, middle, true) {
return;
}
let bounds = ParamCurveExtrema::bounding_box(&part);
let extreme = match (axis, low) {
(0, true) => bounds.x0,
(0, false) => bounds.x1,
(_, true) => bounds.y0,
(_, false) => bounds.y1,
};
reaches |= extreme.to_bits() == edge.to_bits();
});
if reaches && unique_boundary(path, index, segment)? {
return Ok(true);
}
}
Ok(false)
}
pub(super) fn filled_path(
path: &BezPath,
rule: FillRule,
clip: Rect,
precision: Precision,
) -> Result<InkExtent> {
let Some(bounds) = path_bounds(path)? else {
return Ok(InkExtent::Unknown);
};
let Some(possible) = bounds.intersection(clip) else {
return Ok(InkExtent::Empty);
};
if let Some(full) = covers_rect(path, rule, clip)? {
return Ok(if full {
InkExtent::Bounds(clip)
} else {
InkExtent::Empty
});
}
let mut candidates = Bounds::default();
for (index, seg) in path.segments().enumerate() {
if index.is_multiple_of(64) {
crate::operation::checkpoint()?;
}
segment_pieces(seg, clip, |part, _| {
candidates.rect(ParamCurveExtrema::bounding_box(&part));
});
}
for corner in corners(clip) {
if rule.contains(path, corner) {
candidates.point(corner);
}
}
let InkExtent::Bounds(candidate) = candidates.extent()? else {
return Ok(InkExtent::Unknown);
};
let Some(candidate) = candidate.intersection(possible) else {
return Ok(InkExtent::Empty);
};
let [left, top, right, bottom] = edges(candidate);
for (axis, edge, opposite) in [
(0, left, right),
(0, right, left),
(1, top, bottom),
(1, bottom, top),
] {
if !proves_extreme(path, rule, axis, edge, opposite, clip, precision)?
&& !supported_extreme(path, axis, edge, edge < opposite, clip)?
{
return Ok(InkExtent::Unknown);
}
}
Ok(InkExtent::Bounds(candidate))
}
pub(super) fn convex_polygon(points: &[Point], transform: Affine, clip: Rect) -> Result<InkExtent> {
let mut polygon: Vec<_> = points.iter().map(|point| transform * *point).collect();
let [left, top, right, bottom] = edges(clip);
for (axis, value, lower) in [
(0, left, true),
(0, right, false),
(1, top, true),
(1, bottom, false),
] {
let coord = |point: Point| if axis == 0 { point.x } else { point.y };
let inside = |point: Point| {
if lower {
coord(point) >= value
} else {
coord(point) <= value
}
};
let mut clipped = Vec::new();
crate::data::source::reserve_source(&mut clipped, polygon.len() + 2)?;
if polygon.is_empty() {
return Ok(InkExtent::Empty);
}
let mut previous = *polygon.last().expect("nonempty polygon");
for ¤t in &polygon {
if inside(previous) != inside(current) {
let t = (value - coord(previous)) / (coord(current) - coord(previous));
clipped.push(previous + (current - previous) * t);
}
if inside(current) {
clipped.push(current);
}
previous = current;
}
polygon = clipped;
}
if polygon.len() < 3 {
return Ok(InkExtent::Empty);
}
let origin = polygon[0];
let area: f64 = polygon[1..]
.windows(2)
.map(|pair| (pair[0] - origin).cross(pair[1] - origin))
.sum();
if area == 0. {
return Ok(InkExtent::Empty);
}
let mut bounds = Bounds::default();
for point in polygon {
bounds.point(point);
}
bounds.extent()
}
pub(super) fn rectangle(rect: Rect, transform: Affine, clip: Rect) -> Result<InkExtent> {
convex_polygon(&corners(rect), transform, clip)
}
#[derive(Clone, Copy)]
struct Ellipse {
center: Point,
u: Vec2,
v: Vec2,
}
impl Ellipse {
fn new(center: Point, rx: f64, ry: f64, transform: Affine) -> Self {
let [a, b, c, d, _, _] = transform.as_coeffs();
Self {
center: transform * center,
u: Vec2::new(a * rx, b * rx),
v: Vec2::new(c * ry, d * ry),
}
}
fn point(self, angle: f64) -> Point {
let (sin, cos) = angle.sin_cos();
self.center + self.u * cos + self.v * sin
}
fn contains(self, point: Point) -> bool {
let det = self.u.cross(self.v);
if det == 0. {
return false;
}
let delta = point - self.center;
let a = delta.cross(self.v) / det;
let b = self.u.cross(delta) / det;
a.hypot(b) <= 1.
}
fn boundary(self, clip: Rect, bounds: &mut Bounds) {
use std::f64::consts::{PI, TAU};
let [left, top, right, bottom] = edges(clip);
let mut events = vec![0., TAU];
for (center, u, v, low, high) in [
(self.center.x, self.u.x, self.v.x, left, right),
(self.center.y, self.u.y, self.v.y, top, bottom),
] {
let radius = u.hypot(v);
if radius == 0. {
continue;
}
let phase = v.atan2(u);
events.extend([phase.rem_euclid(TAU), (phase + PI).rem_euclid(TAU)]);
for side in [low, high] {
let ratio = (side - center) / radius;
if (-1. ..=1.).contains(&ratio) {
let angle = ratio.acos();
events.extend([
(phase - angle).rem_euclid(TAU),
(phase + angle).rem_euclid(TAU),
]);
}
}
}
events.sort_by(f64::total_cmp);
events.dedup_by(|a, b| a.to_bits() == b.to_bits());
for angles in events.windows(2) {
if point_in(clip, self.point(f64::midpoint(angles[0], angles[1])), true) {
bounds.point(self.point(angles[0]));
bounds.point(self.point(angles[1]));
}
}
}
}
pub(super) fn ellipse_band(
center: Point,
radii: (f64, f64),
inner: Option<(f64, f64)>,
transform: Affine,
clip: Rect,
) -> Result<InkExtent> {
if radii.0 <= 0. || radii.1 <= 0. {
return Ok(InkExtent::Empty);
}
let outer = Ellipse::new(center, radii.0, radii.1, transform);
let inner = inner
.filter(|(rx, ry)| *rx > 0. && *ry > 0.)
.map(|(rx, ry)| Ellipse::new(center, rx, ry, transform));
let mut bounds = Bounds::default();
outer.boundary(clip, &mut bounds);
if let Some(inner) = inner {
inner.boundary(clip, &mut bounds);
}
for corner in corners(clip) {
if outer.contains(corner) && inner.is_none_or(|inner| !inner.contains(corner)) {
bounds.point(corner);
}
}
Ok(bounds.extent()?.clipped(clip))
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Cap {
Butt,
Round,
Square,
}
#[derive(Clone, Copy, PartialEq)]
pub(super) enum Join {
Miter(f64),
Round,
Bevel,
}
pub(super) struct Pen {
pub(super) radius: f64,
pub(super) cap: Cap,
pub(super) join: Join,
pub(super) dash: Vec<f64>,
}
fn disk(center: Point, radius: f64, transform: Affine, clip: Rect) -> Result<InkExtent> {
ellipse_band(center, (radius, radius), None, transform, clip)
}
fn segment_body(
start: Point,
end: Point,
radius: f64,
cap: Cap,
transform: Affine,
clip: Rect,
) -> Result<InkExtent> {
let delta = end - start;
let length = delta.hypot();
if length == 0. {
return if cap == Cap::Round {
disk(start, radius, transform, clip)
} else {
Ok(InkExtent::Empty)
};
}
let direction = delta / length;
let normal = Vec2::new(-direction.y, direction.x) * radius;
let extension = if cap == Cap::Square {
direction * radius
} else {
Vec2::ZERO
};
let mut ink = convex_polygon(
&[
start - extension + normal,
end + extension + normal,
end + extension - normal,
start - extension - normal,
],
transform,
clip,
)?;
if cap == Cap::Round {
ink = ink
.union(disk(start, radius, transform, clip)?)
.union(disk(end, radius, transform, clip)?);
}
Ok(ink)
}
fn join(
before: Point,
vertex: Point,
after: Point,
pen: &Pen,
transform: Affine,
clip: Rect,
) -> Result<InkExtent> {
if pen.join == Join::Round {
return disk(vertex, pen.radius, transform, clip);
}
let first = vertex - before;
let second = after - vertex;
let (l1, l2) = (first.hypot(), second.hypot());
if l1 == 0. || l2 == 0. {
return Ok(InkExtent::Empty);
}
let (first, second) = (first / l1, second / l2);
let cross = first.cross(second);
if cross == 0. {
return Ok(InkExtent::Empty);
}
let sign = -cross.signum() * pen.radius;
let outer_first = vertex + Vec2::new(-first.y, first.x) * sign;
let outer_second = vertex + Vec2::new(-second.y, second.x) * sign;
if let Join::Miter(limit) = pen.join {
let apex = outer_first + first * ((outer_second - outer_first).cross(second) / cross);
if (apex - vertex).hypot() <= limit * pen.radius {
return convex_polygon(&[vertex, outer_first, apex, outer_second], transform, clip);
}
}
convex_polygon(&[vertex, outer_first, outer_second], transform, clip)
}
fn dashed_stroke(
points: &[Point],
closed: bool,
pen: &Pen,
transform: Affine,
clip: Rect,
) -> Result<InkExtent> {
let mut ink = InkExtent::Empty;
if closed {
return Ok(InkExtent::Unknown);
}
if pen.cap != Cap::Round || pen.join != Join::Round {
return Ok(InkExtent::Unknown);
}
let mut dash_index = 0;
let mut left = pen.dash[0];
for pair in points.windows(2) {
let delta = pair[1] - pair[0];
let length = delta.hypot();
let mut distance = 0.;
while distance < length {
crate::operation::check()?;
let step = left.min(length - distance);
let end = distance + step;
if end <= distance {
return Ok(InkExtent::Unknown);
}
if dash_index % 2 == 0 {
ink = ink.union(segment_body(
pair[0] + delta * (distance / length),
pair[0] + delta * (end / length),
pen.radius,
Cap::Round,
transform,
clip,
)?);
}
distance = end;
left -= step;
if left <= 0. {
dash_index = (dash_index + 1) % pen.dash.len();
left = pen.dash[dash_index];
}
}
}
Ok(ink)
}
pub(super) fn linear_stroke(
points: &[Point],
closed: bool,
pen: &Pen,
transform: Affine,
clip: Rect,
) -> Result<InkExtent> {
let mut ink = InkExtent::Empty;
if points.len() < 2 || pen.radius <= 0. {
return Ok(ink);
}
let mut distinct = std::borrow::Cow::Borrowed(points);
if points.windows(2).any(|pair| pair[0] == pair[1]) {
distinct.to_mut().dedup();
}
let points = distinct.as_ref();
if points.len() == 1 {
if closed {
return Ok(InkExtent::Unknown);
}
return match pen.cap {
Cap::Butt => Ok(InkExtent::Empty),
Cap::Round => disk(points[0], pen.radius, transform, clip),
Cap::Square => {
let point = points[0];
rectangle(
Rect::new(
point.x - pen.radius,
point.y - pen.radius,
2. * pen.radius,
2. * pen.radius,
)?,
transform,
clip,
)
}
};
}
if !pen.dash.is_empty() {
return dashed_stroke(points, closed, pen, transform, clip);
}
if pen.join == Join::Round && pen.cap != Cap::Round && !closed && points.len() > 2 {
return Ok(InkExtent::Unknown);
}
let pairs = points.windows(2);
for pair in pairs {
crate::operation::check()?;
ink = ink.union(segment_body(
pair[0],
pair[1],
pen.radius,
Cap::Butt,
transform,
clip,
)?);
}
for triple in points.windows(3) {
ink = ink.union(join(triple[0], triple[1], triple[2], pen, transform, clip)?);
}
let first = points[0];
let last = *points.last().expect("nonempty path");
if closed {
if last != first {
ink = ink.union(segment_body(
last,
first,
pen.radius,
Cap::Butt,
transform,
clip,
)?);
ink = ink.union(join(
points[points.len() - 2],
last,
first,
pen,
transform,
clip,
)?);
}
let previous = if last == first {
points[points.len() - 2]
} else {
last
};
ink = ink.union(join(previous, first, points[1], pen, transform, clip)?);
} else if pen.cap == Cap::Round {
ink = ink
.union(disk(first, pen.radius, transform, clip)?)
.union(disk(last, pen.radius, transform, clip)?);
} else if pen.cap == Cap::Square {
for (point, other) in [(first, points[1]), (last, points[points.len() - 2])] {
let direction = point - other;
if direction.hypot() > 0. {
ink = ink.union(segment_body(
point,
point + direction / direction.hypot() * pen.radius,
pen.radius,
Cap::Butt,
transform,
clip,
)?);
}
}
}
Ok(ink)
}
pub(super) fn rounded_rectangle(
rect: Rect,
radius: f64,
fill: bool,
pen: Option<&Pen>,
transform: Affine,
clip: Rect,
) -> Result<InkExtent> {
let [scale_x, skew_y, skew_x, scale_y, _, _] = transform.as_coeffs();
if skew_y != 0. || skew_x != 0. || scale_x == 0. || scale_y == 0. {
return Ok(InkExtent::Unknown);
}
if pen.is_some_and(|pen| !pen.dash.is_empty()) {
return Ok(InkExtent::Unknown);
}
let [left, top, right, bottom] = edges(rect);
let x0 = left + radius;
let x1 = right - radius;
let y0 = top + radius;
let y1 = bottom - radius;
let mut ink = InkExtent::Empty;
let half_width = pen.map_or(0., |pen| pen.radius);
let mut band = |l: f64, t: f64, r: f64, b: f64| -> Result<()> {
if r > l && b > t {
ink = ink.union(rectangle(Rect::new(l, t, r - l, b - t)?, transform, clip)?);
}
Ok(())
};
if fill {
band(x0, top - half_width, x1, bottom + half_width)?;
band(left - half_width, y0, right + half_width, y1)?;
} else {
band(x0, top - half_width, x1, top + half_width)?;
band(x0, bottom - half_width, x1, bottom + half_width)?;
band(left - half_width, y0, left + half_width, y1)?;
band(right - half_width, y0, right + half_width, y1)?;
}
let outer = radius + half_width;
let inner = (!fill).then_some((radius - half_width, radius - half_width));
for (x, y, sx, sy) in [
(x0, y0, -1., -1.),
(x1, y0, 1., -1.),
(x0, y1, -1., 1.),
(x1, y1, 1., 1.),
] {
let center = Point::new(x, y);
let opposite = center + Vec2::new(sx * outer, sy * outer);
let a = transform * center;
let b = transform * opposite;
let quadrant = Rect::new(
a.x.min(b.x),
a.y.min(b.y),
(a.x - b.x).abs(),
(a.y - b.y).abs(),
)?;
if let Some(clip) = clip.intersection(quadrant) {
ink = ink.union(ellipse_band(
center,
(outer, outer),
inner,
transform,
clip,
)?);
}
}
Ok(ink)
}