Width profiles: judge a segment's samples by its own flattened points

Whether a profile segment can reuse the flattened path's points was decided
from the whole subpath's point density, so a long straight run beside a
densely flattened curve counted points it did not have: the run drew its
width as one straight chord across the segment. Compare the width curve
with the points inside the segment instead, and keep reusing them where
they already follow it.

Reported in review of #8846. A 200 pt line whose second half is 128
collinear pieces now draws the same lens outline as the two-segment line
(1167.2 pt² against 1168.3 pt²), where the density shortcut left it at
1000.6 pt².
This commit is contained in:
adambelis
2026-11-20 20:05:23 +01:00
parent cd3dda3f2a
commit b333a0b23e
2 changed files with 83 additions and 30 deletions
+82 -29
View File
@@ -53,7 +53,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil
kept.push(!(a.x.max(b.x) < near.x0 || a.x.min(b.x) > near.x1 || a.y.max(b.y) < near.y0 || a.y.min(b.y) > near.y1));
}
if kept.iter().all(|v| *v) {
ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0), count as f64);
ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0));
continue;
}
cut = true;
@@ -78,14 +78,14 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil
} else if let Some(part) = run.take()
&& part.pts.len() > 1
{
ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64);
ctx.subpath(&mut out, &part, &segs, false, (from, walked / total));
}
walked += lengths[i];
}
if let Some(part) = run
&& part.pts.len() > 1
{
ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64);
ctx.subpath(&mut out, &part, &segs, false, (from, walked / total));
}
}
cut.then_some(out)
@@ -102,8 +102,7 @@ pub(super) fn outline_spans(bp: &BezPath, spans: &[(f64, f64)], width: f64, prof
let flat = flatten(&segs, closed, ctx.tol);
if flat.pts.len() > 1 {
let span = spans.get(i).copied().unwrap_or((0.0, 1.0));
let pieces = if closed { flat.pts.len() } else { flat.pts.len() - 1 }.max(1);
ctx.subpath(&mut out, &flat, &segs, closed, span, pieces as f64 / (span.1 - span.0));
ctx.subpath(&mut out, &flat, &segs, closed, span);
}
}
out
@@ -218,15 +217,7 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> Flat {
/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]); `bend` is
/// the gap (in width factor) the straight line between samples may leave the curve, the outline
/// tolerance turned into the profile's units (see [`adaptive_samples`]).
fn densify(
flat: &Flat,
segs: &[PathSeg],
closed: bool,
profile: &WidthProfile,
span: (f64, f64),
density: f64,
bend: f64,
) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) {
fn densify(flat: &Flat, segs: &[PathSeg], closed: bool, profile: &WidthProfile, span: (f64, f64), bend: f64) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) {
// Start at a midpoint per profile segment: the fit through those keeps a gentle taper smooth
// with little path data. A stronger bend measures itself finer (see `adaptive_samples`): the
// straight line between samples must stay within the outline tolerance, as a plain stroke's
@@ -250,6 +241,15 @@ fn densify(
// piece the profile's own points are enough; a straight run has only its ends, so it needs
// the extra samples. This keeps curved, profiled art close to a uniform stroke's size.
let mut marks = Vec::with_capacity(ts.len() * SAMPLES);
// Where each flattened point falls on the profile, so a segment can see the points inside it.
let mut at = Vec::with_capacity(flat.pts.len());
let mut walked = 0.0;
for (i, p) in flat.pts.iter().enumerate() {
at.push(span.0 + walked / total * range);
if let Some(next) = flat.pts.get(i + 1) {
walked += p.distance(*next);
}
}
for w in ts.windows(2) {
let (a, b) = (w[0], w[1]);
let samples = if constant {
@@ -260,11 +260,10 @@ fn densify(
let start = a.rem_euclid(1.0);
let end = start + (b - a);
let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, bend).min(cap);
// How many of the flattened path's points already fall in this profile segment.
// `density` is measured on the whole subpath, not on this piece, so outlining only
// the piece near the view picks the same samples as outlining the whole subpath.
let existing = (b - a) * density;
if existing >= want as f64 { 1 } else { want }
// Judge the flattened points inside this profile segment, not the subpath's overall
// density: a long straight run beside a densely flattened curve has few points of its
// own, and only they can tell whether the run already follows the width curve.
if sampled_enough(profile, &at, a, b, bend) { 1 } else { want }
};
for k in 0..samples {
marks.push(a + (b - a) * k as f64 / samples as f64);
@@ -286,14 +285,8 @@ fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max:
// One probe in the middle of each piece: how far the curve leaves the straight line
// between the piece's ends. The more pieces, the closer the line follows the curve, so
// the loop only stops when the pieces it has are fine enough (or at `max`).
let mut dev = 0.0_f64;
for k in 0..samples {
let (a, b) = (k as f64 / samples as f64, (k + 1) as f64 / samples as f64);
let (la, ra) = profile.at(t0 + (t1 - t0) * a);
let (lb, rb) = profile.at(t0 + (t1 - t0) * b);
let (lm, rm) = profile.at(t0 + (t1 - t0) * (a + b) / 2.0);
dev = dev.max((lm - (la + lb) / 2.0).abs()).max((rm - (ra + rb) / 2.0).abs());
}
let step = (t1 - t0) / samples as f64;
let dev = (0..samples).fold(0.0_f64, |dev, k| dev.max(deviation(profile, t0 + step * k as f64, t0 + step * (k + 1) as f64)));
if dev <= bend {
break;
}
@@ -302,6 +295,36 @@ fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max:
samples
}
/// How far the width curve leaves the straight line between two profile positions: the widest of
/// its two sides at the span's middle.
fn deviation(profile: &WidthProfile, t0: f64, t1: f64) -> f64 {
let (la, ra) = profile.at(t0);
let (lb, rb) = profile.at(t1);
let (lm, rm) = profile.at((t0 + t1) / 2.0);
(lm - (la + lb) / 2.0).abs().max((rm - (ra + rb) / 2.0).abs())
}
/// Whether the flattened points inside profile segment `[a, b]` already follow the width curve to
/// within `bend`, so the segment needs no samples of its own. `at` holds each flattened point's
/// profile position. The subpath's overall point density cannot answer this: a long straight run
/// beside a densely flattened curve has few points of its own, and its width must still follow the
/// curve rather than run straight between its ends.
fn sampled_enough(profile: &WidthProfile, at: &[f64], a: f64, b: f64, bend: f64) -> bool {
let first = at.partition_point(|p| *p < a);
let last = at.partition_point(|p| *p <= b);
let mut from = a;
for &p in &at[first..last] {
if p <= from {
continue;
}
if deviation(profile, from, p) > bend {
return false;
}
from = p;
}
deviation(profile, from, b) <= bend
}
/// Length of a flattened subpath (see [`flatten`]).
pub(super) fn length(pts: &[Point], closed: bool) -> f64 {
let n = pts.len();
@@ -420,11 +443,11 @@ impl<'a> Ctx<'a> {
}
}
fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64), density: f64) {
fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64)) {
// The flattened edge and its cubic fit are already within `tol`, so a width bend that
// strays further would show as a dent or a bulge that the plain stroke does not have.
let bend = self.tol.max(1e-9) / self.half.max(1e-12);
let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, density, bend);
let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, bend);
let n = pts.len();
let seg_count = if closed { n } else { n - 1 };
let seg_dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect();
@@ -1106,6 +1129,36 @@ mod tests {
assert!((a - want).abs() / want < 0.01, "{a} vs {want}");
}
/// A long straight run beside a densely flattened curve still follows the profile across the
/// run: the subpath's overall point count must not stand in for the points the run itself has.
#[test]
fn a_long_run_beside_a_dense_curve_keeps_the_profiles_shape() {
// One 200 pt line whose second half is 128 collinear pieces: the same geometry as the
// two-segment line, with most of the flattened points on the second half. The lens peaks
// at the join, so a straight chord across either half would sit at 2.5 pt half way along
// it rather than the 3.125 the profile has there.
let mut dense = BezPath::new();
dense.move_to((0.0, 0.0));
for i in 1..=128 {
dense.line_to((100.0 + 100.0 * i as f64 / 128.0, 0.0));
}
let mut sparse = BezPath::new();
sparse.move_to((0.0, 0.0));
sparse.line_to((200.0, 0.0));
let p = WidthProfile::lens();
let dense = width_outline(&dense, 10.0, &p, &capped(LineCap::Butt), 0.01);
let sparse = width_outline(&sparse, 10.0, &p, &capped(LineCap::Butt), 0.01);
// The extra collinear points may not change the outline.
let (a, b) = (area(&dense), area(&sparse));
assert!((a - b).abs() < 2.0, "{a} vs {b}");
assert!((b - 10.0 * 200.0 * 7.0 / 12.0).abs() < 2.0, "{b}");
// ... and the edge at a quarter of the way along each half sits at the lens's width.
for x in [50.0, 150.0] {
assert!(dense.contains(Point::new(x, -3.0)), "{x}: {dense:?}");
assert!(!dense.contains(Point::new(x, -3.4)), "{x}: no extra samples: {dense:?}");
}
}
#[test]
fn profiled_outlines_stay_compact() {
// A smooth profile is fitted with cubics, so it must not turn every profile sample into
+1 -1
View File
@@ -2050,7 +2050,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)).
With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke.
- **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own.
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step.
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and reusing a segment's own flattened points only where they already follow the curve) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step.
- **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web.
Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules.
Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush).