inlaytrace 0.5.0 → 0.6.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,5 +1,11 @@
1
1
  # inlaytrace
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - New `sticker(result, options)` and `stickerSvg(result, options)`: a solid backing behind a trace, so it prints and cuts as one sticker. The backing follows the art's outline grown by a margin (holes filled, tight inside corners rounded off so a blade can follow them, then traced into one smooth path), or is the smallest circle, upright oval, square or rectangle round it, with rounded corners if asked. Options give the margin, colour and corners, and a cut line with bleed: the backing reaches past the cut so a cut that lands a little off never shows a sliver of the background. A background shape is left out, and a sheet of objects gets a backing each.
8
+
3
9
  ## 0.5.0
4
10
 
5
11
  ### Minor Changes
package/README.md CHANGED
@@ -90,6 +90,10 @@ says what each does.
90
90
  rotational orders in an image, each scored by how much of the drawing
91
91
  matches (the app offers to enforce one at 95% or more).
92
92
  - `oklab(rgb)`: the perceptual colour space the palette and labelling use.
93
+ - `sticker(result, options)` / `stickerSvg(…)`: a solid backing behind a trace,
94
+ so it prints and cuts as one sticker: the art's outline grown by a margin,
95
+ or a circle, oval, square or rectangle round it, with an optional cut line
96
+ and bleed.
93
97
 
94
98
  ## How it works
95
99
 
package/dist/index.d.ts CHANGED
@@ -516,4 +516,47 @@ type SymmetryOptions = {
516
516
  * no foreground.
517
517
  */
518
518
  export declare function detectSymmetry(rgba: ArrayLike<number>, w: number, h: number, options?: SymmetryOptions): Symmetry[];
519
- export type { AbortSignalLike, CenterlineOptions, CenterlineResult, Cubic, FitOptions, Gradient, GradientStop, ImageLike, InlayOptions, InlayPath, InlayResult, MirrorSymmetry, PathNode, PresetDefaults, PresetName, Pt, Rgb, RotationalSymmetry, Subpath, Symmetry, SymmetryOptions, TraceAsyncOptions, TraceOptions, TraceStage, TraceStep };
519
+ type StickerShape = 'contour' | 'circle' | 'oval' | 'square' | 'rectangle';
520
+ type StickerOptions = {
521
+ /** The backing's shape: the drawing's outline grown by `margin` ('contour', the default), or a circle, oval, square or rectangle round it. */
522
+ shape?: StickerShape;
523
+ /** Px from the drawing to the backing's edge (the cut). Default 4% of the drawing's longer side. */
524
+ margin?: number;
525
+ /** Contour: inside corners are rounded to at least this radius, in px, so a blade can follow them. Default half the margin. */
526
+ roundOff?: number;
527
+ /** Square and rectangle: corner radius, as a share (0–1) of half the shorter side. 0, the default, is sharp; 1 makes a rectangle a pill. */
528
+ corners?: number;
529
+ /** The backing's colour. Default '#ffffff'. */
530
+ color?: string;
531
+ /** Also give the cut line: the backing's edge before `bleed`. */
532
+ cutLine?: boolean;
533
+ /** Px the backing reaches past the cut line. Default 0. */
534
+ bleed?: number;
535
+ /** Leave out a background (a filled shape at least 95% of the drawing's width and height), as it isn't part of the art. Default true. */
536
+ background?: boolean;
537
+ };
538
+ type StickerResult = {
539
+ /** The backing: a filled shape, drawn behind the art. Its `d` is empty when there's nothing to back. */
540
+ backing: InlayPath;
541
+ /** Path data for the cut line, when `cutLine` was asked for. */
542
+ cutLine?: string;
543
+ /** The sticker's bounds in the drawing's px (the backing's, with its bleed). They can reach past the drawing's own edges. */
544
+ box: {
545
+ x: number;
546
+ y: number;
547
+ width: number;
548
+ height: number;
549
+ };
550
+ /** The art the backing was made for: the drawing's shapes, less its background (with `background`, the default). */
551
+ art: InlayPath[];
552
+ };
553
+ /** The backing for a trace, and optionally its cut line. */
554
+ export declare function sticker(r: InlayResult, o?: StickerOptions): StickerResult;
555
+ /**
556
+ * The sticker as an SVG document: the backing (`id="sticker-backing"`), the
557
+ * art over it, and the cut line on top (`id="cut-line"`, an unfilled
558
+ * hairline). The page is the sticker's box, so it can reach past the
559
+ * drawing's own edges.
560
+ */
561
+ export declare function stickerSvg(r: InlayResult, o?: StickerOptions): string;
562
+ export type { AbortSignalLike, CenterlineOptions, CenterlineResult, Cubic, FitOptions, Gradient, GradientStop, ImageLike, InlayOptions, InlayPath, InlayResult, MirrorSymmetry, PathNode, PresetDefaults, PresetName, Pt, Rgb, RotationalSymmetry, StickerOptions, StickerResult, StickerShape, Subpath, Symmetry, SymmetryOptions, TraceAsyncOptions, TraceOptions, TraceStage, TraceStep };
package/dist/index.js CHANGED
@@ -197,11 +197,11 @@ function close(sub) {
197
197
  nodes.pop();
198
198
  }
199
199
  }
200
- const num$1 = (n) => {
200
+ const num$2 = (n) => {
201
201
  const r = Math.round(n * 1e3) / 1e3;
202
202
  return Object.is(r, -0) ? "0" : String(r);
203
203
  };
204
- const pt = (p) => `${num$1(p.x)} ${num$1(p.y)}`;
204
+ const pt = (p) => `${num$2(p.x)} ${num$2(p.y)}`;
205
205
  function segment(a, b) {
206
206
  return a.out || b.in ? `C${pt(a.out ?? a)} ${pt(b.in ?? b)} ${pt(b)}` : `L${pt(b)}`;
207
207
  }
@@ -253,7 +253,7 @@ const LOOSE = {
253
253
  };
254
254
  /** An ellipse whose axes differ by less than this is drawn as a circle. */
255
255
  const ROUND = .015;
256
- const KAPPA = .5522847498307936;
256
+ const KAPPA$1 = .5522847498307936;
257
257
  /** Area, centroid and central second moments (per unit area) of a closed polygon. */
258
258
  function moments(pts) {
259
259
  let a = 0;
@@ -354,8 +354,8 @@ function quarter(cx, cy, cos, sin, a, b, ox, oy, t) {
354
354
  const p = (u, v) => world(ox + u, oy + v, cx, cy, cos, sin);
355
355
  return [
356
356
  p(a * c0, b * s0),
357
- p(a * c0 - KAPPA * a * s0, b * s0 + KAPPA * b * c0),
358
- p(a * c1 + KAPPA * a * s1, b * s1 - KAPPA * b * c1),
357
+ p(a * c0 - KAPPA$1 * a * s0, b * s0 + KAPPA$1 * b * c0),
358
+ p(a * c1 + KAPPA$1 * a * s1, b * s1 - KAPPA$1 * b * c1),
359
359
  p(a * c1, b * s1)
360
360
  ];
361
361
  }
@@ -760,7 +760,7 @@ function fitOnce(points, closed, o, smoothLoop, fine) {
760
760
  }
761
761
  const run = smoothed.true;
762
762
  const t = norm(sub$1(run[1], run[run.length - 2]));
763
- const loop = flatten(fitMixed(smoothed, o.tolerance, t, mul(t, -1), 0));
763
+ const loop = flatten$1(fitMixed(smoothed, o.tolerance, t, mul(t, -1), 0));
764
764
  return o.snap === false ? loop : snapLines(loop, true);
765
765
  }
766
766
  const breaks = corners.map((c) => ({
@@ -793,10 +793,10 @@ function fitOnce(points, closed, o, smoothLoop, fine) {
793
793
  run[run.length - 1] = to.at;
794
794
  out.push(...fitBetween(smooth(run, false, o.smoothing ?? SMOOTH$1), o.tolerance));
795
795
  }
796
- return o.snap === false ? flatten(out) : snapLines(flatten(out), closed);
796
+ return o.snap === false ? flatten$1(out) : snapLines(flatten$1(out), closed);
797
797
  }
798
798
  /** Straight runs written as exact lines, so they serialise as L, not C. */
799
- function flatten(cubics) {
799
+ function flatten$1(cubics) {
800
800
  return cubics.map((c) => isFlat(c) ? line(c[0], c[3]) : c);
801
801
  }
802
802
  /** Lines within this many degrees of horizontal, vertical or 45° are made exactly that... */
@@ -1465,7 +1465,7 @@ function peakPalette(rgba, maxColors, { minDistance = .07, minShare = .002, minD
1465
1465
  if (picked.length >= maxColors) break;
1466
1466
  const share = it.weight / opaque;
1467
1467
  if (share < minDetail && picked.length > 0) break;
1468
- if (!picked.every((p) => distance(p.lab, it.lab) >= minDistance)) continue;
1468
+ if (!picked.every((p) => distance$1(p.lab, it.lab) >= minDistance)) continue;
1469
1469
  if ((share < minShare || flat !== null && share < EDGE_SHARE && it.flatWeight < EDGE_FLAT * it.weight) && isBlend(it.rgb, it.lab, picked, minDistance)) continue;
1470
1470
  picked.push({
1471
1471
  lab: it.lab,
@@ -1551,7 +1551,7 @@ function weigh(items, radius) {
1551
1551
  }
1552
1552
  for (const it of items) {
1553
1553
  const [cl, ca, cb] = it.lab.map(cell);
1554
- for (let i = cl - 1; i <= cl + 1; i++) for (let j = ca - 1; j <= ca + 1; j++) for (let k = cb - 1; k <= cb + 1; k++) for (const o of grid.get(`${i},${j},${k}`) ?? []) if (distance(o.lab, it.lab) <= radius) {
1554
+ for (let i = cl - 1; i <= cl + 1; i++) for (let j = ca - 1; j <= ca + 1; j++) for (let k = cb - 1; k <= cb + 1; k++) for (const o of grid.get(`${i},${j},${k}`) ?? []) if (distance$1(o.lab, it.lab) <= radius) {
1555
1555
  it.weight += o.n;
1556
1556
  it.flatWeight += o.flat;
1557
1557
  if (o.n > it.n) it.peak = false;
@@ -1588,7 +1588,7 @@ function flatTints(flat, opaque, picked, room, minTint, minFlat) {
1588
1588
  const tint = (it) => it.peak && it.lab[0] >= TINT_LIGHTNESS && it.weight >= minFlat * opaque;
1589
1589
  for (const it of items.filter(tint).sort((a, b) => b.weight - a.weight)) {
1590
1590
  if (out.length >= room) break;
1591
- if ([...picked, ...out].every((p) => distance(p.lab, it.lab) >= minTint)) out.push({
1591
+ if ([...picked, ...out].every((p) => distance$1(p.lab, it.lab) >= minTint)) out.push({
1592
1592
  lab: it.lab,
1593
1593
  rgb: it.rgb
1594
1594
  });
@@ -1641,13 +1641,13 @@ function closeFills(flat, opaque, picked, room, radius, minShare) {
1641
1641
  const passed = /* @__PURE__ */ new Set();
1642
1642
  while (out.length < room) {
1643
1643
  const all = [...picked, ...out];
1644
- const left = bins.filter((b) => !passed.has(b.key) && b.lab[0] < TINT_LIGHTNESS && all.every((p) => distance(p.lab, b.lab) > radius));
1644
+ const left = bins.filter((b) => !passed.has(b.key) && b.lab[0] < TINT_LIGHTNESS && all.every((p) => distance$1(p.lab, b.lab) > radius));
1645
1645
  for (const b of left) b.weight = 0;
1646
1646
  weigh(left, radius);
1647
1647
  let best;
1648
1648
  for (const b of left) if (!best || b.weight > best.weight) best = b;
1649
1649
  if (!best || best.weight < minShare * opaque) break;
1650
- const spot = left.filter((o) => distance(o.lab, best.lab) <= radius);
1650
+ const spot = left.filter((o) => distance$1(o.lab, best.lab) <= radius);
1651
1651
  const sum = [
1652
1652
  0,
1653
1653
  0,
@@ -1664,7 +1664,7 @@ function closeFills(flat, opaque, picked, room, radius, minShare) {
1664
1664
  sum[2] / n
1665
1665
  ];
1666
1666
  const lab = oklab(rgb);
1667
- if (inRamp(rgb, lab, all, RAMP_TOLERANCE, RAMP_SPAN * radius) || !all.every((p) => distance(p.lab, lab) > radius)) for (const o of spot) passed.add(o.key);
1667
+ if (inRamp(rgb, lab, all, RAMP_TOLERANCE, RAMP_SPAN * radius) || !all.every((p) => distance$1(p.lab, lab) > radius)) for (const o of spot) passed.add(o.key);
1668
1668
  else out.push({
1669
1669
  rgb,
1670
1670
  lab
@@ -1680,11 +1680,11 @@ function closeFills(flat, opaque, picked, room, radius, minShare) {
1680
1680
  * the truck's grey was 0.021 off it.
1681
1681
  */
1682
1682
  function inRamp(rgb, lab, picked, tolerance, span) {
1683
- const near = picked.filter((p) => distance(p.lab, lab) <= span);
1683
+ const near = picked.filter((p) => distance$1(p.lab, lab) <= span);
1684
1684
  for (let i = 0; i < near.length; i++) for (let j = i + 1; j < near.length; j++) {
1685
1685
  const a = near[i].rgb;
1686
1686
  const b = near[j].rgb;
1687
- if (distance(near[i].lab, near[j].lab) > span) continue;
1687
+ if (distance$1(near[i].lab, near[j].lab) > span) continue;
1688
1688
  const d = [
1689
1689
  b[0] - a[0],
1690
1690
  b[1] - a[1],
@@ -1698,7 +1698,7 @@ function inRamp(rgb, lab, picked, tolerance, span) {
1698
1698
  1,
1699
1699
  2
1700
1700
  ].map((k) => Math.min(255, Math.max(0, a[k] + t * d[k])));
1701
- if (distance(oklab(mix), lab) < tolerance) return true;
1701
+ if (distance$1(oklab(mix), lab) < tolerance) return true;
1702
1702
  }
1703
1703
  return false;
1704
1704
  }
@@ -1718,7 +1718,7 @@ function isBlend(rgb, lab, picked, tolerance) {
1718
1718
  const len = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
1719
1719
  if (!len) continue;
1720
1720
  const t = Math.min(1, Math.max(0, ((rgb[0] - a[0]) * d[0] + (rgb[1] - a[1]) * d[1] + (rgb[2] - a[2]) * d[2]) / len));
1721
- if (distance(oklab([
1721
+ if (distance$1(oklab([
1722
1722
  a[0] + t * d[0],
1723
1723
  a[1] + t * d[1],
1724
1724
  a[2] + t * d[2]
@@ -1880,7 +1880,7 @@ function quantizePalette(rgba, maxColors, { iterations = 16 } = {}) {
1880
1880
  return [...new Set(hexes)];
1881
1881
  }
1882
1882
  const distance2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
1883
- const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
1883
+ const distance$1 = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
1884
1884
  const toHex = (rgb) => `#${rgb.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
1885
1885
  /**
1886
1886
  * Pixel art's palette: its colours exactly, most-used first. Pixel art has a
@@ -3728,7 +3728,7 @@ function toSvg(r) {
3728
3728
  const head = defs.length ? `<defs>\n${defs.join("\n")}\n</defs>\n` : "";
3729
3729
  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${head}${body}\n</svg>\n`;
3730
3730
  }
3731
- const num = (v) => String(Math.round(v * 100) / 100);
3731
+ const num$1 = (v) => String(Math.round(v * 100) / 100);
3732
3732
  /** A short hash (FNV-1a, base 36). */
3733
3733
  function fnv(s) {
3734
3734
  let h = 2166136261;
@@ -3737,8 +3737,8 @@ function fnv(s) {
3737
3737
  }
3738
3738
  /** A gradient element, in the drawing's pixels. */
3739
3739
  function gradientMarkup(g, id) {
3740
- const stops = g.stops.map((s) => `<stop offset="${num(s.offset * 100)}%" stop-color="${attr(s.color)}"/>`).join("");
3741
- return g.type === "linear" ? `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${num(g.x1)}" y1="${num(g.y1)}" x2="${num(g.x2)}" y2="${num(g.y2)}">${stops}</linearGradient>` : `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${num(g.cx)}" cy="${num(g.cy)}" r="${num(g.r)}">${stops}</radialGradient>`;
3740
+ const stops = g.stops.map((s) => `<stop offset="${num$1(s.offset * 100)}%" stop-color="${attr(s.color)}"/>`).join("");
3741
+ return g.type === "linear" ? `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${num$1(g.x1)}" y1="${num$1(g.y1)}" x2="${num$1(g.x2)}" y2="${num$1(g.y2)}">${stops}</linearGradient>` : `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${num$1(g.cx)}" cy="${num$1(g.cy)}" r="${num$1(g.r)}">${stops}</radialGradient>`;
3742
3742
  }
3743
3743
  /**
3744
3744
  * Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
@@ -8000,4 +8000,562 @@ function detectSymmetry(rgba, w, h, options = {}) {
8000
8000
  });
8001
8001
  return out.sort((a, b) => b.score - a.score);
8002
8002
  }
8003
- export { boostLines, centerline, centerlineToSvg, deblur, detectSymmetry, edgeBlur, exactPalette, fitChain, isFlat, mapPoints, oklab, parsePath, peakPalette, pointAt, presets, quantizePalette, serializePath, smoothShading, toSvg, trace, traceAsync, traceCenterline, traceInlay };
8003
+ // src/sticker.ts
8004
+ /**
8005
+ * Stickers: a solid backing behind a trace, so it can be printed and cut out
8006
+ * as one piece.
8007
+ *
8008
+ * The backing's shape is either the drawing's own outline grown by a margin
8009
+ * ('contour', a die-cut sticker) or a plain circle, oval, square or rectangle
8010
+ * round it. For a contour the shapes are drawn into a mask, their holes are
8011
+ * filled (a sticker is one solid piece, so the inside of an O is backing
8012
+ * too), the mask is grown by the margin with an exact distance transform, and
8013
+ * tight inside corners are rounded off so a blade can follow them; then Inlay
8014
+ * traces the mask, so the backing is one smooth path like any other shape.
8015
+ *
8016
+ * A cut line is the backing's edge without the bleed: the backing reaches
8017
+ * `bleed` past it, so a cut that lands a little off the line never shows a
8018
+ * sliver of the background.
8019
+ */
8020
+ /** A shape at least this share of the drawing's width and height is its background (as the app's objects.ts). */
8021
+ const BACKGROUND = .95;
8022
+ /** The mask's longer side, in cells, at most; and its cells per drawing px, at most. */
8023
+ const GRID = 1024;
8024
+ const MAX_SCALE = 4;
8025
+ /** The circle and ellipse as cubics: the handle length for a quarter turn. */
8026
+ const KAPPA = .5522847498;
8027
+ const num = (v) => String(Math.round(v * 100) / 100);
8028
+ /** The backing for a trace, and optionally its cut line. */
8029
+ function sticker(r, o = {}) {
8030
+ const shape = o.shape ?? "contour";
8031
+ const color = o.color ?? "#ffffff";
8032
+ const art = o.background === false ? r.paths : r.paths.filter((p) => !isBackground(p, r));
8033
+ const shapes = art.map((p) => ({
8034
+ subs: parsePath(p.d),
8035
+ stroke: p.stroke ?? 0
8036
+ }));
8037
+ const box = boundsOf(shapes);
8038
+ if (!box) return {
8039
+ backing: {
8040
+ d: "",
8041
+ fill: color
8042
+ },
8043
+ ...o.cutLine ? { cutLine: "" } : {},
8044
+ box: {
8045
+ x: 0,
8046
+ y: 0,
8047
+ width: r.width,
8048
+ height: r.height
8049
+ },
8050
+ art
8051
+ };
8052
+ const side = Math.max(box.x1 - box.x0, box.y1 - box.y0, 1);
8053
+ const margin = Math.max(0, o.margin ?? .04 * side);
8054
+ const bleed = Math.max(0, o.bleed ?? 0);
8055
+ const roundOff = Math.max(0, o.roundOff ?? margin / 2);
8056
+ const pad = margin + bleed + roundOff + 2;
8057
+ const scale = Math.min(MAX_SCALE, GRID / (side + 2 * pad));
8058
+ const ox = box.x0 - pad;
8059
+ const oy = box.y0 - pad;
8060
+ const w = Math.ceil((box.x1 - box.x0 + 2 * pad) * scale);
8061
+ const h = Math.ceil((box.y1 - box.y0 + 2 * pad) * scale);
8062
+ const toGrid = (p) => ({
8063
+ x: (p.x - ox) * scale,
8064
+ y: (p.y - oy) * scale
8065
+ });
8066
+ const art0 = new Uint8Array(w * h);
8067
+ for (const s of shapes) {
8068
+ const rings = s.subs.map((sub) => flatten(mapPoints([sub], toGrid)[0]));
8069
+ if (s.stroke > 0) strokeRings(art0, w, h, rings, s.stroke / 2 * scale);
8070
+ else fillRings(art0, w, h, rings);
8071
+ }
8072
+ fillHoles(art0, w, h);
8073
+ const fromGrid = (p) => ({
8074
+ x: p.x / scale + ox,
8075
+ y: p.y / scale + oy
8076
+ });
8077
+ let backingD;
8078
+ let cutD;
8079
+ let out;
8080
+ if (shape === "contour") {
8081
+ const grown = (by) => {
8082
+ const m = grow(art0, w, h, (by + roundOff) * scale);
8083
+ if (roundOff > 0) shrink(m, w, h, roundOff * scale);
8084
+ fillHoles(m, w, h);
8085
+ return m;
8086
+ };
8087
+ const trace = (m) => {
8088
+ const rgba = new Uint8ClampedArray(w * h * 4);
8089
+ for (let i = 0; i < w * h; i++) {
8090
+ const v = m[i] ? 0 : 255;
8091
+ rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = v;
8092
+ rgba[i * 4 + 3] = 255;
8093
+ }
8094
+ return serializePath(traceRaw(rgba, w, h, {
8095
+ mode: "binary",
8096
+ threshold: 128,
8097
+ speckle: 0,
8098
+ tolerance: .75,
8099
+ cornerAngle: 60
8100
+ }).paths.flatMap((p) => mapPoints(parsePath(p.d), fromGrid)));
8101
+ };
8102
+ const back = grown(margin + bleed);
8103
+ backingD = trace(back);
8104
+ if (o.cutLine) cutD = bleed > 0 ? trace(grown(margin)) : backingD;
8105
+ out = maskBounds(back, w, h, fromGrid);
8106
+ } else {
8107
+ const hull = hullOf(art0, w, h).map(fromGrid);
8108
+ const make = (by) => geometric(shape, hull, box, by, o.corners ?? 0, margin);
8109
+ const back = make(margin + bleed);
8110
+ backingD = back.d;
8111
+ if (o.cutLine) cutD = bleed > 0 ? make(margin).d : back.d;
8112
+ out = back.box;
8113
+ }
8114
+ return {
8115
+ backing: {
8116
+ d: backingD,
8117
+ fill: color
8118
+ },
8119
+ ...o.cutLine ? { cutLine: cutD ?? "" } : {},
8120
+ box: {
8121
+ x: out.x0,
8122
+ y: out.y0,
8123
+ width: out.x1 - out.x0,
8124
+ height: out.y1 - out.y0
8125
+ },
8126
+ art
8127
+ };
8128
+ }
8129
+ /**
8130
+ * The sticker as an SVG document: the backing (`id="sticker-backing"`), the
8131
+ * art over it, and the cut line on top (`id="cut-line"`, an unfilled
8132
+ * hairline). The page is the sticker's box, so it can reach past the
8133
+ * drawing's own edges.
8134
+ */
8135
+ function stickerSvg(r, o = {}) {
8136
+ const s = sticker(r, o);
8137
+ const { x, y, width, height } = s.box;
8138
+ const svg = toSvg({
8139
+ ...r,
8140
+ paths: s.art
8141
+ });
8142
+ const open = `<svg xmlns="http://www.w3.org/2000/svg" width="${num(width)}" height="${num(height)}" viewBox="${num(x)} ${num(y)} ${num(width)} ${num(height)}">\n`;
8143
+ const backing = s.backing.d ? `<path id="sticker-backing" d="${attr(s.backing.d)}" fill="${attr(s.backing.fill)}"/>\n` : "";
8144
+ const cut = s.cutLine ? `\n<path id="cut-line" d="${attr(s.cutLine)}" fill="none" stroke="#ec008c" stroke-width="1" vector-effect="non-scaling-stroke"/>` : "";
8145
+ return svg.replace(/^<svg[^>]*>\n/, open + backing).replace(/\n<\/svg>\n$/, `${cut}\n</svg>\n`);
8146
+ }
8147
+ /** Whether a shape is the drawing's background: filled, and at least 95% of its width and height. */
8148
+ function isBackground(p, r) {
8149
+ if (p.stroke) return false;
8150
+ const b = boundsOf([{
8151
+ subs: parsePath(p.d),
8152
+ stroke: 0
8153
+ }]);
8154
+ return !!b && b.x1 - b.x0 >= BACKGROUND * r.width && b.y1 - b.y0 >= BACKGROUND * r.height;
8155
+ }
8156
+ /** The shapes' bounds, by their nodes and handles (a curve stays inside its handles), and half a stroke round lines. */
8157
+ function boundsOf(shapes) {
8158
+ let x0 = 1e400;
8159
+ let y0 = 1e400;
8160
+ let x1 = -1e400;
8161
+ let y1 = -1e400;
8162
+ for (const s of shapes) {
8163
+ const e = s.stroke / 2;
8164
+ for (const sub of s.subs) for (const n of sub.nodes) for (const p of [
8165
+ n,
8166
+ n.in,
8167
+ n.out
8168
+ ]) {
8169
+ if (!p) continue;
8170
+ x0 = Math.min(x0, p.x - e);
8171
+ y0 = Math.min(y0, p.y - e);
8172
+ x1 = Math.max(x1, p.x + e);
8173
+ y1 = Math.max(y1, p.y + e);
8174
+ }
8175
+ }
8176
+ return x0 <= x1 ? {
8177
+ x0,
8178
+ y0,
8179
+ x1,
8180
+ y1
8181
+ } : null;
8182
+ }
8183
+ /** A subpath as points: each node, and along a curve a point every cell or so. Closed rings repeat their first point at the end. */
8184
+ function flatten(s) {
8185
+ const out = [];
8186
+ const n = s.nodes.length;
8187
+ if (!n) return out;
8188
+ out.push({
8189
+ x: s.nodes[0].x,
8190
+ y: s.nodes[0].y
8191
+ });
8192
+ const last = s.closed ? n : n - 1;
8193
+ for (let i = 0; i < last; i++) {
8194
+ const a = s.nodes[i];
8195
+ const b = s.nodes[(i + 1) % n];
8196
+ if (!a.out && !b.in) {
8197
+ out.push({
8198
+ x: b.x,
8199
+ y: b.y
8200
+ });
8201
+ continue;
8202
+ }
8203
+ const c1 = a.out ?? a;
8204
+ const c2 = b.in ?? b;
8205
+ const len = Math.hypot(c1.x - a.x, c1.y - a.y) + Math.hypot(c2.x - c1.x, c2.y - c1.y) + Math.hypot(b.x - c2.x, b.y - c2.y);
8206
+ const k = Math.min(256, Math.max(1, Math.ceil(len)));
8207
+ for (let j = 1; j <= k; j++) {
8208
+ const t = j / k;
8209
+ const u = 1 - t;
8210
+ out.push({
8211
+ x: u * u * u * a.x + 3 * u * u * t * c1.x + 3 * u * t * t * c2.x + t * t * t * b.x,
8212
+ y: u * u * u * a.y + 3 * u * u * t * c1.y + 3 * u * t * t * c2.y + t * t * t * b.y
8213
+ });
8214
+ }
8215
+ }
8216
+ return out;
8217
+ }
8218
+ /** Fill one shape's rings into the mask by the nonzero rule, at cell centres. */
8219
+ function fillRings(mask, w, h, rings) {
8220
+ const rows = Array.from({ length: h }, () => []);
8221
+ for (const ring of rings) for (let i = 0; i < ring.length; i++) {
8222
+ const a = ring[i];
8223
+ const b = ring[(i + 1) % ring.length];
8224
+ if (a.y === b.y) continue;
8225
+ const dir = a.y < b.y ? 1 : -1;
8226
+ const [p, q] = a.y < b.y ? [a, b] : [b, a];
8227
+ const from = Math.max(0, Math.ceil(p.y - .5));
8228
+ const to = Math.min(h - 1, Math.ceil(q.y - .5) - 1);
8229
+ for (let y = from; y <= to; y++) {
8230
+ const cy = y + .5;
8231
+ rows[y].push(p.x + (cy - p.y) / (q.y - p.y) * (q.x - p.x), dir);
8232
+ }
8233
+ }
8234
+ for (let y = 0; y < h; y++) {
8235
+ const row = rows[y];
8236
+ if (!row.length) continue;
8237
+ const xs = [];
8238
+ for (let i = 0; i < row.length; i += 2) xs.push({
8239
+ x: row[i],
8240
+ d: row[i + 1]
8241
+ });
8242
+ xs.sort((a, b) => a.x - b.x);
8243
+ let wind = 0;
8244
+ for (let i = 0; i < xs.length - 1; i++) {
8245
+ wind += xs[i].d;
8246
+ if (!wind) continue;
8247
+ const from = Math.max(0, Math.ceil(xs[i].x - .5));
8248
+ const to = Math.min(w - 1, Math.ceil(xs[i + 1].x - .5) - 1);
8249
+ for (let x = from; x <= to; x++) mask[y * w + x] = 1;
8250
+ }
8251
+ }
8252
+ }
8253
+ /** Stamp a line's rings into the mask as round-capped strokes `r` cells wide each side. */
8254
+ function strokeRings(mask, w, h, rings, r) {
8255
+ const stamp = (cx, cy) => {
8256
+ const rr = Math.max(r, .5);
8257
+ for (let y = Math.max(0, Math.floor(cy - rr)); y <= Math.min(h - 1, Math.ceil(cy + rr)); y++) for (let x = Math.max(0, Math.floor(cx - rr)); x <= Math.min(w - 1, Math.ceil(cx + rr)); x++) if ((x + .5 - cx) ** 2 + (y + .5 - cy) ** 2 <= rr * rr) mask[y * w + x] = 1;
8258
+ };
8259
+ for (const ring of rings) for (let i = 0; i < ring.length; i++) {
8260
+ const a = ring[i];
8261
+ const b = ring[i + 1] ?? a;
8262
+ const k = Math.max(1, Math.ceil(Math.hypot(b.x - a.x, b.y - a.y) / Math.max(.5, r / 2)));
8263
+ for (let j = 0; j < k; j++) stamp(a.x + (b.x - a.x) * j / k, a.y + (b.y - a.y) * j / k);
8264
+ }
8265
+ }
8266
+ /** Fill the mask's holes: every empty cell that can't reach the edge through empty cells. */
8267
+ function fillHoles(mask, w, h) {
8268
+ const out = new Uint8Array(w * h);
8269
+ const stack = [];
8270
+ const push = (i) => {
8271
+ if (!mask[i] && !out[i]) {
8272
+ out[i] = 1;
8273
+ stack.push(i);
8274
+ }
8275
+ };
8276
+ for (let x = 0; x < w; x++) {
8277
+ push(x);
8278
+ push((h - 1) * w + x);
8279
+ }
8280
+ for (let y = 0; y < h; y++) {
8281
+ push(y * w);
8282
+ push(y * w + w - 1);
8283
+ }
8284
+ while (stack.length) {
8285
+ const i = stack.pop();
8286
+ const x = i % w;
8287
+ if (x > 0) push(i - 1);
8288
+ if (x < w - 1) push(i + 1);
8289
+ if (i >= w) push(i - w);
8290
+ if (i < w * (h - 1)) push(i + w);
8291
+ }
8292
+ for (let i = 0; i < w * h; i++) if (!out[i]) mask[i] = 1;
8293
+ }
8294
+ const INF = 0x56bc75e2d63100000;
8295
+ /** Squared distance from each cell to the nearest cell where `seed` is set (Felzenszwalb and Huttenlocher's exact transform). */
8296
+ function distance(seed, w, h) {
8297
+ const f = new Float64Array(w * h);
8298
+ for (let i = 0; i < w * h; i++) f[i] = seed(i) ? 0 : INF;
8299
+ const n = Math.max(w, h);
8300
+ const g = new Float64Array(n);
8301
+ const d = new Float64Array(n);
8302
+ const v = new Int32Array(n);
8303
+ const z = new Float64Array(n + 1);
8304
+ const pass = (len) => {
8305
+ let k = 0;
8306
+ v[0] = 0;
8307
+ z[0] = -0x56bc75e2d63100000;
8308
+ z[1] = INF;
8309
+ for (let q = 1; q < len; q++) {
8310
+ let s = (g[q] + q * q - (g[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
8311
+ while (s <= z[k]) {
8312
+ k--;
8313
+ s = (g[q] + q * q - (g[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
8314
+ }
8315
+ k++;
8316
+ v[k] = q;
8317
+ z[k] = s;
8318
+ z[k + 1] = INF;
8319
+ }
8320
+ k = 0;
8321
+ for (let q = 0; q < len; q++) {
8322
+ while (z[k + 1] < q) k++;
8323
+ const p = v[k];
8324
+ d[q] = (q - p) * (q - p) + g[p];
8325
+ }
8326
+ };
8327
+ for (let x = 0; x < w; x++) {
8328
+ for (let y = 0; y < h; y++) g[y] = f[y * w + x];
8329
+ pass(h);
8330
+ for (let y = 0; y < h; y++) f[y * w + x] = d[y];
8331
+ }
8332
+ for (let y = 0; y < h; y++) {
8333
+ for (let x = 0; x < w; x++) g[x] = f[y * w + x];
8334
+ pass(w);
8335
+ for (let x = 0; x < w; x++) f[y * w + x] = d[x];
8336
+ }
8337
+ return f;
8338
+ }
8339
+ /** A new mask: every cell within `r` cells of the mask. */
8340
+ function grow(mask, w, h, r) {
8341
+ const d = distance((i) => mask[i] === 1, w, h);
8342
+ const out = new Uint8Array(w * h);
8343
+ const rr = r * r;
8344
+ for (let i = 0; i < w * h; i++) if (d[i] <= rr) out[i] = 1;
8345
+ return out;
8346
+ }
8347
+ /** Shrink the mask in place: keep only cells more than `r` cells from its outside. */
8348
+ function shrink(mask, w, h, r) {
8349
+ const d = distance((i) => mask[i] === 0, w, h);
8350
+ const rr = r * r;
8351
+ for (let i = 0; i < w * h; i++) if (mask[i] && d[i] <= rr) mask[i] = 0;
8352
+ }
8353
+ /** The mask's bounds, in the drawing's px. */
8354
+ function maskBounds(mask, w, h, from) {
8355
+ let x0 = w;
8356
+ let y0 = h;
8357
+ let x1 = -1;
8358
+ let y1 = -1;
8359
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (mask[y * w + x]) {
8360
+ if (x < x0) x0 = x;
8361
+ if (x > x1) x1 = x;
8362
+ if (y < y0) y0 = y;
8363
+ if (y > y1) y1 = y;
8364
+ }
8365
+ const a = from({
8366
+ x: x0,
8367
+ y: y0
8368
+ });
8369
+ const b = from({
8370
+ x: x1 + 1,
8371
+ y: y1 + 1
8372
+ });
8373
+ return {
8374
+ x0: a.x,
8375
+ y0: a.y,
8376
+ x1: b.x,
8377
+ y1: b.y
8378
+ };
8379
+ }
8380
+ /** The convex hull of the mask's cells (their corners), in cells. */
8381
+ function hullOf(mask, w, h) {
8382
+ const pts = [];
8383
+ for (let y = 0; y < h; y++) {
8384
+ let a = -1;
8385
+ let b = -1;
8386
+ for (let x = 0; x < w; x++) if (mask[y * w + x]) {
8387
+ if (a < 0) a = x;
8388
+ b = x;
8389
+ }
8390
+ if (a < 0) continue;
8391
+ pts.push({
8392
+ x: a,
8393
+ y
8394
+ }, {
8395
+ x: a,
8396
+ y: y + 1
8397
+ }, {
8398
+ x: b + 1,
8399
+ y
8400
+ }, {
8401
+ x: b + 1,
8402
+ y: y + 1
8403
+ });
8404
+ }
8405
+ pts.sort((p, q) => p.x - q.x || p.y - q.y);
8406
+ if (pts.length < 3) return pts;
8407
+ const cross = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
8408
+ const lower = [];
8409
+ for (const p of pts) {
8410
+ while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
8411
+ lower.push(p);
8412
+ }
8413
+ const upper = [];
8414
+ for (let i = pts.length - 1; i >= 0; i--) {
8415
+ const p = pts[i];
8416
+ while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
8417
+ upper.push(p);
8418
+ }
8419
+ return lower.slice(0, -1).concat(upper.slice(0, -1));
8420
+ }
8421
+ /** The smallest circle round the points (Welzl's, iterative; the points come shuffled by a fixed seed, so the result is repeatable). */
8422
+ function enclosingCircle(input) {
8423
+ const pts = input.slice();
8424
+ let seed = 1;
8425
+ for (let i = pts.length - 1; i > 0; i--) {
8426
+ seed = seed * 16807 % 2147483647;
8427
+ const j = seed % (i + 1);
8428
+ [pts[i], pts[j]] = [pts[j], pts[i]];
8429
+ }
8430
+ const inside = (c, p) => Math.hypot(p.x - c.x, p.y - c.y) <= c.r + 1e-7;
8431
+ const two = (a, b) => ({
8432
+ x: (a.x + b.x) / 2,
8433
+ y: (a.y + b.y) / 2,
8434
+ r: Math.hypot(a.x - b.x, a.y - b.y) / 2
8435
+ });
8436
+ const three = (a, b, c) => {
8437
+ const d = 2 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
8438
+ if (Math.abs(d) < 1e-12) return [
8439
+ two(a, b),
8440
+ two(a, c),
8441
+ two(b, c)
8442
+ ].reduce((m, k) => k.r > m.r ? k : m);
8443
+ const a2 = a.x * a.x + a.y * a.y;
8444
+ const b2 = b.x * b.x + b.y * b.y;
8445
+ const c2 = c.x * c.x + c.y * c.y;
8446
+ const x = (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d;
8447
+ const y = (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d;
8448
+ return {
8449
+ x,
8450
+ y,
8451
+ r: Math.hypot(a.x - x, a.y - y)
8452
+ };
8453
+ };
8454
+ if (!pts.length) return {
8455
+ x: 0,
8456
+ y: 0,
8457
+ r: 0
8458
+ };
8459
+ let c = {
8460
+ x: pts[0].x,
8461
+ y: pts[0].y,
8462
+ r: 0
8463
+ };
8464
+ for (let i = 1; i < pts.length; i++) {
8465
+ if (inside(c, pts[i])) continue;
8466
+ c = {
8467
+ x: pts[i].x,
8468
+ y: pts[i].y,
8469
+ r: 0
8470
+ };
8471
+ for (let j = 0; j < i; j++) {
8472
+ if (inside(c, pts[j])) continue;
8473
+ c = two(pts[i], pts[j]);
8474
+ for (let k = 0; k < j; k++) if (!inside(c, pts[k])) c = three(pts[i], pts[j], pts[k]);
8475
+ }
8476
+ }
8477
+ return c;
8478
+ }
8479
+ /** An ellipse (a circle when rx = ry) as four cubics. */
8480
+ function ellipseD(cx, cy, rx, ry) {
8481
+ const kx = KAPPA * rx;
8482
+ const ky = KAPPA * ry;
8483
+ return `M${num(cx + rx)} ${num(cy)}C${num(cx + rx)} ${num(cy + ky)} ${num(cx + kx)} ${num(cy + ry)} ${num(cx)} ${num(cy + ry)}C${num(cx - kx)} ${num(cy + ry)} ${num(cx - rx)} ${num(cy + ky)} ${num(cx - rx)} ${num(cy)}C${num(cx - rx)} ${num(cy - ky)} ${num(cx - kx)} ${num(cy - ry)} ${num(cx)} ${num(cy - ry)}C${num(cx + kx)} ${num(cy - ry)} ${num(cx + rx)} ${num(cy - ky)} ${num(cx + rx)} ${num(cy)}Z`;
8484
+ }
8485
+ /** A rectangle with corners of radius `r` (sharp at 0), clockwise from the top left. */
8486
+ function rectD(x0, y0, x1, y1, r) {
8487
+ if (r <= 0) return `M${num(x0)} ${num(y0)}L${num(x1)} ${num(y0)}L${num(x1)} ${num(y1)}L${num(x0)} ${num(y1)}Z`;
8488
+ const k = KAPPA * r;
8489
+ return `M${num(x0 + r)} ${num(y0)}L${num(x1 - r)} ${num(y0)}C${num(x1 - r + k)} ${num(y0)} ${num(x1)} ${num(y0 + r - k)} ${num(x1)} ${num(y0 + r)}L${num(x1)} ${num(y1 - r)}C${num(x1)} ${num(y1 - r + k)} ${num(x1 - r + k)} ${num(y1)} ${num(x1 - r)} ${num(y1)}L${num(x0 + r)} ${num(y1)}C${num(x0 + r - k)} ${num(y1)} ${num(x0)} ${num(y1 - r + k)} ${num(x0)} ${num(y1 - r)}L${num(x0)} ${num(y0 + r)}C${num(x0)} ${num(y0 + r - k)} ${num(x0 + r - k)} ${num(y0)} ${num(x0 + r)} ${num(y0)}Z`;
8490
+ }
8491
+ /**
8492
+ * A plain backing round the art's hull, `by` px out. Corners are sized on the
8493
+ * cut (`margin` out) and grow with the bleed, so the backing's edge stays the
8494
+ * same distance past the cut all the way round.
8495
+ */
8496
+ function geometric(shape, hull, box, by, corners, margin) {
8497
+ if (shape === "circle") {
8498
+ const c = enclosingCircle(hull);
8499
+ const r = c.r + by;
8500
+ return {
8501
+ d: ellipseD(c.x, c.y, r, r),
8502
+ box: {
8503
+ x0: c.x - r,
8504
+ y0: c.y - r,
8505
+ x1: c.x + r,
8506
+ y1: c.y + r
8507
+ }
8508
+ };
8509
+ }
8510
+ let x0 = 1e400;
8511
+ let y0 = 1e400;
8512
+ let x1 = -1e400;
8513
+ let y1 = -1e400;
8514
+ for (const p of hull) {
8515
+ x0 = Math.min(x0, p.x);
8516
+ y0 = Math.min(y0, p.y);
8517
+ x1 = Math.max(x1, p.x);
8518
+ y1 = Math.max(y1, p.y);
8519
+ }
8520
+ if (!(x0 <= x1)) ({x0, y0, x1, y1} = box);
8521
+ const cx = (x0 + x1) / 2;
8522
+ const cy = (y0 + y1) / 2;
8523
+ if (shape === "oval") {
8524
+ const a = Math.max((x1 - x0) / 2, 1e-6);
8525
+ const b = Math.max((y1 - y0) / 2, 1e-6);
8526
+ let k = 0;
8527
+ for (const p of hull) k = Math.max(k, Math.hypot((p.x - cx) / a, (p.y - cy) / b));
8528
+ const rx = a * k + by;
8529
+ const ry = b * k + by;
8530
+ return {
8531
+ d: ellipseD(cx, cy, rx, ry),
8532
+ box: {
8533
+ x0: cx - rx,
8534
+ y0: cy - ry,
8535
+ x1: cx + rx,
8536
+ y1: cy + ry
8537
+ }
8538
+ };
8539
+ }
8540
+ if (shape === "square") {
8541
+ const s = Math.max(x1 - x0, y1 - y0) / 2;
8542
+ x0 = cx - s;
8543
+ x1 = cx + s;
8544
+ y0 = cy - s;
8545
+ y1 = cy + s;
8546
+ }
8547
+ const cut = Math.min(x1 - x0, y1 - y0) / 2 + margin;
8548
+ const r = Math.min(1, Math.max(0, corners)) * cut;
8549
+ const R = r > 0 ? r + (by - margin) : 0;
8550
+ const b = {
8551
+ x0: x0 - by,
8552
+ y0: y0 - by,
8553
+ x1: x1 + by,
8554
+ y1: y1 + by
8555
+ };
8556
+ return {
8557
+ d: rectD(b.x0, b.y0, b.x1, b.y1, Math.min(R, (b.x1 - b.x0) / 2, (b.y1 - b.y0) / 2)),
8558
+ box: b
8559
+ };
8560
+ }
8561
+ export { boostLines, centerline, centerlineToSvg, deblur, detectSymmetry, edgeBlur, exactPalette, fitChain, isFlat, mapPoints, oklab, parsePath, peakPalette, pointAt, presets, quantizePalette, serializePath, smoothShading, sticker, stickerSvg, toSvg, trace, traceAsync, traceCenterline, traceInlay };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inlaytrace",
3
- "version": "0.5.0",
3
+ "version": "0.6.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",