M4, #2731: a vector's lines are placed by what is filled beside them, and trimmed only where they end on the outline

From the review of #2732:
- A segment is on the outline when the fill lies on one side of it, in the fill or outside it
  when on both or neither. The loops alone don't say: a loop inside another that turns the
  same way bounds nothing under the non-zero rule, and was stroked as outline.
- An inside stroke cut every line in the fill by the fill. Now only what shows past the
  outline around a point where such a line ends on it: a line that goes through the fill
  keeps its parts outside, and one close to the edge its whole stroke.
- A segment's middle comes from its own curve, not from a copy of the network.
- The stroke cache's key takes in the segments and the points' places: the loops name
  segments by number, and two networks can have the same path with other numbers.
This commit is contained in:
Livio Sidler committed 2026-11-29 12:34:14 +01:00
1 parent b60e8acdfe
commit 1d18f795d0
3 files changed
+145 -33

No files matched your search

+76 -31
View File
@@ -4,56 +4,70 @@
//! other segments are stroked on their centre at the same weight, so every line of the network
//! reads equally thick.
use figcraft_doc::{Segment, StrokeAlign, StrokeProps, VectorNetwork, WindingRule};
use figcraft_geom::kurbo::{BezPath, ParamCurve as _, Point, Shape as _};
use figcraft_doc::{StrokeAlign, StrokeProps, VectorNetwork, WindingRule};
use figcraft_geom::kurbo::{BezPath, Circle, ParamCurve as _, ParamCurveDeriv as _, Point, Shape as _, Vec2};
/// Where a segment lies relative to the network's fill.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Place {
/// On the fill's outline: in the loops of the regions an odd number of times.
/// On the fill's outline: filled on one side.
Edge,
/// Inside the fill: shared by regions, or a line across one.
/// In the fill: filled on both sides (shared by regions, a line across one, a loop the fill
/// rule doesn't cut out).
Within,
/// Outside the fill.
/// Outside the fill: filled on neither side.
Beyond,
}
/// The stroke of `net` aligned `align` (Inside or Outside) at `props`' weight, or `None` when every
/// segment is on the fill's outline (the plain clip does it).
pub(crate) fn outline(net: &VectorNetwork, props: &StrokeProps, align: StrokeAlign) -> Option<BezPath> {
if loop_uses(net).iter().all(|u| u % 2 == 1) {
let even_odd = net.regions.iter().any(|r| r.winding == WindingRule::EvenOdd);
// Every segment in the loops once: the outline, when the loops say what is filled (one loop,
// or the even-odd rule). Under the non-zero rule a loop inside another may bound nothing.
let by_loops = even_odd || net.regions.iter().map(|r| r.loops.len()).sum::<usize>() <= 1;
if by_loops && loop_uses(net).iter().all(|u| u % 2 == 1) {
return None;
}
// Rounded points are drawn in on the whole network: a part of it would round other points.
let rounded = net.rounded();
let net = rounded.as_ref().unwrap_or(net);
let uses = loop_uses(net);
let fill = net.fill_path();
let even_odd = net.regions.iter().any(|r| r.winding == WindingRule::EvenOdd);
let filled = |p: Point| {
let w = fill.winding(p);
if even_odd { w % 2 != 0 } else { w != 0 }
};
// A segment is placed by what is filled beside its middle, a little way off to either side:
// the loops alone don't say (a loop inside another of the same direction bounds nothing).
let bounds = fill.bounding_box();
let off = (bounds.width().max(bounds.height()) * 1e-5).max(1e-9);
let places: Vec<Place> = (0..net.segments.len())
.map(|i| {
let Some(c) = net.cubic(i) else { return Place::Beyond };
let (at, mut along) = (c.eval(0.5), c.deriv().eval(0.5).to_vec2());
if along.hypot2() == 0.0 {
along = c.p3 - c.p0;
}
let side = Vec2::new(-along.y, along.x).normalize() * off;
if !side.is_finite() {
return if filled(at) { Place::Within } else { Place::Beyond };
}
match (filled(at + side), filled(at - side)) {
(true, true) => Place::Within,
(false, false) => Place::Beyond,
_ => Place::Edge,
}
})
.collect();
if places.iter().all(|p| *p == Place::Edge) {
return None;
}
let part = |keep: &dyn Fn(Place) -> bool| -> VectorNetwork {
let mut vertices = net.vertices.clone();
for v in &mut vertices {
v.radius = 0.0;
}
let segments = net
.segments
.iter()
.zip(&uses)
.filter(|(s, u)| {
let place = match **u {
0 if middle(net, s).is_some_and(filled) => Place::Within,
0 => Place::Beyond,
u if u % 2 == 1 => Place::Edge,
_ => Place::Within,
};
keep(place)
})
.map(|(s, _)| *s)
.collect();
let segments = net.segments.iter().zip(&places).filter(|(_, p)| keep(**p)).map(|(s, _)| *s).collect();
VectorNetwork { vertices, segments, regions: Vec::new() }
};
let w = props.weight;
@@ -66,9 +80,46 @@ pub(crate) fn outline(net: &VectorNetwork, props: &StrokeProps, align: StrokeAli
};
let op = if align == StrokeAlign::Inside { linesweeper::BinaryOp::Intersection } else { linesweeper::BinaryOp::Difference };
let edge = crate::clip(centred(&part(&|p| p == Place::Edge), w * 2.0), &fill, even_odd, op);
// The ends of a line across the fill meet the outline: an inside stroke must not show past it.
let lines = if align == StrokeAlign::Inside {
let mut lines = crate::clip(centred(&part(&|p| p == Place::Within), w), &fill, even_odd, linesweeper::BinaryOp::Intersection);
let within = centred(&part(&|p| p == Place::Within), w);
// Where a line in the fill ends on the outline, an inside stroke must not show past it.
// Only there: a line may leave the fill further on, or run close to its edge.
let mut on_edge = vec![false; net.vertices.len()];
for (s, _) in net.segments.iter().zip(&places).filter(|(_, p)| **p == Place::Edge) {
for v in [s.a, s.b] {
if let Some(e) = on_edge.get_mut(v) {
*e = true;
}
}
}
// As far as a cap or a mitre reaches from the point.
let reach = w * props.miter_limit.clamp(2.0, 16.0) / 2.0;
let mut ends = BezPath::new();
for (s, _) in net.segments.iter().zip(&places).filter(|(_, p)| **p == Place::Within) {
for v in [s.a, s.b] {
if on_edge.get(v) == Some(&true)
&& let Some(p) = net.vertices.get(v)
{
ends.extend(Circle::new((p.x, p.y), reach).to_path(0.01));
if let Some(e) = on_edge.get_mut(v) {
*e = false;
}
}
}
}
let trimmed = if ends.elements().is_empty() {
Ok(within.clone())
} else {
let past = if even_odd {
crate::simplify(&within).and_then(|s| crate::binary_by(&s, &fill, linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Difference))
} else {
crate::binary(&within, &fill, linesweeper::BinaryOp::Difference)
};
past.and_then(|past| crate::binary(&past, &ends, linesweeper::BinaryOp::Intersection))
.and_then(|past| crate::binary(&within, &past, linesweeper::BinaryOp::Difference))
};
// Should that fail: all of it cut by the fill, as the outline's stroke is.
let mut lines = trimmed.unwrap_or_else(|_| crate::clip(within, &fill, even_odd, linesweeper::BinaryOp::Intersection));
lines.extend(centred(&part(&|p| p == Place::Beyond), w).elements().iter().copied());
lines
} else {
@@ -96,9 +147,3 @@ fn loop_uses(net: &VectorNetwork) -> Vec<usize> {
}
uses
}
/// The middle of segment `s`.
fn middle(net: &VectorNetwork, s: &Segment) -> Option<Point> {
let one = VectorNetwork { vertices: net.vertices.clone(), segments: vec![*s], regions: Vec::new() };
one.stroke_path().segments().next().map(|seg| seg.eval(0.5))
}
+63
View File
@@ -61,3 +61,66 @@ fn a_line_that_leaves_the_fill_is_drawn_with_an_inside_stroke() {
assert!(painted(&area, 130.0, -30.0));
assert!(!painted(&area, 130.0, -26.0));
}
#[test]
fn a_line_ending_on_the_outline_does_not_show_past_it_with_an_inside_stroke() {
// Beside the bottom left corner, where the square end of the line from it would lie.
let area = stroke(&crossed_square(false, false), StrokeAlign::Inside);
assert!(!painted(&area, -0.5, 99.2));
assert!(painted(&area, 3.0, 96.5), "the line starts in the corner");
}
/// The square of 100 with one more line, from `a` to `b`, that is in no loop.
fn square_and_line(a: (f64, f64), b: (f64, f64)) -> VectorNetwork {
let vertices: Vec<Vertex> = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), a, b].iter().map(|(x, y)| Vertex::new(*x, *y)).collect();
let segments = vec![Segment::line(0, 1), Segment::line(1, 2), Segment::line(2, 3), Segment::line(3, 0), Segment::line(4, 5)];
VectorNetwork { vertices, segments, regions: vec![Region { loops: vec![vec![0, 1, 2, 3]], ..Default::default() }] }
}
#[test]
fn a_line_through_the_fill_keeps_its_parts_outside_it() {
for align in [StrokeAlign::Inside, StrokeAlign::Outside] {
let area = stroke(&square_and_line((-20.0, 50.0), (120.0, 50.0)), align);
for x in [-10.0, 50.0, 110.0] {
assert!(painted(&area, x, 51.4), "{align:?}: the line is missing at {x}");
assert!(!painted(&area, x, 53.2), "{align:?}: the line is thicker than its weight at {x}");
}
}
}
#[test]
fn a_line_close_to_the_outline_keeps_its_whole_stroke() {
// One unit inside the top edge, at a weight of 4: a unit of the stroke lies outside the square.
let area = stroke(&square_and_line((20.0, 1.0), (80.0, 1.0)), StrokeAlign::Inside);
assert!(painted(&area, 50.0, -0.5));
assert!(!painted(&area, 50.0, -1.5) && !painted(&area, 10.0, -0.5));
}
#[test]
fn a_loop_the_fill_rule_does_not_cut_out_is_a_line_in_the_fill() {
// Two squares that turn the same way, one in the other: the non-zero rule fills both, so the
// inner one bounds nothing. And a tail, so not every segment is in a loop once.
let at = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), (30.0, 30.0), (70.0, 30.0), (70.0, 70.0), (30.0, 70.0), (160.0, -60.0)];
let vertices: Vec<Vertex> = at.iter().map(|(x, y)| Vertex::new(*x, *y)).collect();
let mut segments: Vec<Segment> =
[(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4)].iter().map(|(a, b)| Segment::line(*a, *b)).collect();
for tail in [false, true] {
if tail {
segments.push(Segment::line(1, 8));
}
let net = VectorNetwork {
vertices: vertices.clone(),
segments: segments.clone(),
regions: vec![Region { loops: vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7]], ..Default::default() }],
};
assert_ne!(net.fill_path().winding(Point::new(50.0, 50.0)), 0, "the inner square is filled");
for align in [StrokeAlign::Inside, StrokeAlign::Outside] {
let area = stroke(&net, align);
// The inner square's top edge, at y = 30.
assert!(painted(&area, 50.0, 28.6) && painted(&area, 50.0, 31.4), "{align:?}, tail {tail}: the inner line is missing");
assert!(!painted(&area, 50.0, 26.8) && !painted(&area, 50.0, 33.2), "{align:?}, tail {tail}: the inner line is too thick");
// The outer square keeps its side.
assert_eq!((painted(&area, 30.0, 2.0), painted(&area, 30.0, -2.0)), (align == StrokeAlign::Inside, align == StrokeAlign::Outside));
}
}
}
+6 -2
View File
@@ -378,12 +378,16 @@ fn cached_stroke_outline(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath>
_ => None,
};
net.is_some_and(|n| n.regions.iter().any(|r| r.winding == figcraft_doc::WindingRule::EvenOdd)).hash(&mut h);
// Which segments are the fill's outline: only those are aligned (the others are stroked on their centre).
// What is filled: only the fill's outline is aligned (other segments are stroked on their
// centre), and the path alone doesn't say which segments the loops' numbers mean.
for r in net.map(|n| n.regions.as_slice()).unwrap_or_default() {
r.loops.hash(&mut h);
}
for s in net.map(|n| n.segments.as_slice()).unwrap_or_default() {
(s.a, s.b, s.ta.0.to_bits(), s.ta.1.to_bits(), s.tb.0.to_bits(), s.tb.1.to_bits()).hash(&mut h);
}
for v in net.map(|n| n.vertices.as_slice()).unwrap_or_default() {
(v.cap.map(|c| c as u8), v.join.map(|j| j as u8)).hash(&mut h);
(v.x.to_bits(), v.y.to_bits(), v.cap.map(|c| c as u8), v.join.map(|j| j as u8)).hash(&mut h);
}
for p in props.profile().map(|p| p.points.as_slice()).unwrap_or_default() {
(p.t.to_bits(), p.scale.to_bits(), p.bias.to_bits()).hash(&mut h);