inlaytrace 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,41 +1,57 @@
1
1
  # inlaytrace
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Painted lines stay through smoothing and clean-up: `boostLines` can mark the pixels it darkens (a `lines` array), `smoothShading` takes a `keep` mask it leaves alone, and the tracer's new `lines` option stops a marked line from being folded into a neighbour as a sliver. A dark outline between two dark areas (trousers against a night background) now keeps them apart.
8
+ - New `boostLines(rgba, width, height, radius?)`: darkens faint painted outlines (thin lines darker than both their sides, found with a black-hat filter) before the palette is picked, so a mouth on a shadowed face or a line between two near-equal colours labels apart from them instead of being lost. Short dark marks are left alone as texture.
9
+ - New `smoothShading(rgba, width, height)`: an edge-preserving (bilateral) filter for painted art, run before picking the palette. Brush and JPEG noise inside a shadow evens out, so the shadow traces as one shape instead of flecks of its two nearest colours, while the edges between colours stay sharp.
10
+
11
+ ### Patch Changes
12
+
13
+ - `centerlineToSvg` escapes the drawing's width and height like every other value it writes.
14
+ - Faster colour labelling: converting colours to OKLab reads linear light from a table instead of a power per channel, which cut a 24-colour trace of an 820 × 1162 painted poster from 20 s to 11 s with the same output.
15
+ - Gradient fills no longer smear one shape into its neighbour on painted art (a face into the hair or shadow beside it): a gradient must stay within 20 RGB levels of the image, and must draw each of the bands it replaces no worse than that band's own colour did.
16
+ - Smaller files with Keep painted outlines: with the tracer's `lines` option, the pieces one painted line labels as (a few dark shades along its length) now join each other instead of each staying a shape, and a marked piece too short to part anything folds into its neighbour like any sliver. 9–15% smaller on a painted film poster, with its outlines kept.
17
+ - Strokes keep sharp corners sharp (a flag's swallowtail no longer comes out rounded), and in outline art a dot drawn on a line's end (a flagpole's knob) stays a shape instead of being lost under the stroke.
18
+
3
19
  ## 0.2.0
4
20
 
5
21
  ### Minor Changes
6
22
 
7
- - d37e56b: `stacked: true` now works for flat art too: shapes come back to front, each whole, with the parts hidden behind other shapes completed (a disc behind a bar traces as a whole disc). Which shape is in front is read from the junctions where two shapes' shared edge ends. Photos (`photo: true`) stack as before.
8
- - b1c2494: Flat outline illustrations (thin coloured outlines on white, pale tinted fills) now trace. Speck clean-up folds a speck into its nearest colour, and no longer dissolves a thin stroke that lossy compression split into two shades of its ink. `peakPalette` takes a new `width` option: given it, pale tints are found by their flatness (new options `minTint`, `minFlat`), and a colour that is only ever an anti-aliased edge is left out. Slivers under 2 px wide fold into a neighbour of nearly the same colour. New option `photo` keeps the old clean-up for photos (specks join the colour they share the most edge with, no sliver pass), which is what a stacked `quantizePalette` trace wants. Binary and centerline modes take `threshold: 'auto'` (Otsu, falling back to 128 on a page with nothing to split). A thin closed shape (a 3 px letter stem) no longer collapses to a line, and the fitter no longer grows spikes on thin letters. On a new outline fixture, Logo went from 13.0% to 2.1% of pixels wrong; the badge, emblems and photos (with `photo`) score the same.
9
- - 1d9df88: New `strokes` option for flat outline art: in palette mode, the colours drawn mostly as thin, long lines are traced down their middle as one stroked path each (`InlayPath.stroke` is the width measured from the ink), with their anti-aliased edges and darker shades joined in, and the shapes either side meet beneath them. Small lettering, short marks and solid shapes stay shapes. `scale` says how far the image was enlarged, so the line widths scale with it. Off by default; output without it is unchanged.
10
-
23
+ - `stacked: true` now works for flat art too: shapes come back to front, each whole, with the parts hidden behind other shapes completed (a disc behind a bar traces as a whole disc). Which shape is in front is read from the junctions where two shapes' shared edge ends. Photos (`photo: true`) stack as before.
24
+ - Flat outline illustrations (thin coloured outlines on white, pale tinted fills) now trace. Speck clean-up folds a speck into its nearest colour, and no longer dissolves a thin stroke that lossy compression split into two shades of its ink. `peakPalette` takes a new `width` option: given it, pale tints are found by their flatness (new options `minTint`, `minFlat`), and a colour that is only ever an anti-aliased edge is left out. Slivers under 2 px wide fold into a neighbour of nearly the same colour. New option `photo` keeps the old clean-up for photos (specks join the colour they share the most edge with, no sliver pass), which is what a stacked `quantizePalette` trace wants. Binary and centerline modes take `threshold: 'auto'` (Otsu, falling back to 128 on a page with nothing to split). A thin closed shape (a 3 px letter stem) no longer collapses to a line, and the fitter no longer grows spikes on thin letters. On a new outline fixture, Logo went from 13.0% to 2.1% of pixels wrong; the badge, emblems and photos (with `photo`) score the same.
25
+ - New `strokes` option for flat outline art: in palette mode, the colours drawn mostly as thin, long lines are traced down their middle as one stroked path each (`InlayPath.stroke` is the width measured from the ink), with their anti-aliased edges and darker shades joined in, and the shapes either side meet beneath them. Small lettering, short marks and solid shapes stay shapes. `scale` says how far the image was enlarged, so the line widths scale with it. Off by default; output without it is unchanged.
26
+
11
27
  `toSvg` and `centerlineToSvg` now escape the attribute values they write, so a palette colour given with a quote in it can't end its attribute.
12
- - 1719316: `peakPalette` finds colours spread over several histogram bins (a photo's red lettering, a small decal) instead of stopping at the greys; flat art's palettes are unchanged. New option `minDetail`. Stacked shapes now reach under the neighbours painted after them, so no hairline seam shows where two shapes meet (12% closer on photos, about a third more path data).
13
- - 2cf20c5: Lines within a degree of horizontal, vertical or 45° are now exactly that, so a square stays square after JPEG and lines either side of a junction line up. `fitChain` takes `snap: false` to keep lines as fitted.
28
+ - `peakPalette` finds colours spread over several histogram bins (a photo's red lettering, a small decal) instead of stopping at the greys; flat art's palettes are unchanged. New option `minDetail`. Stacked shapes now reach under the neighbours painted after them, so no hairline seam shows where two shapes meet (12% closer on photos, about a third more path data).
29
+ - Lines within a degree of horizontal, vertical or 45° are now exactly that, so a square stays square after JPEG and lines either side of a junction line up. `fitChain` takes `snap: false` to keep lines as fitted.
14
30
 
15
31
  ### Patch Changes
16
32
 
17
- - 56f4604: `centerline(rgba, width, height, options)` (and `traceCenterline`, `centerlineToSvg`): single strokes down the middle of the ink, for pen plotters and engraving, with the stroke width measured from the ink or set.
18
- - b7fa938: Add a funding link (Ko-fi) to the package metadata.
19
- - fb90904: New `gradients` option: soft shading that a palette splits into bands of tints is traced as one shape with a linear or radial gradient (`path.gradient`, written by `toSvg` as `<linearGradient>` / `<radialGradient>`), when the gradient fits much better than a flat colour. Off by default.
20
- - e462e9b: Lines about a pixel wide stay in one piece at a slant, instead of breaking into dashes or vanishing.
21
- - 1ff571f: Centerline and outline-art strokes run straight through junctions. Thinning bends the skeleton toward each junction, so an X of thick strokes came out pinched at its crossing and a T's stem bent to meet the bar; within a stroke width of a junction the arms are now cut back and drawn straight on to where their own lines meet.
22
- - 6e9a2d0: Small text and dots beside flat art now trace. Thin anti-aliased strokes (1.5 px grey letters) were labelled as the paper, pale edges as a nearby colour, and each letter then cleared as a speck. In flat art (not `photo`), a pixel between colours and close to none of them is now read as a mix of the pair that explains it best; one next to only one other colour keeps its own; and a speck that stands well apart from every colour around it stays from an eighth of the speck area up, so raising `speckle` still clears it. Poster output is unchanged.
23
- - 3660a64: In images with exactly flat colours, such as most PNG exports, edges are placed between pixels from their anti-aliasing instead of on the pixel grid: straight sides land where they really are, and small shapes come out cleaner (2–16% fewer wrong pixels on the PNG fixtures, for the same nodes). Whether an image qualifies is judged from its pixels, so typical JPEG and WebP traces and Poster are unchanged.
24
- - 62d79d3: `toSvg` escapes the drawing's width and height like every other value it writes.
25
- - 4b20b95: Lines one or two pixels wide keep their width to their ends. Where such a line's outline turned back at its end inside one fitted run (an arm of a T or a Y), its two sides were joined at a point, so each arm tapered to nothing and thin outlines looked broken.
33
+ - `centerline(rgba, width, height, options)` (and `traceCenterline`, `centerlineToSvg`): single strokes down the middle of the ink, for pen plotters and engraving, with the stroke width measured from the ink or set.
34
+ - Add a funding link (Ko-fi) to the package metadata.
35
+ - New `gradients` option: soft shading that a palette splits into bands of tints is traced as one shape with a linear or radial gradient (`path.gradient`, written by `toSvg` as `<linearGradient>` / `<radialGradient>`), when the gradient fits much better than a flat colour. Off by default.
36
+ - Lines about a pixel wide stay in one piece at a slant, instead of breaking into dashes or vanishing.
37
+ - Centerline and outline-art strokes run straight through junctions. Thinning bends the skeleton toward each junction, so an X of thick strokes came out pinched at its crossing and a T's stem bent to meet the bar; within a stroke width of a junction the arms are now cut back and drawn straight on to where their own lines meet.
38
+ - Small text and dots beside flat art now trace. Thin anti-aliased strokes (1.5 px grey letters) were labelled as the paper, pale edges as a nearby colour, and each letter then cleared as a speck. In flat art (not `photo`), a pixel between colours and close to none of them is now read as a mix of the pair that explains it best; one next to only one other colour keeps its own; and a speck that stands well apart from every colour around it stays from an eighth of the speck area up, so raising `speckle` still clears it. Poster output is unchanged.
39
+ - In images with exactly flat colours, such as most PNG exports, edges are placed between pixels from their anti-aliasing instead of on the pixel grid: straight sides land where they really are, and small shapes come out cleaner (2–16% fewer wrong pixels on the PNG fixtures, for the same nodes). Whether an image qualifies is judged from its pixels, so typical JPEG and WebP traces and Poster are unchanged.
40
+ - `toSvg` escapes the drawing's width and height like every other value it writes.
41
+ - Lines one or two pixels wide keep their width to their ends. Where such a line's outline turned back at its end inside one fitted run (an arm of a T or a Y), its two sides were joined at a point, so each arm tapered to nothing and thin outlines looked broken.
26
42
 
27
43
  ## 0.1.3
28
44
 
29
45
  ### Patch Changes
30
46
 
31
- - f71beed: New `shapes` option: a closed outline that is a circle, an ellipse, a rectangle, a rounded rectangle or a regular polygon is drawn as that exact shape instead of fitted curves (on the sample badge, 0.70% → 0.54% wrong pixels). Off by default.
32
- - 074cc75: `detectSymmetry(rgba, width, height, options?)` finds the likeliest mirror axes (vertical and horizontal) and rotational orders (2–8 by default) in an image, each scored by the share of the drawing that matches its reflection or turn.
47
+ - New `shapes` option: a closed outline that is a circle, an ellipse, a rectangle, a rounded rectangle or a regular polygon is drawn as that exact shape instead of fitted curves (on the sample badge, 0.70% → 0.54% wrong pixels). Off by default.
48
+ - `detectSymmetry(rgba, width, height, options?)` finds the likeliest mirror axes (vertical and horizontal) and rotational orders (2–8 by default) in an image, each scored by the share of the drawing that matches its reflection or turn.
33
49
 
34
50
  ## 0.1.2
35
51
 
36
52
  ### Patch Changes
37
53
 
38
- - 679659c: Photos: `quantizePalette(rgba, n)` picks a photo's colours by k-means in OKLab (deterministic), and the `stacked` option draws each shape whole, larger shapes first, instead of cutting holes (same picture, less path data, no hairline seams). Also fixes speck merging, which could strand fragments of merged specks as new specks: on photos that left thousands of extra shapes, and a larger `speckle` gave more shapes rather than fewer.
54
+ - Photos: `quantizePalette(rgba, n)` picks a photo's colours by k-means in OKLab (deterministic), and the `stacked` option draws each shape whole, larger shapes first, instead of cutting holes (same picture, less path data, no hairline seams). Also fixes speck merging, which could strand fragments of merged specks as new specks: on photos that left thousands of extra shapes, and a larger `speckle` gave more shapes rather than fewer.
39
55
 
40
56
  ## 0.1.1
41
57
 
package/dist/index.d.ts CHANGED
@@ -212,6 +212,14 @@ type InlayOptions = FitOptions & {
212
212
  * pixel art. Off by default: a cutter or a plotter can't draw a gradient.
213
213
  */
214
214
  gradients?: boolean;
215
+ /**
216
+ * Painted lines (one entry per pixel, non-zero on a line), as `boostLines`
217
+ * marks them. A region mostly on them is a drawn line, not one ink's two
218
+ * shades, so it folds only into another piece of line: a dark outline
219
+ * between two dark shapes is nearly their colour, and folding it in joined
220
+ * them.
221
+ */
222
+ lines?: ArrayLike<number>;
215
223
  } & (
216
224
  /**
217
225
  * `merge` folds colours together before any region is built, so the edge
@@ -274,6 +282,51 @@ export declare function mergeLabels(labels: Int32Array, colors: string[], merge:
274
282
  /** Otsu's threshold over opaque pixels: the split that best separates two populations. */
275
283
  export declare function otsu(lum: Uint8Array, alpha: Uint8Array): number;
276
284
  //#endregion
285
+ //#region src/smooth.d.ts
286
+ /**
287
+ * Edge-preserving smoothing for painted art, before its palette is picked.
288
+ *
289
+ * A painted poster's skin shadow is a soft ramp with brush and JPEG noise on
290
+ * it. Labelled pixel by pixel, the noise flips each pixel between the two
291
+ * nearest palette colours, and the shadow traces as ragged patches. A
292
+ * bilateral filter averages each pixel with neighbours of a similar colour
293
+ * only, so the noise inside a shadow evens out and the edges between colours
294
+ * (an arm against the dark coat, a line on a face) stay where they are.
295
+ *
296
+ * On a painted film poster traced at 2× in Illustration, this turned the
297
+ * blotchy arm and neck shadows into whole shapes, kept the face lines, and cut
298
+ * the file from 3.3 MB to 2.1 MB; the filter took 4 s of the trace. Stronger
299
+ * (radius 6, three passes at sigma 25) began to wash out lines in the hair.
300
+ */
301
+ /**
302
+ * A smoothed copy of `rgba` (`width` × `height`, RGBA). Transparent pixels, and
303
+ * any marked in `keep` (one entry per pixel, non-zero to keep), are left as
304
+ * they are and never averaged into their neighbours.
305
+ */
306
+ export declare function smoothShading(rgba: ArrayLike<number>, width: number, height: number, keep?: ArrayLike<number>): Uint8ClampedArray;
307
+ /**
308
+ * Painted outlines made plain, before the palette is picked. A painter's line
309
+ * between two near-equal colours (a mouth on a shadowed face, dark trousers
310
+ * against a dark background) is only a few levels darker than either side, so
311
+ * it labels as one of them and is lost. A black-hat filter (the image's
312
+ * closing minus the image, over `radius` px) finds lines up to about twice
313
+ * that wide that are darker than both sides; each is darkened by twice its
314
+ * depth, at most LINE_MAX, colour kept, so it labels apart from both sides.
315
+ * Only lines that run a while are kept: brick, foliage and brush texture are
316
+ * dark too, but short. When `lines` (one entry per pixel) is given, each
317
+ * pixel darkened is marked in it with 1, for `smoothShading`'s `keep` and
318
+ * the tracer's `lines`, which leave them be.
319
+ *
320
+ * On a painted film poster at 2× (radius 3), with smoothing, this brought back
321
+ * the mouth, eyes, brows and jaw lines Illustration lost, and the outline
322
+ * parting dark trousers from a dark background, for twice the paths (2.1 to
323
+ * 3.6 MB). The trousers merged with the background until the lines were marked:
324
+ * the outline was found, but smoothing blurred it back into its sides, and,
325
+ * left unsmoothed, it labelled as the near-black of the trousers, close
326
+ * enough to the dark grey on either side to be folded in as a sliver.
327
+ */
328
+ export declare function boostLines(rgba: ArrayLike<number>, width: number, height: number, radius?: number, lines?: Uint8Array): Uint8ClampedArray;
329
+ //#endregion
277
330
  //#region src/centerline.d.ts
278
331
  type CenterlineOptions = {
279
332
  /** Ink is darker than this (0–255); 'auto' splits ink from paper by the image's histogram (Otsu); null compares each pixel with its neighbourhood instead. */
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  //#region src/shapes.ts
2
2
  /** How closely an outline must follow a shape: RMS and worst distance, in px, of its pixel-edge midpoints. */
3
- const MAX_RMS = .3;
3
+ const MAX_RMS$1 = .3;
4
4
  const MAX_OFF = .85;
5
5
  /** An ellipse whose axes differ by less than this is drawn as a circle. */
6
6
  const ROUND = .015;
@@ -69,7 +69,7 @@ function fits(points, distance) {
69
69
  if (d > MAX_OFF) return false;
70
70
  sum += d * d;
71
71
  }
72
- return Math.sqrt(sum / points.length) <= MAX_RMS;
72
+ return Math.sqrt(sum / points.length) <= MAX_RMS$1;
73
73
  }
74
74
  /** Into a frame centred on (cx, cy) and turned by `angle`. */
75
75
  const local = (p, cx, cy, cos, sin) => {
@@ -1259,10 +1259,6 @@ function isBlend(rgb, lab, picked, tolerance) {
1259
1259
  return false;
1260
1260
  }
1261
1261
  function oklab([r, g, b]) {
1262
- const lin = (c) => {
1263
- c /= 255;
1264
- return c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
1265
- };
1266
1262
  const [lr, lg, lb] = [
1267
1263
  lin(r),
1268
1264
  lin(g),
@@ -1277,6 +1273,24 @@ function oklab([r, g, b]) {
1277
1273
  .0259040371 * l + .7827717662 * m - .808675766 * s
1278
1274
  ];
1279
1275
  }
1276
+ const linear = (c) => {
1277
+ c /= 255;
1278
+ return c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
1279
+ };
1280
+ /**
1281
+ * sRGB to linear light, from a table at 1/16 steps: labelling reads hundreds of
1282
+ * mixes per in-between colour (every pair of a 24-colour palette), and the
1283
+ * power was half its time. Interpolated, it is within 1e-7 of the formula.
1284
+ */
1285
+ const LIN_STEPS = 16;
1286
+ const LIN = Float64Array.from({ length: 4082 }, (_, i) => linear(i / LIN_STEPS));
1287
+ function lin(c) {
1288
+ if (!(c > 0)) return 0;
1289
+ if (c >= 255) return linear(c);
1290
+ const x = c * LIN_STEPS;
1291
+ const i = Math.floor(x);
1292
+ return LIN[i] + (LIN[i + 1] - LIN[i]) * (x - i);
1293
+ }
1280
1294
  /**
1281
1295
  * A photo's palette: `maxColors` colours that best summarise it, by k-means in
1282
1296
  * OKLab (so the clusters are perceptual, not RGB boxes).
@@ -1876,7 +1890,9 @@ function complete(p0, t0, p1, t1, visible, straight0, straight1, hidden) {
1876
1890
  * the skeleton toward each junction, so within a stroke width of one the
1877
1891
  * arms are dropped and drawn straight on to where their own lines meet.
1878
1892
  * Where strokes cross or branch, chains that carry on in the same
1879
- * direction are joined, so a plotter lifts its pen less.
1893
+ * direction are joined, so a plotter lifts its pen less. Thinning also
1894
+ * rounds a sharp corner off, turning inside it, so a corner's arms are
1895
+ * drawn straight on to where they meet.
1880
1896
  * 5. Fit each chain with the same curve fitter as outlines.
1881
1897
  */
1882
1898
  /** The ink's skeleton as fitted subpaths (open, or closed for a loop), and the stroke width measured from the ink. `thinned` is the skeleton, if already thinned; it is pruned in place. */
@@ -1885,7 +1901,7 @@ function skeletonStrokes(ink, w, h, o, thinned) {
1885
1901
  const measured = strokeWidthOf(skel, ink, w);
1886
1902
  prune(skel, w, h, Math.max(3, Math.round(measured)));
1887
1903
  const subs = [];
1888
- for (const c of joinStraight(refitJunctions(walk(skel, w, h), measured))) {
1904
+ for (const c of joinStraight(refitJunctions(walk(skel, w, h), measured)).map((c) => refitCorners(c, measured, ink, w, h))) {
1889
1905
  if (c.pts.length < 2) continue;
1890
1906
  const cubics = c.pts.length < 4 ? polyline(c.pts) : fitChain(c.pts, c.closed, {
1891
1907
  tolerance: o.tolerance,
@@ -2356,6 +2372,111 @@ function refitJunctions(chains, width) {
2356
2372
  };
2357
2373
  });
2358
2374
  }
2375
+ /** A chain turns this much (radians) across a corner before it's redrawn as one: 60°. */
2376
+ const CORNER_TURN = Math.PI / 3;
2377
+ /**
2378
+ * Sharp corners drawn sharp. Thinning a stroke that turns sharply cuts the
2379
+ * corner: the skeleton turns inside it, short of the point by up to a few
2380
+ * stroke widths (a flag's swallowtail comes out rounded). Where the chain's
2381
+ * direction just before a point and just after it (measured outside a stroke
2382
+ * width of it, as at junctions) differs by more than CORNER_TURN, the points
2383
+ * within a stroke width are replaced by where the two arms' lines meet, if
2384
+ * the ink runs on toward that point past where the stroke's edge would be.
2385
+ * A rounded corner or a small ring turns as much, but its ink stops half a
2386
+ * width out, so it keeps its shape.
2387
+ */
2388
+ function refitCorners(c, width, ink, w, h) {
2389
+ const pts = c.pts;
2390
+ const n = pts.length;
2391
+ const cut = Math.max(2, width);
2392
+ const reach = Math.max(6, width);
2393
+ if (n < 4) return c;
2394
+ const s = [0];
2395
+ for (let i = 1; i < n; i++) s.push(s[i - 1] + Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y));
2396
+ const at = (t) => {
2397
+ let lo = 1;
2398
+ let hi = n - 1;
2399
+ while (lo < hi) {
2400
+ const mid = lo + hi >> 1;
2401
+ if (s[mid] < t) lo = mid + 1;
2402
+ else hi = mid;
2403
+ }
2404
+ const j = lo;
2405
+ const f = s[j] > s[j - 1] ? (t - s[j - 1]) / (s[j] - s[j - 1]) : 0;
2406
+ return {
2407
+ x: pts[j - 1].x + f * (pts[j].x - pts[j - 1].x),
2408
+ y: pts[j - 1].y + f * (pts[j].y - pts[j - 1].y)
2409
+ };
2410
+ };
2411
+ const unit = (a, b) => {
2412
+ const l = Math.hypot(b.x - a.x, b.y - a.y) || 1;
2413
+ return {
2414
+ x: (b.x - a.x) / l,
2415
+ y: (b.y - a.y) / l
2416
+ };
2417
+ };
2418
+ const isInk = (p) => {
2419
+ const x = Math.floor(p.x);
2420
+ const y = Math.floor(p.y);
2421
+ return x >= 0 && y >= 0 && x < w && y < h && ink[y * w + x] === 1;
2422
+ };
2423
+ const found = [];
2424
+ for (let i = 1; i < n - 1; i++) {
2425
+ if (s[i] - cut - reach < 0 || s[i] + cut + reach > s[n - 1]) continue;
2426
+ const pa = at(s[i] - cut);
2427
+ const d1 = unit(at(s[i] - cut - reach), pa);
2428
+ const qa = at(s[i] + cut);
2429
+ const d2 = unit(qa, at(s[i] + cut + reach));
2430
+ const turn = Math.acos(Math.max(-1, Math.min(1, d1.x * d2.x + d1.y * d2.y)));
2431
+ if (turn < CORNER_TURN) continue;
2432
+ const det = d1.x * -d2.y - d1.y * -d2.x;
2433
+ if (Math.abs(det) < 1e-6) continue;
2434
+ const u = ((qa.x - pa.x) * -d2.y - (qa.y - pa.y) * -d2.x) / det;
2435
+ if (u < 0) continue;
2436
+ const apex = {
2437
+ x: pa.x + u * d1.x,
2438
+ y: pa.y + u * d1.y
2439
+ };
2440
+ const off = Math.hypot(apex.x - pts[i].x, apex.y - pts[i].y);
2441
+ if (off < .5 || off > 3 * width || !isInk(apex)) continue;
2442
+ const past = width / 2 + 1.5;
2443
+ if (!isInk({
2444
+ x: pts[i].x + (apex.x - pts[i].x) / off * past,
2445
+ y: pts[i].y + (apex.y - pts[i].y) / off * past
2446
+ })) continue;
2447
+ const last = found[found.length - 1];
2448
+ if (last && s[i] - s[last.i] < 2 * cut) {
2449
+ if (turn > last.turn) found[found.length - 1] = {
2450
+ i,
2451
+ turn,
2452
+ apex
2453
+ };
2454
+ } else found.push({
2455
+ i,
2456
+ turn,
2457
+ apex
2458
+ });
2459
+ }
2460
+ if (!found.length) return c;
2461
+ const out = [];
2462
+ let k = 0;
2463
+ for (let i = 0; i < n; i++) {
2464
+ const f = found[k];
2465
+ if (f && s[i] > s[f.i] - cut) {
2466
+ if (s[i] < s[f.i] + cut) continue;
2467
+ out.push(f.apex);
2468
+ k++;
2469
+ i--;
2470
+ continue;
2471
+ }
2472
+ out.push(pts[i]);
2473
+ }
2474
+ for (; k < found.length; k++) out.push(found[k].apex);
2475
+ return {
2476
+ ...c,
2477
+ pts: out
2478
+ };
2479
+ }
2359
2480
  /** The direction a chain leaves its start, measured a few pixels along it. */
2360
2481
  function leaving(pts) {
2361
2482
  const a = pts[0];
@@ -2497,6 +2618,15 @@ const FLAT_MIN = 6;
2497
2618
  const GAIN = .5;
2498
2619
  /** …and come within this of the bands' own error. */
2499
2620
  const BANDS_SLACK = 1.1;
2621
+ /**
2622
+ * …and stay this close to the image (RMS, RGB levels). Soft shading fits to
2623
+ * within noise; a fit this far off is smearing distinct shapes together (a
2624
+ * face and the hair beside it on a painted poster, whose palette is far off
2625
+ * both, so the bands' error is no guide).
2626
+ */
2627
+ const MAX_RMS = 20;
2628
+ /** A band with at least this many sampled pixels must be drawn no worse by the gradient than by its own colour. */
2629
+ const BAND_MIN = 16;
2500
2630
  /** A radial fit replaces the linear one only when this much closer. */
2501
2631
  const RADIAL_GAIN = .8;
2502
2632
  /** Pixels a shade is fitted on, at most. */
@@ -2570,12 +2700,14 @@ function shadings(rgba, w, h, comp, regions, colorOf) {
2570
2700
  const ys = [];
2571
2701
  const cs = [];
2572
2702
  const bands = [];
2703
+ const ids = [];
2573
2704
  for (let k = 0; k < all.length; k += stride) {
2574
2705
  const i = all[k];
2575
2706
  xs.push(i % w + .5);
2576
2707
  ys.push(Math.floor(i / w) + .5);
2577
2708
  cs.push(rgb(i));
2578
2709
  bands.push(colors[comp[i]]);
2710
+ ids.push(comp[i]);
2579
2711
  }
2580
2712
  const g = fitShading(xs, ys, cs);
2581
2713
  if (!g) continue;
@@ -2588,7 +2720,8 @@ function shadings(rgba, w, h, comp, regions, colorOf) {
2588
2720
  const rms = (f) => Math.sqrt(cs.reduce((s, c, j) => s + d3(c, f(j)) ** 2, 0) / n);
2589
2721
  const flat = rms(() => mean);
2590
2722
  const banded = rms((j) => bands[j]);
2591
- if (flat < FLAT_MIN || g.rms > GAIN * flat || g.rms > BANDS_SLACK * banded) continue;
2723
+ if (flat < FLAT_MIN || g.rms > MAX_RMS || g.rms > GAIN * flat || g.rms > BANDS_SLACK * banded) continue;
2724
+ if (worseOnABand(g.gradient, xs, ys, cs, bands, ids)) continue;
2592
2725
  out.push({
2593
2726
  comps: [...groups.get(r)],
2594
2727
  gradient: g.gradient,
@@ -2656,6 +2789,28 @@ function shadings(rgba, w, h, comp, regions, colorOf) {
2656
2789
  }
2657
2790
  /** A gradient's colour at a point. */
2658
2791
  const colorAt = (g, x, y) => ramp(g)(x, y);
2792
+ /**
2793
+ * Whether the gradient draws any one band of the shade worse than the band's
2794
+ * own flat colour did: a gradient that suits the whole on average can still
2795
+ * paint one member (a shirt's fold shadow, a strand of hair) the wrong colour.
2796
+ */
2797
+ function worseOnABand(g, xs, ys, cs, bands, ids) {
2798
+ const at = ramp(g);
2799
+ const err = /* @__PURE__ */ new Map();
2800
+ cs.forEach((c, j) => {
2801
+ const e = err.get(ids[j]) ?? [
2802
+ 0,
2803
+ 0,
2804
+ 0
2805
+ ];
2806
+ e[0] += dist2(c, at(xs[j], ys[j]));
2807
+ e[1] += dist2(c, bands[j]);
2808
+ e[2]++;
2809
+ err.set(ids[j], e);
2810
+ });
2811
+ for (const [grad, band, n] of err.values()) if (n >= BAND_MIN && grad > BANDS_SLACK ** 2 * band) return true;
2812
+ return false;
2813
+ }
2659
2814
  /** A gradient as a function of the point, its stops parsed once. */
2660
2815
  function ramp(g) {
2661
2816
  const offsets = g.stops.map((s) => s.offset);
@@ -3008,7 +3163,7 @@ function trace(rgba, w, h, o) {
3008
3163
  if (!o.pixels && !(o.mode === "palette" && o.photo)) joinDiagonals(labels, w, h, rgba, drawn);
3009
3164
  const labs = o.mode === "palette" && !o.photo ? colors.map((c) => c ? oklab(hexToRgb(c)) : null) : void 0;
3010
3165
  mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2, labs);
3011
- if (labs && !o.pixels) mergeSlivers(labels, w, h, labs);
3166
+ if (labs && !o.pixels) mergeSlivers(labels, w, h, labs, o.lines);
3012
3167
  const lines = o.mode === "palette" && o.strokes && labs && !o.pixels ? strokesOf(rgba, labels, w, h, colors, labs, drawn, o) : [];
3013
3168
  let { comp, compLabel, compArea } = components(labels, w, h, (l) => drawn[l]);
3014
3169
  const gradientOf = /* @__PURE__ */ new Map();
@@ -3944,21 +4099,35 @@ function mergeSpecksOnce(labels, w, h, minArea, labs) {
3944
4099
  const SLIVER_WIDTH = 2;
3945
4100
  /** A sliver joins a neighbour only this close in colour (OKLab): two shades of one ink (0.08–0.11 apart), not a grey hairline on white (#d4d4d4 is 0.13 from it). */
3946
4101
  const SLIVER_DISTANCE = .12;
4102
+ /** A painted line's piece spans this many px (bounding-box diagonal) before it is kept from folding into a shape. */
4103
+ const LINE_PIECE_SPAN = 16;
3947
4104
  /**
3948
4105
  * Fold slivers into a neighbour of nearly the same colour. JPEG and WebP
3949
4106
  * smear a thin stroke into two shades of its ink (a 3 px letter stem came
3950
4107
  * out dark at its edges and lighter down the middle), and a one-pixel strip
3951
4108
  * of one shade inside the other fitted as a spike shooting out of the
3952
4109
  * letter. A hairline of a colour of its own has no neighbour that close, so
3953
- * it stays. Within a pass a sliver waits if a neighbour has already moved,
3954
- * so two side by side don't just swap colours.
4110
+ * it stays. Within a pass a sliver waits if a neighbour has already moved, so
4111
+ * two side by side don't just swap colours.
4112
+ *
4113
+ * A region mostly on a painted line marked in `lines` folds only into another
4114
+ * such region, sliver or not: a dark outline between two dark shapes is
4115
+ * nearly their colour, and folding it in joined them, but one line labels as
4116
+ * several dark shades along its length, and keeping each piece apart cost a
4117
+ * painted film poster a third of its shapes. A line piece shorter than
4118
+ * LINE_PIECE_SPAN is too short to part anything, and folds as any sliver.
3955
4119
  */
3956
- function mergeSlivers(labels, w, h, labs) {
4120
+ function mergeSlivers(labels, w, h, labs, lines) {
3957
4121
  for (let pass = 0; pass < 4; pass++) {
3958
4122
  const { comp, compArea } = components(labels, w, h, () => true);
3959
4123
  const m = compArea.length;
3960
4124
  const perimeter = new Int32Array(m);
3961
4125
  const label = new Int32Array(m);
4126
+ const onLine = new Int32Array(m);
4127
+ const x0 = new Int32Array(m).fill(w);
4128
+ const x1 = new Int32Array(m).fill(-1);
4129
+ const y0 = new Int32Array(m).fill(h);
4130
+ const y1 = new Int32Array(m).fill(-1);
3962
4131
  const around = /* @__PURE__ */ new Map();
3963
4132
  const touch = (a, b) => {
3964
4133
  const id = comp[a];
@@ -3969,23 +4138,40 @@ function mergeSlivers(labels, w, h, labs) {
3969
4138
  };
3970
4139
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
3971
4140
  const i = y * w + x;
3972
- label[comp[i]] = labels[i];
4141
+ const c = comp[i];
4142
+ label[c] = labels[i];
4143
+ if (lines?.[i]) {
4144
+ onLine[c]++;
4145
+ if (x < x0[c]) x0[c] = x;
4146
+ if (x > x1[c]) x1[c] = x;
4147
+ if (y < y0[c]) y0[c] = y;
4148
+ if (y > y1[c]) y1[c] = y;
4149
+ }
3973
4150
  if (x < w - 1 && comp[i + 1] !== comp[i]) touch(i, i + 1), touch(i + 1, i);
3974
4151
  if (y < h - 1 && comp[i + w] !== comp[i]) touch(i, i + w), touch(i + w, i);
3975
4152
  }
3976
4153
  const to = new Int32Array(m).fill(-1);
3977
4154
  let changed = false;
4155
+ const onALine = (id) => 2 * onLine[id] > compArea[id];
3978
4156
  for (const [id, near] of [...around].sort((a, b) => compArea[a[0]] - compArea[b[0]])) {
3979
- if (2 * compArea[id] / perimeter[id] >= SLIVER_WIDTH) continue;
4157
+ const sliver = 2 * compArea[id] / perimeter[id] < SLIVER_WIDTH;
4158
+ const line = onALine(id);
4159
+ if (!sliver && !line) continue;
3980
4160
  const mine = labs[label[id]];
3981
4161
  if (!mine || [...near].some((n) => to[n] >= 0)) continue;
3982
- let best = -1;
3983
- let bd = SLIVER_DISTANCE;
3984
- for (const n of near) {
3985
- const lab = labs[label[n]];
3986
- const d = lab ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : Infinity;
3987
- if (d < bd) bd = d, best = label[n];
3988
- }
4162
+ const nearest = (ok) => {
4163
+ let best = -1;
4164
+ let bd = SLIVER_DISTANCE;
4165
+ for (const n of near) {
4166
+ const lab = labs[label[n]];
4167
+ const d = lab && ok(n) ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : Infinity;
4168
+ if (d < bd) bd = d, best = label[n];
4169
+ }
4170
+ return best;
4171
+ };
4172
+ const sides = new Set([...near].filter((n) => !onALine(n)).map((n) => label[n]));
4173
+ let best = nearest(line ? (n) => onALine(n) && !sides.has(label[n]) : () => true);
4174
+ if (best < 0 && line && sliver && Math.hypot(x1[id] - x0[id], y1[id] - y0[id]) < LINE_PIECE_SPAN) best = nearest(() => true);
3989
4175
  if (best < 0) continue;
3990
4176
  to[id] = best;
3991
4177
  changed = true;
@@ -4152,6 +4338,10 @@ function strokesOf(rgba, labels, w, h, colors, labs, drawn, o) {
4152
4338
  for (let i = 0; i < n; i++) if (ink[i] && !fits(pieces.comp[i])) ink[i] = skel[i] = 0;
4153
4339
  const { subs, measured } = skeletonStrokes(ink, w, h, o, skel);
4154
4340
  if (!subs.length) continue;
4341
+ for (const i of beyondStroke(ink, w, h, subs, measured)) {
4342
+ ink[i] = 0;
4343
+ labels[i] = l;
4344
+ }
4155
4345
  out.push({
4156
4346
  d: serializePath(subs),
4157
4347
  fill: colors[l],
@@ -4199,6 +4389,77 @@ function strokesOf(rgba, labels, w, h, colors, labs, drawn, o) {
4199
4389
  }
4200
4390
  return out;
4201
4391
  }
4392
+ /** Ink past a stroke's edge (px) before it counts as ink the stroke misses: anti-aliasing and fitting stay within it. */
4393
+ const BEYOND = .75;
4394
+ /** A piece of missed ink is kept only if this many pixels or more; less is the edge's noise. */
4395
+ const BEYOND_AREA = 6;
4396
+ /**
4397
+ * The ink a stroke of `width` along `subs` doesn't cover at the stroke's open
4398
+ * ends, in pieces of at least BEYOND_AREA pixels, each with the ink within
4399
+ * half the width of it so it comes out solid: a dot drawn on a line's end.
4400
+ * Missed ink elsewhere (the tip of a sharp corner, which a centreline turns
4401
+ * inside) is left to the line: as a shape it reads as a blob, not a point.
4402
+ */
4403
+ function beyondStroke(ink, w, h, subs, width) {
4404
+ const n = w * h;
4405
+ const covered = new Uint8Array(n);
4406
+ const r = width / 2 + BEYOND;
4407
+ const stamp = (p) => {
4408
+ for (let y = Math.max(0, Math.floor(p.y - r)); y <= Math.min(h - 1, Math.ceil(p.y + r)); y++) for (let x = Math.max(0, Math.floor(p.x - r)); x <= Math.min(w - 1, Math.ceil(p.x + r)); x++) if ((x + .5 - p.x) ** 2 + (y + .5 - p.y) ** 2 <= r * r) covered[y * w + x] = 1;
4409
+ };
4410
+ for (const sp of subs) {
4411
+ const m = sp.nodes.length;
4412
+ if (m === 1) stamp(sp.nodes[0]);
4413
+ for (let i = 0; i < (sp.closed ? m : m - 1); i++) {
4414
+ const a = sp.nodes[i];
4415
+ const b = sp.nodes[(i + 1) % m];
4416
+ const c = [
4417
+ a,
4418
+ a.out ?? a,
4419
+ b.in ?? b,
4420
+ b
4421
+ ];
4422
+ const steps = Math.max(2, Math.ceil(2 * (Math.hypot(c[1].x - c[0].x, c[1].y - c[0].y) + Math.hypot(c[2].x - c[1].x, c[2].y - c[1].y) + Math.hypot(c[3].x - c[2].x, c[3].y - c[2].y))));
4423
+ for (let k = 0; k <= steps; k++) stamp(pointAt(c, k / steps));
4424
+ }
4425
+ }
4426
+ const missed = new Int32Array(n);
4427
+ for (let i = 0; i < n; i++) missed[i] = ink[i] && !covered[i] ? 1 : 0;
4428
+ const pieces = components(missed, w, h, (v) => v === 1);
4429
+ const ends = subs.filter((sp) => !sp.closed && sp.nodes.length > 1).flatMap((sp) => [sp.nodes[0], sp.nodes[sp.nodes.length - 1]]);
4430
+ const atEnd = new Uint8Array(pieces.compArea.length);
4431
+ const near = width + 1;
4432
+ for (let i = 0; i < n; i++) if (missed[i] && !atEnd[pieces.comp[i]]) {
4433
+ const x = i % w + .5;
4434
+ const y = Math.floor(i / w) + .5;
4435
+ if (ends.some((e) => (e.x - x) ** 2 + (e.y - y) ** 2 <= near * near)) atEnd[pieces.comp[i]] = 1;
4436
+ }
4437
+ const out = [];
4438
+ const taken = new Uint8Array(n);
4439
+ for (let i = 0; i < n; i++) if (missed[i] && atEnd[pieces.comp[i]] && pieces.compArea[pieces.comp[i]] >= BEYOND_AREA) {
4440
+ taken[i] = 1;
4441
+ out.push(i);
4442
+ }
4443
+ let front = out.slice();
4444
+ for (let step = 0; step < Math.round(width / 2) && front.length; step++) {
4445
+ const next = [];
4446
+ for (const i of front) {
4447
+ const x = i % w;
4448
+ for (const j of [
4449
+ x > 0 ? i - 1 : -1,
4450
+ x < w - 1 ? i + 1 : -1,
4451
+ i - w,
4452
+ i + w
4453
+ ]) if (j >= 0 && j < n && ink[j] && !taken[j]) {
4454
+ taken[j] = 1;
4455
+ next.push(j);
4456
+ out.push(j);
4457
+ }
4458
+ }
4459
+ front = next;
4460
+ }
4461
+ return out;
4462
+ }
4202
4463
  /** The median of `values` weighted by `weights`, over the indices `ok` takes; 0 if none. */
4203
4464
  function weightedMedian(values, weights, ok) {
4204
4465
  const order = [];
@@ -4511,6 +4772,192 @@ function toSubpath(cubics) {
4511
4772
  };
4512
4773
  }
4513
4774
  //#endregion
4775
+ //#region src/smooth.ts
4776
+ /**
4777
+ * Edge-preserving smoothing for painted art, before its palette is picked.
4778
+ *
4779
+ * A painted poster's skin shadow is a soft ramp with brush and JPEG noise on
4780
+ * it. Labelled pixel by pixel, the noise flips each pixel between the two
4781
+ * nearest palette colours, and the shadow traces as ragged patches. A
4782
+ * bilateral filter averages each pixel with neighbours of a similar colour
4783
+ * only, so the noise inside a shadow evens out and the edges between colours
4784
+ * (an arm against the dark coat, a line on a face) stay where they are.
4785
+ *
4786
+ * On a painted film poster traced at 2× in Illustration, this turned the
4787
+ * blotchy arm and neck shadows into whole shapes, kept the face lines, and cut
4788
+ * the file from 3.3 MB to 2.1 MB; the filter took 4 s of the trace. Stronger
4789
+ * (radius 6, three passes at sigma 25) began to wash out lines in the hair.
4790
+ */
4791
+ /** Neighbourhood radius, px. */
4792
+ const RADIUS = 4;
4793
+ /** Spatial falloff (Gaussian sigma, px). */
4794
+ const SIGMA_SPACE = 3;
4795
+ /** Colour falloff (Gaussian sigma, RGB distance). */
4796
+ const SIGMA_COLOR = 30;
4797
+ const PASSES = 3;
4798
+ /**
4799
+ * A smoothed copy of `rgba` (`width` × `height`, RGBA). Transparent pixels, and
4800
+ * any marked in `keep` (one entry per pixel, non-zero to keep), are left as
4801
+ * they are and never averaged into their neighbours.
4802
+ */
4803
+ function smoothShading(rgba, width, height, keep) {
4804
+ const dxs = [];
4805
+ const dys = [];
4806
+ const ws = [];
4807
+ for (let dy = -4; dy <= RADIUS; dy++) for (let dx = -4; dx <= RADIUS; dx++) if (dx * dx + dy * dy <= 16) {
4808
+ dxs.push(dx);
4809
+ dys.push(dy);
4810
+ ws.push(Math.exp(-(dx * dx + dy * dy) / (2 * SIGMA_SPACE ** 2)));
4811
+ }
4812
+ const n = ws.length;
4813
+ const offsets = Int32Array.from(dxs, (dx, k) => (dys[k] * width + dx) * 4);
4814
+ const spatial = Float32Array.from(ws);
4815
+ const near = Float32Array.from({ length: 195076 }, (_, d2) => Math.exp(-d2 / (2 * SIGMA_COLOR ** 2)));
4816
+ let src = Uint8ClampedArray.from(rgba);
4817
+ const kept = [];
4818
+ if (keep) {
4819
+ for (let p = 0; p < width * height; p++) if (keep[p] && src[p * 4 + 3] >= 128) {
4820
+ kept.push(p, src[p * 4 + 3]);
4821
+ src[p * 4 + 3] = 0;
4822
+ }
4823
+ }
4824
+ for (let pass = 0; pass < PASSES; pass++) {
4825
+ const out = new Uint8ClampedArray(src);
4826
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
4827
+ const i = (y * width + x) * 4;
4828
+ if (src[i + 3] < 128) continue;
4829
+ const r = src[i];
4830
+ const g = src[i + 1];
4831
+ const b = src[i + 2];
4832
+ const inside = x >= RADIUS && y >= RADIUS && x < width - RADIUS && y < height - RADIUS;
4833
+ let sr = 0;
4834
+ let sg = 0;
4835
+ let sb = 0;
4836
+ let sw = 0;
4837
+ for (let k = 0; k < n; k++) {
4838
+ if (!inside) {
4839
+ const nx = x + dxs[k];
4840
+ const ny = y + dys[k];
4841
+ if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
4842
+ }
4843
+ const j = i + offsets[k];
4844
+ if (src[j + 3] < 128) continue;
4845
+ const dr = src[j] - r;
4846
+ const dg = src[j + 1] - g;
4847
+ const db = src[j + 2] - b;
4848
+ const w = spatial[k] * near[dr * dr + dg * dg + db * db];
4849
+ sr += w * src[j];
4850
+ sg += w * src[j + 1];
4851
+ sb += w * src[j + 2];
4852
+ sw += w;
4853
+ }
4854
+ out[i] = sr / sw;
4855
+ out[i + 1] = sg / sw;
4856
+ out[i + 2] = sb / sw;
4857
+ }
4858
+ src = out;
4859
+ }
4860
+ for (let k = 0; k < kept.length; k += 2) src[kept[k] * 4 + 3] = kept[k + 1];
4861
+ return src;
4862
+ }
4863
+ /** A line pixel is this much darker than its closing (0–255 lightness) at least. */
4864
+ const LINE_DEPTH = 6;
4865
+ /** And darkened by this many times that depth, */
4866
+ const LINE_GAIN = 2;
4867
+ /** but by no more than this: a line already well apart from its sides (brows on skin) keeps its colour. */
4868
+ const LINE_MAX = 30;
4869
+ /** A line is kept only when it spans this many times the radius (bounding-box diagonal): texture is short. */
4870
+ const LINE_SPAN = 4;
4871
+ /**
4872
+ * Painted outlines made plain, before the palette is picked. A painter's line
4873
+ * between two near-equal colours (a mouth on a shadowed face, dark trousers
4874
+ * against a dark background) is only a few levels darker than either side, so
4875
+ * it labels as one of them and is lost. A black-hat filter (the image's
4876
+ * closing minus the image, over `radius` px) finds lines up to about twice
4877
+ * that wide that are darker than both sides; each is darkened by twice its
4878
+ * depth, at most LINE_MAX, colour kept, so it labels apart from both sides.
4879
+ * Only lines that run a while are kept: brick, foliage and brush texture are
4880
+ * dark too, but short. When `lines` (one entry per pixel) is given, each
4881
+ * pixel darkened is marked in it with 1, for `smoothShading`'s `keep` and
4882
+ * the tracer's `lines`, which leave them be.
4883
+ *
4884
+ * On a painted film poster at 2× (radius 3), with smoothing, this brought back
4885
+ * the mouth, eyes, brows and jaw lines Illustration lost, and the outline
4886
+ * parting dark trousers from a dark background, for twice the paths (2.1 to
4887
+ * 3.6 MB). The trousers merged with the background until the lines were marked:
4888
+ * the outline was found, but smoothing blurred it back into its sides, and,
4889
+ * left unsmoothed, it labelled as the near-black of the trousers, close
4890
+ * enough to the dark grey on either side to be folded in as a sliver.
4891
+ */
4892
+ function boostLines(rgba, width, height, radius = 2, lines) {
4893
+ const n = width * height;
4894
+ const out = Uint8ClampedArray.from(rgba);
4895
+ const lum = new Float32Array(n);
4896
+ for (let i = 0; i < n; i++) lum[i] = .299 * out[i * 4] + .587 * out[i * 4 + 1] + .114 * out[i * 4 + 2];
4897
+ const sweep = (src, max) => {
4898
+ const across = new Float32Array(n);
4899
+ const down = new Float32Array(n);
4900
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
4901
+ let v = src[y * width + x];
4902
+ for (let k = Math.max(0, x - radius); k <= Math.min(width - 1, x + radius); k++) v = max ? Math.max(v, src[y * width + k]) : Math.min(v, src[y * width + k]);
4903
+ across[y * width + x] = v;
4904
+ }
4905
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
4906
+ let v = across[y * width + x];
4907
+ for (let k = Math.max(0, y - radius); k <= Math.min(height - 1, y + radius); k++) v = max ? Math.max(v, across[k * width + x]) : Math.min(v, across[k * width + x]);
4908
+ down[y * width + x] = v;
4909
+ }
4910
+ return down;
4911
+ };
4912
+ const closed = sweep(sweep(lum, true), false);
4913
+ const depth = new Float32Array(n);
4914
+ for (let i = 0; i < n; i++) if (out[i * 4 + 3] >= 128 && closed[i] - lum[i] > LINE_DEPTH) depth[i] = closed[i] - lum[i];
4915
+ const seen = new Uint8Array(n);
4916
+ const stack = [];
4917
+ const piece = [];
4918
+ const span = LINE_SPAN * radius;
4919
+ for (let s = 0; s < n; s++) {
4920
+ if (!depth[s] || seen[s]) continue;
4921
+ seen[s] = 1;
4922
+ stack.push(s);
4923
+ piece.length = 0;
4924
+ let x0 = width;
4925
+ let x1 = 0;
4926
+ let y0 = height;
4927
+ let y1 = 0;
4928
+ while (stack.length) {
4929
+ const i = stack.pop();
4930
+ piece.push(i);
4931
+ const x = i % width;
4932
+ const y = (i - x) / width;
4933
+ x0 = Math.min(x0, x);
4934
+ x1 = Math.max(x1, x);
4935
+ y0 = Math.min(y0, y);
4936
+ y1 = Math.max(y1, y);
4937
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
4938
+ const nx = x + dx;
4939
+ const ny = y + dy;
4940
+ if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
4941
+ const j = ny * width + nx;
4942
+ if (depth[j] && !seen[j]) {
4943
+ seen[j] = 1;
4944
+ stack.push(j);
4945
+ }
4946
+ }
4947
+ }
4948
+ if (Math.hypot(x1 - x0, y1 - y0) < span) continue;
4949
+ for (const i of piece) {
4950
+ const target = Math.max(0, lum[i] - Math.min(LINE_MAX, LINE_GAIN * depth[i]));
4951
+ const f = lum[i] > 0 ? target / lum[i] : 0;
4952
+ out[i * 4] *= f;
4953
+ out[i * 4 + 1] *= f;
4954
+ out[i * 4 + 2] *= f;
4955
+ if (lines) lines[i] = 1;
4956
+ }
4957
+ }
4958
+ return out;
4959
+ }
4960
+ //#endregion
4514
4961
  //#region src/centerline.ts
4515
4962
  /**
4516
4963
  * Centerline tracing: single strokes down the middle of the ink, for pen
@@ -4536,7 +4983,7 @@ function toSubpath(cubics) {
4536
4983
  const traceCenterline = (rgba, w, h, o) => centerlineToSvg(centerline(rgba, w, h, o));
4537
4984
  function centerlineToSvg(r) {
4538
4985
  const paths = r.paths.map((p) => `<path d="${attr(p.d)}" fill="none" stroke="${attr(p.stroke)}" stroke-width="${attr(round(p.strokeWidth))}" stroke-linecap="round" stroke-linejoin="round"/>`);
4539
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${r.width}" height="${r.height}" viewBox="0 0 ${r.width} ${r.height}">\n${paths.join("\n")}\n</svg>\n`;
4986
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${attr(r.width)}" height="${attr(r.height)}" viewBox="0 0 ${attr(r.width)} ${attr(r.height)}">\n${paths.join("\n")}\n</svg>\n`;
4540
4987
  }
4541
4988
  const round = (n) => Math.round(n * 100) / 100;
4542
4989
  function centerline(rgba, w, h, o) {
@@ -4742,4 +5189,4 @@ function detectSymmetry(rgba, w, h, options = {}) {
4742
5189
  return out.sort((a, b) => b.score - a.score);
4743
5190
  }
4744
5191
  //#endregion
4745
- export { centerline, centerlineToSvg, colorAt, detectSymmetry, exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, quantizePalette, serializePath, staircase, toSvg, trace, traceCenterline, traceInlay };
5192
+ export { boostLines, centerline, centerlineToSvg, colorAt, detectSymmetry, exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, quantizePalette, serializePath, smoothShading, staircase, toSvg, trace, traceCenterline, traceInlay };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inlaytrace",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Trace images into SVG shapes that share their edges exactly: no gaps, no overlaps. Pure TypeScript, no WebAssembly.",
5
5
  "type": "module",
6
6
  "license": "MIT",