inlaytrace 0.1.3 → 0.2.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/dist/index.js CHANGED
@@ -292,14 +292,14 @@ function withCorners(f, corners, mids) {
292
292
  //#region src/fit.ts
293
293
  const R = 6;
294
294
  const END_TRIM = 3;
295
- const SMOOTH = 12;
295
+ const SMOOTH$1 = 12;
296
296
  /**
297
297
  * A straight line is accepted at 1.5× the curve tolerance. Straight edges are
298
298
  * common in flat art, and a ripple along one is almost always JPEG noise (its
299
299
  * colour is stored in 16 px blocks), not a shape the artist drew.
300
300
  */
301
301
  const LINE_BIAS = 1.5;
302
- const sub = (a, b) => ({
302
+ const sub$1 = (a, b) => ({
303
303
  x: a.x - b.x,
304
304
  y: a.y - b.y
305
305
  });
@@ -323,49 +323,85 @@ const norm = (a) => {
323
323
  y: 0
324
324
  };
325
325
  };
326
- const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
326
+ const dist$2 = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
327
327
  const line = (a, b) => [
328
328
  a,
329
- add(a, mul(sub(b, a), 1 / 3)),
330
- add(a, mul(sub(b, a), 2 / 3)),
329
+ add(a, mul(sub$1(b, a), 1 / 3)),
330
+ add(a, mul(sub$1(b, a), 2 / 3)),
331
331
  b
332
332
  ];
333
333
  /** A cubic whose handles sit on its chord (within 0.15 px, and between the ends) is a line. */
334
334
  function isFlat([p0, c1, c2, p3]) {
335
- const d = sub(p3, p0);
335
+ const d = sub$1(p3, p0);
336
336
  const l = len(d);
337
337
  if (l < 1e-9) return true;
338
338
  const off = (p) => Math.abs((p.x - p0.x) * d.y - (p.y - p0.y) * d.x) / l;
339
- const t = (p) => dot(sub(p, p0), d) / (l * l);
339
+ const t = (p) => dot(sub$1(p, p0), d) / (l * l);
340
340
  return off(c1) < .15 && off(c2) < .15 && t(c1) >= -.01 && t(c1) <= 1.01 && t(c2) >= -.01 && t(c2) <= 1.01;
341
341
  }
342
342
  /**
343
343
  * Fit a chain. Open: from points[0] to the last point, which stay fixed.
344
344
  * Closed: points[0] is not repeated at the end; the result is a loop that starts
345
- * at a corner if there is one.
345
+ * at a corner if there is one. `fine`, if given, is the same chain placed more
346
+ * exactly (between pixels) and is what gets fitted, exact shapes included;
347
+ * `points` stays the pixel outline that the area check measures.
346
348
  */
347
- function fitChain(points, closed, o) {
348
- const pts = resample(points, closed);
349
+ function fitChain(points, closed, o, fine) {
350
+ const out = fitOnce(points, closed, o, false, fine);
351
+ if (!closed || !out.length) return out;
352
+ const want = Math.abs(loopArea(points));
353
+ if (Math.abs(loopArea(sampled(out))) >= want / 2) return out;
354
+ const loop = fitOnce(points, closed, o, true, fine);
355
+ if (loop.length && Math.abs(loopArea(sampled(loop))) >= want / 2) return loop;
356
+ return polygon(turns(points), true);
357
+ }
358
+ /** Shoelace area of a closed polygon (points[0] not repeated). */
359
+ function loopArea(pts) {
360
+ let a = 0;
361
+ for (let i = 0; i < pts.length; i++) {
362
+ const p = pts[i];
363
+ const q = pts[(i + 1) % pts.length];
364
+ a += p.x * q.y - q.x * p.y;
365
+ }
366
+ return a / 2;
367
+ }
368
+ /** A fitted loop as points, four along each cubic. */
369
+ const sampled = (cubics) => cubics.flatMap((c) => [
370
+ 0,
371
+ .25,
372
+ .5,
373
+ .75
374
+ ].map((t) => pointAt(c, t)));
375
+ /** The points of a closed outline where it changes direction. */
376
+ function turns(pts) {
377
+ const n = pts.length;
378
+ const dir = (a, b) => Math.atan2(b.y - a.y, b.x - a.x);
379
+ const out = pts.filter((p, i) => Math.abs(dir(pts[(i - 1 + n) % n], p) - dir(p, pts[(i + 1) % n])) > 1e-9);
380
+ return out.length >= 3 ? out : pts;
381
+ }
382
+ function fitOnce(points, closed, o, smoothLoop, fine) {
383
+ const pts = resample(fine ?? points, closed);
349
384
  const n = pts.length;
350
385
  if (n < 2) return [];
351
386
  if (!closed && n === 2) return [line(pts[0], pts[1])];
352
- const corners = findCorners(pts, closed, o.cornerAngle).filter((c) => closed || dist(c.at, pts[0]) >= MIN_GAP && dist(c.at, pts[n - 1]) >= MIN_GAP);
387
+ const corners = smoothLoop ? [] : findCorners(pts, closed, o.cornerAngle).filter((c) => closed || dist$2(c.at, pts[0]) >= MIN_GAP && dist$2(c.at, pts[n - 1]) >= MIN_GAP);
353
388
  if (closed && o.shapes) {
354
- const shape = fitShape(points, corners.map((c) => c.at));
389
+ const shape = fitShape(fine ?? points, corners.map((c) => c.at));
355
390
  if (shape) return shape.cubics;
356
391
  }
357
392
  if (closed && corners.length === 0) {
358
393
  if (n < 4) return polygon(pts, true);
359
- let smoothed = smooth([...pts, pts[0]], true, o.smoothing ?? SMOOTH);
394
+ let smoothed = smooth([...pts, pts[0]], true, o.smoothing ?? SMOOTH$1);
360
395
  const first = straights(smoothed.true, smoothed.radius, o.tolerance)[0];
361
396
  if (first && first[0] > 0 && first[0] < n) {
362
397
  const k = first[0];
363
398
  const turned = [...pts.slice(k), ...pts.slice(0, k)];
364
- smoothed = smooth([...turned, turned[0]], true, o.smoothing ?? SMOOTH);
399
+ smoothed = smooth([...turned, turned[0]], true, o.smoothing ?? SMOOTH$1);
365
400
  }
366
401
  const run = smoothed.true;
367
- const t = norm(sub(run[1], run[run.length - 2]));
368
- return flatten(fitMixed(smoothed, o.tolerance, t, mul(t, -1), 0));
402
+ const t = norm(sub$1(run[1], run[run.length - 2]));
403
+ const loop = flatten(fitMixed(smoothed, o.tolerance, t, mul(t, -1), 0));
404
+ return o.snap === false ? loop : snapLines(loop, true);
369
405
  }
370
406
  const breaks = corners.map((c) => ({
371
407
  index: c.index,
@@ -395,14 +431,148 @@ function fitChain(points, closed, o) {
395
431
  }
396
432
  run[0] = from.at;
397
433
  run[run.length - 1] = to.at;
398
- out.push(...fitBetween(smooth(run, false, o.smoothing ?? SMOOTH), o.tolerance));
434
+ out.push(...fitBetween(smooth(run, false, o.smoothing ?? SMOOTH$1), o.tolerance));
399
435
  }
400
- return flatten(out);
436
+ return o.snap === false ? flatten(out) : snapLines(flatten(out), closed);
401
437
  }
402
438
  /** Straight runs written as exact lines, so they serialise as L, not C. */
403
439
  function flatten(cubics) {
404
440
  return cubics.map((c) => isFlat(c) ? line(c[0], c[3]) : c);
405
441
  }
442
+ /** Lines within this many degrees of horizontal, vertical or 45° are made exactly that... */
443
+ const SNAP = 1;
444
+ /** ...if they are at least this long (px)... */
445
+ const SNAP_MIN = 8;
446
+ /** ...and no node moves further than this (px). */
447
+ const SNAP_MOVE = 1.5;
448
+ /**
449
+ * Make nearly horizontal, vertical and 45° lines exact. People draw those
450
+ * with a snap, and a fit to the pixels leaves them a fraction of a degree
451
+ * off (more after JPEG), which shows as a slant on a long edge and as nodes
452
+ * a hair apart when the shape is edited. Each such line is turned about its
453
+ * middle, or about an open chain's end, which stays fixed so the edge is
454
+ * still shared exactly; consecutive lines in one direction become one line;
455
+ * each node then moves to where its snapped lines meet, or onto its one
456
+ * snapped line, carrying the curve handle beside it, turned with the line.
457
+ * A needle's two sides, snapped opposite ways, are left as they were. Two lines either side
458
+ * of a junction that both snap pass through the same point, so they are
459
+ * collinear too.
460
+ */
461
+ function snapLines(cubics, closed) {
462
+ const n = cubics.length;
463
+ if (!n) return cubics;
464
+ const nodes = closed ? n : n + 1;
465
+ const node = (k) => k < n ? cubics[k][0] : cubics[n - 1][3];
466
+ const fixed = (k) => !closed && (k === 0 || k === n);
467
+ const end = (k) => closed ? (k + 1) % n : k + 1;
468
+ const prev = (k) => closed ? (k - 1 + n) % n : k - 1;
469
+ const was = cubics.map((c) => Math.atan2(c[3].y - c[0].y, c[3].x - c[0].x));
470
+ const angle = cubics.map((c, k) => {
471
+ if (!isFlat(c) || dist$2(c[0], c[3]) < SNAP_MIN) return null;
472
+ const to = Math.round(was[k] / (Math.PI / 4)) * (Math.PI / 4);
473
+ return Math.abs(was[k] - to) < SNAP * Math.PI / 180 ? to : null;
474
+ });
475
+ for (let round = 0; round <= n; round++) {
476
+ const same = (i, j) => angle[i] !== null && angle[j] !== null && Math.cos(angle[i] - angle[j]) > 1 - 1e-9;
477
+ const group = new Array(n).fill(-1);
478
+ const groups = [];
479
+ const drop = /* @__PURE__ */ new Set();
480
+ for (let k = 0; k < n; k++) {
481
+ if (angle[k] === null || group[k] >= 0) continue;
482
+ let first = k;
483
+ if (closed) for (let i = 1; i < n && same(prev(first), k) && prev(first) !== k; i++) first = prev(first);
484
+ const members = [];
485
+ for (let j = first; members.length < n && j < n && same(j, k) && group[j] < 0; j = closed ? (j + 1) % n : j + 1) {
486
+ group[j] = groups.length;
487
+ members.push(j);
488
+ }
489
+ const ends = [...new Set(members.flatMap((j) => [j, end(j)]))];
490
+ const dir = {
491
+ x: Math.cos(angle[k]),
492
+ y: Math.sin(angle[k])
493
+ };
494
+ const pinned = ends.filter(fixed).map(node);
495
+ const across = (p) => p.x * -dir.y + p.y * dir.x;
496
+ if (pinned.length > 1 && Math.abs(across(pinned[0]) - across(pinned[1])) > 1e-6) members.forEach((j) => drop.add(j));
497
+ const pts = pinned.length ? pinned : ends.map(node);
498
+ groups.push({
499
+ dir,
500
+ at: mul(pts.reduce(add, {
501
+ x: 0,
502
+ y: 0
503
+ }), 1 / pts.length),
504
+ members
505
+ });
506
+ }
507
+ const live = (j) => j >= 0 && group[j] >= 0 && !drop.has(j);
508
+ const onto = (g, p) => add(g.at, mul(g.dir, dot(sub$1(p, g.at), g.dir)));
509
+ const moved = [];
510
+ for (let k = 0; k < nodes; k++) {
511
+ const p = node(k);
512
+ const sides = [prev(k), k < n ? k : -1].filter(live);
513
+ const gs = [...new Set(sides.map((j) => group[j]))].map((i) => groups[i]);
514
+ let q = p;
515
+ if (fixed(k) || !gs.length) q = p;
516
+ else if (gs.length === 1) q = onto(gs[0], p);
517
+ else {
518
+ const meet = intersect(gs[0].at, add(gs[0].at, gs[0].dir), gs[1].at, add(gs[1].at, gs[1].dir));
519
+ if (!meet) for (const j of sides) groups[group[j]].members.forEach((m) => drop.add(m));
520
+ q = meet ?? p;
521
+ }
522
+ if (dist$2(p, q) > SNAP_MOVE) for (const j of sides) groups[group[j]].members.forEach((m) => drop.add(m));
523
+ moved.push(q);
524
+ }
525
+ for (let k = 0; k < n; k++) if (live(k) && dot(sub$1(moved[end(k) % nodes], moved[k]), sub$1(cubics[k][3], cubics[k][0])) <= 0) groups[group[k]].members.forEach((m) => drop.add(m));
526
+ if (drop.size) {
527
+ drop.forEach((j) => angle[j] = null);
528
+ continue;
529
+ }
530
+ const turned = (h, at, j) => {
531
+ if (!live(j)) return sub$1(h, at);
532
+ const t = angle[j] - was[j];
533
+ const v = sub$1(h, at);
534
+ return {
535
+ x: v.x * Math.cos(t) - v.y * Math.sin(t),
536
+ y: v.x * Math.sin(t) + v.y * Math.cos(t)
537
+ };
538
+ };
539
+ const out = [];
540
+ for (let k = 0; k < n; k++) {
541
+ const [p0, c1, c2, p3] = cubics[k];
542
+ const a = moved[k];
543
+ const b = moved[end(k) % nodes];
544
+ if (live(k)) out.push({
545
+ c: line(a, b),
546
+ g: group[k]
547
+ });
548
+ else if (isFlat(cubics[k])) out.push({
549
+ c: line(a, b),
550
+ g: -1
551
+ });
552
+ else out.push({
553
+ c: [
554
+ a,
555
+ add(a, turned(c1, p0, prev(k))),
556
+ add(b, turned(c2, p3, end(k) < n ? end(k) : -1)),
557
+ b
558
+ ],
559
+ g: -1
560
+ });
561
+ }
562
+ if (closed && out.length > 1 && out[0].g >= 0 && out[0].g === out[out.length - 1].g) {
563
+ const k = out.findIndex((o) => o.g !== out[0].g);
564
+ if (k > 0) out.push(...out.splice(0, k));
565
+ }
566
+ const merged = [];
567
+ for (const o of out) {
568
+ const last = merged[merged.length - 1];
569
+ if (last && o.g >= 0 && last.g === o.g) last.c = line(last.c[0], o.c[3]);
570
+ else merged.push({ ...o });
571
+ }
572
+ return merged.map((o) => o.c);
573
+ }
574
+ return cubics;
575
+ }
406
576
  function polygon(pts, closed) {
407
577
  const out = [];
408
578
  for (let i = 0; i < pts.length - (closed ? 0 : 1); i++) out.push(line(pts[i], pts[(i + 1) % pts.length]));
@@ -415,8 +585,8 @@ function resample(points, closed) {
415
585
  for (let i = 0; i < m; i++) {
416
586
  const a = points[i];
417
587
  const b = points[(i + 1) % points.length];
418
- if (dist(a, b) < 1e-9) continue;
419
- const k = Math.max(1, Math.ceil(dist(a, b)));
588
+ if (dist$2(a, b) < 1e-9) continue;
589
+ const k = Math.max(1, Math.ceil(dist$2(a, b)));
420
590
  for (let s = 0; s < k; s++) out.push({
421
591
  x: a.x + (b.x - a.x) * s / k,
422
592
  y: a.y + (b.y - a.y) * s / k
@@ -439,8 +609,8 @@ function along(pts, closed, i, ds) {
439
609
  if (!closed && (next < 0 || next >= n)) return null;
440
610
  const a = pts[k];
441
611
  const b = pts[(next + n) % n];
442
- const l = dist(a, b);
443
- if (l >= left) return add(a, mul(sub(b, a), left / l));
612
+ const l = dist$2(a, b);
613
+ if (l >= left) return add(a, mul(sub$1(b, a), left / l));
444
614
  left -= l;
445
615
  k = (next + n) % n;
446
616
  }
@@ -453,15 +623,15 @@ const room = (n, closed, i, side) => closed ? Infinity : side < 0 ? i : n - 1 -
453
623
  * open chain's end (a junction, where a peak often sits) it measures over what
454
624
  * is there, down to MIN_REACH px; null when even that is missing.
455
625
  */
456
- function turn(pts, closed, i, r) {
626
+ function turn$1(pts, closed, i, r) {
457
627
  const p = pts[i];
458
628
  const reach = Math.min(r, room(pts.length, closed, i, -1), room(pts.length, closed, i, 1));
459
629
  if (reach < Math.min(r, MIN_REACH)) return null;
460
630
  const before = along(pts, closed, i, -reach);
461
631
  const after = along(pts, closed, i, reach);
462
632
  if (!before || !after) return null;
463
- const a = norm(sub(p, before));
464
- const b = norm(sub(after, p));
633
+ const a = norm(sub$1(p, before));
634
+ const b = norm(sub$1(after, p));
465
635
  return Math.acos(Math.max(-1, Math.min(1, dot(a, b)))) * 180 / Math.PI;
466
636
  }
467
637
  function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
@@ -470,7 +640,7 @@ function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
470
640
  const meet = new Array(n).fill(null);
471
641
  const sm = lightly(pts, closed);
472
642
  for (let i = 0; i < n; i++) {
473
- const wide = turn(pts, closed, i, R);
643
+ const wide = turn$1(pts, closed, i, R);
474
644
  if (wide === null || wide < cornerAngle) continue;
475
645
  const a = arm(sm, closed, i, -1);
476
646
  const b = arm(sm, closed, i, 1);
@@ -481,13 +651,14 @@ function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
481
651
  const x = intersect(a.at, add(a.at, a.dir), b.at, add(b.at, b.dir));
482
652
  const half = interior / 2 * Math.PI / 180;
483
653
  const reachOut = 1 / Math.sin(half) - 1;
484
- if (!x || dist(x, pts[i]) > Math.min(MAX_REACH_OUT, R / 2 + maxRounding * reachOut)) continue;
654
+ if (!x || dist$2(x, pts[i]) > Math.min(MAX_REACH_OUT, R / 2 + maxRounding * reachOut)) continue;
485
655
  let d = Infinity;
486
656
  for (let k = -6; k <= R; k++) {
487
657
  const j = closed ? ((i + k) % n + n) % n : i + k;
488
- if (j >= 0 && j < n) d = Math.min(d, dist(pts[j], x));
658
+ if (j >= 0 && j < n) d = Math.min(d, dist$2(pts[j], x));
489
659
  }
490
660
  if (d / Math.max(1e-6, reachOut) > maxRounding && d > .75) continue;
661
+ if (d > .5 / Math.tan(half) + 1) continue;
491
662
  score[i] = bend;
492
663
  meet[i] = x;
493
664
  }
@@ -507,7 +678,7 @@ function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
507
678
  at: meet[i]
508
679
  });
509
680
  }
510
- return corners.filter((c) => !corners.some((o) => o !== c && dist(o.at, c.at) < R && (score[o.index] > score[c.index] || score[o.index] === score[c.index] && o.index < c.index)));
681
+ return corners.filter((c) => !corners.some((o) => o !== c && dist$2(o.at, c.at) < R && (score[o.index] > score[c.index] || score[o.index] === score[c.index] && o.index < c.index)));
511
682
  }
512
683
  /** ±2-point moving average; an open chain keeps its ends. Same length and indices as the input. */
513
684
  function lightly(pts, closed) {
@@ -566,12 +737,12 @@ function arm(pts, closed, i, side) {
566
737
  x: Math.cos(theta),
567
738
  y: Math.sin(theta)
568
739
  };
569
- const outward = sub(sample[sample.length - 1], sample[0]);
740
+ const outward = sub$1(sample[sample.length - 1], sample[0]);
570
741
  if (dot(dir, outward) < 0) dir = mul(dir, -1);
571
742
  const rms = Math.sqrt(sample.reduce((s, p) => s + ((p.x - cx) * dir.y - (p.y - cy) * dir.x) ** 2, 0) / sample.length);
572
743
  const mid = Math.floor(sample.length / 2);
573
- const near = norm(sub(sample[mid], sample[0]));
574
- const far = norm(sub(sample[sample.length - 1], sample[mid]));
744
+ const near = norm(sub$1(sample[mid], sample[0]));
745
+ const far = norm(sub$1(sample[sample.length - 1], sample[mid]));
575
746
  const bend = Math.acos(Math.max(-1, Math.min(1, dot(near, far)))) * 180 / Math.PI;
576
747
  return {
577
748
  at: {
@@ -584,8 +755,8 @@ function arm(pts, closed, i, side) {
584
755
  };
585
756
  }
586
757
  function intersect(a0, a1, b0, b1) {
587
- const d1 = sub(a1, a0);
588
- const d2 = sub(b1, b0);
758
+ const d1 = sub$1(a1, a0);
759
+ const d2 = sub$1(b1, b0);
589
760
  const den = d1.x * d2.y - d1.y * d2.x;
590
761
  if (Math.abs(den) < 1e-9) return null;
591
762
  const t = ((b0.x - a0.x) * d2.y - (b0.y - a0.y) * d2.x) / den;
@@ -624,8 +795,8 @@ function smooth(run, loop, half) {
624
795
  const light = avg(() => Math.min(h, 2));
625
796
  const lat = (i) => light[loop ? (i % m + m) % m : Math.max(0, Math.min(m - 1, i))];
626
797
  const radiusAt = (i, span) => {
627
- const a = norm(sub(lat(i), lat(i - span)));
628
- const b = norm(sub(lat(i + span), lat(i)));
798
+ const a = norm(sub$1(lat(i), lat(i - span)));
799
+ const b = norm(sub$1(lat(i + span), lat(i)));
629
800
  const turn = Math.acos(Math.max(-1, Math.min(1, dot(a, b))));
630
801
  return turn > 1e-6 ? span / turn : 1e9;
631
802
  };
@@ -694,11 +865,12 @@ function fitMixed(s, tolerance, t1, t2, skipEnds) {
694
865
  let tFrom = t1;
695
866
  let fromAt = curve[0];
696
867
  for (const [i, j] of lines) {
697
- const isStub = (p, q) => dist(curve[p], curve[q]) < MIN_GAP && Math.abs(q - p) < 12;
698
- const short = i > from && isStub(from, i);
868
+ const isStub = (p, q) => dist$2(curve[p], curve[q]) < MIN_GAP && Math.abs(q - p) < 12;
869
+ const back = dot(tFrom, norm(sub$1(curve[j], curve[i]))) < 0;
870
+ const short = i > from && isStub(from, i) && !back;
699
871
  const a = short ? fromAt : curve[i];
700
872
  const b = curve[j];
701
- const dir = norm(sub(b, a));
873
+ const dir = norm(sub$1(b, a));
702
874
  if (i > from && !short) {
703
875
  const piece = curve.slice(from, i + 1);
704
876
  piece[0] = fromAt;
@@ -710,7 +882,7 @@ function fitMixed(s, tolerance, t1, t2, skipEnds) {
710
882
  fromAt = b;
711
883
  tFrom = dir;
712
884
  }
713
- if (from < n - 1 && out.length && dist(fromAt, curve[n - 1]) < MIN_GAP && n - 1 - from < 12) out[out.length - 1] = line(out[out.length - 1][0], curve[n - 1]);
885
+ if (from < n - 1 && out.length && dist$2(fromAt, curve[n - 1]) < MIN_GAP && n - 1 - from < 12) out[out.length - 1] = line(out[out.length - 1][0], curve[n - 1]);
714
886
  else if (from < n - 1) {
715
887
  const piece = curve.slice(from);
716
888
  piece[0] = fromAt;
@@ -731,7 +903,7 @@ function straights(exact, radius, tolerance) {
731
903
  const n = exact.length;
732
904
  const straight = (i, j) => {
733
905
  const a = exact[i];
734
- const d = norm(sub(exact[j], a));
906
+ const d = norm(sub$1(exact[j], a));
735
907
  let worst = 0;
736
908
  let bow = 0;
737
909
  for (let k = i + 1; k < j; k++) {
@@ -751,7 +923,7 @@ function straights(exact, radius, tolerance) {
751
923
  }
752
924
  while (j + 1 < n && straight(i, j + 1)) j++;
753
925
  const a = exact[i];
754
- const d = norm(sub(exact[j], a));
926
+ const d = norm(sub$1(exact[j], a));
755
927
  const off = (p) => Math.abs((p.x - a.x) * d.y - (p.y - a.y) * d.x);
756
928
  let s = i;
757
929
  let e = j;
@@ -761,17 +933,17 @@ function straights(exact, radius, tolerance) {
761
933
  const own = [...radius.slice(s + 1, e)].sort((x, y) => x - y)[Math.floor((e - s - 1) / 2)] ?? 1e9;
762
934
  const context = beside.length ? Math.min(own, Math.max(...beside)) : own;
763
935
  const needed = 2.5 * Math.sqrt(Math.min(1e6, context));
764
- if (e - s >= MIN_LINE && dist(exact[s], exact[e]) >= needed) found.push([s, e]);
936
+ if (e - s >= MIN_LINE && dist$2(exact[s], exact[e]) >= needed) found.push([s, e]);
765
937
  i = j;
766
938
  }
767
939
  return found;
768
940
  }
769
941
  function maxOffLine(run, a, b) {
770
- const d = sub(b, a);
942
+ const d = sub$1(b, a);
771
943
  const l = len(d);
772
944
  let worst = 0;
773
945
  for (const p of run) {
774
- const off = l < 1e-9 ? dist(p, a) : Math.abs((p.x - a.x) * d.y - (p.y - a.y) * d.x) / l;
946
+ const off = l < 1e-9 ? dist$2(p, a) : Math.abs((p.x - a.x) * d.y - (p.y - a.y) * d.x) / l;
775
947
  if (off > worst) worst = off;
776
948
  }
777
949
  return worst;
@@ -786,13 +958,13 @@ const curveTolerance = (tolerance, minRadius) => Math.min(tolerance, Math.max(.3
786
958
  function endTangent(run, atEnd) {
787
959
  const n = run.length;
788
960
  const k = Math.min(n - 1, R);
789
- return atEnd ? norm(sub(run[n - 1 - k], run[n - 1])) : norm(sub(run[k], run[0]));
961
+ return atEnd ? norm(sub$1(run[n - 1 - k], run[n - 1])) : norm(sub$1(run[k], run[0]));
790
962
  }
791
963
  /** Schneider's recursive fit: one cubic, or split at the worst point and recurse. */
792
964
  function fitRun(pts, t1, t2, tolerance, depth = 0, skipStart = 0, skipEnd = 0) {
793
965
  const n = pts.length;
794
966
  if (n === 2) {
795
- const d = dist(pts[0], pts[1]) / 3;
967
+ const d = dist$2(pts[0], pts[1]) / 3;
796
968
  return [[
797
969
  pts[0],
798
970
  add(pts[0], mul(t1, d)),
@@ -800,34 +972,38 @@ function fitRun(pts, t1, t2, tolerance, depth = 0, skipStart = 0, skipEnd = 0) {
800
972
  pts[1]
801
973
  ]];
802
974
  }
803
- if (Math.acos(Math.max(-1, Math.min(1, -dot(t1, t2)))) * 180 / Math.PI > MAX_SWEEP && n >= 8 && depth <= 12 && dist(pts[0], pts[n - 1]) >= 8) {
975
+ if (Math.acos(Math.max(-1, Math.min(1, -dot(t1, t2)))) * 180 / Math.PI > MAX_SWEEP && n >= 8 && depth <= 12 && dist$2(pts[0], pts[n - 1]) >= 8) {
804
976
  const mid = Math.floor(n / 2);
805
977
  const span = Math.min(3, mid, n - 1 - mid);
806
- const tm = norm(sub(pts[mid - span], pts[mid + span]));
978
+ const tm = norm(sub$1(pts[mid - span], pts[mid + span]));
807
979
  return [...fitRun(pts.slice(0, mid + 1), t1, tm, tolerance, depth + 1, skipStart, 0), ...fitRun(pts.slice(mid), mul(tm, -1), t2, tolerance, depth + 1, 0, skipEnd)];
808
980
  }
809
- let u = chordParams(pts);
810
- let bez = generate(pts, u, t1, t2);
981
+ let { u, arc } = chordParams(pts);
982
+ let bez = generate(pts, u, t1, t2, arc);
811
983
  let { error, split } = maxError(pts, bez, u, skipStart, skipEnd);
812
984
  const tol2 = tolerance * tolerance;
813
985
  if (error <= tol2) return [bez];
814
986
  if (error <= tol2 * 4) for (let it = 0; it < 4; it++) {
815
987
  u = u.map((ui, i) => newton(bez, pts[i], ui));
816
- bez = generate(pts, u, t1, t2);
988
+ bez = generate(pts, u, t1, t2, arc);
817
989
  ({error, split} = maxError(pts, bez, u, skipStart, skipEnd));
818
990
  if (error <= tol2) return [bez];
819
991
  }
820
992
  if (depth > 12 || n < 4) return [bez];
821
993
  split = Math.min(n - 2, Math.max(1, split));
822
994
  const span = Math.min(3, split, n - 1 - split);
823
- const tc = norm(sub(pts[split - span], pts[split + span]));
995
+ const tc = norm(sub$1(pts[split - span], pts[split + span]));
824
996
  return [...fitRun(pts.slice(0, split + 1), t1, tc, tolerance, depth + 1, skipStart, 0), ...fitRun(pts.slice(split), mul(tc, -1), t2, tolerance, depth + 1, 0, skipEnd)];
825
997
  }
998
+ /** Each point's share of the way along the run, and the run's length. */
826
999
  function chordParams(pts) {
827
1000
  const u = [0];
828
- for (let i = 1; i < pts.length; i++) u.push(u[i - 1] + dist(pts[i], pts[i - 1]));
829
- const total = u[u.length - 1] || 1;
830
- return u.map((x) => x / total);
1001
+ for (let i = 1; i < pts.length; i++) u.push(u[i - 1] + dist$2(pts[i], pts[i - 1]));
1002
+ const arc = u[u.length - 1];
1003
+ return {
1004
+ u: u.map((x) => x / (arc || 1)),
1005
+ arc
1006
+ };
831
1007
  }
832
1008
  const B = [
833
1009
  (t) => (1 - t) ** 3,
@@ -838,8 +1014,8 @@ const B = [
838
1014
  function pointAt(b, t) {
839
1015
  return add(add(mul(b[0], B[0](t)), mul(b[1], B[1](t))), add(mul(b[2], B[2](t)), mul(b[3], B[3](t))));
840
1016
  }
841
- /** Least-squares handle lengths along the given tangents (Schneider's GenerateBezier). */
842
- function generate(pts, u, t1, t2) {
1017
+ /** Least-squares handle lengths along the given tangents (Schneider's GenerateBezier); `arc` is the run's length. */
1018
+ function generate(pts, u, t1, t2, arc) {
843
1019
  const p0 = pts[0];
844
1020
  const p3 = pts[pts.length - 1];
845
1021
  let c00 = 0;
@@ -853,15 +1029,15 @@ function generate(pts, u, t1, t2) {
853
1029
  c00 += dot(a1, a1);
854
1030
  c01 += dot(a1, a2);
855
1031
  c11 += dot(a2, a2);
856
- const tmp = sub(pts[i], add(mul(p0, B[0](u[i]) + B[1](u[i])), mul(p3, B[2](u[i]) + B[3](u[i]))));
1032
+ const tmp = sub$1(pts[i], add(mul(p0, B[0](u[i]) + B[1](u[i])), mul(p3, B[2](u[i]) + B[3](u[i]))));
857
1033
  x0 += dot(a1, tmp);
858
1034
  x1 += dot(a2, tmp);
859
1035
  }
860
1036
  const det = c00 * c11 - c01 * c01;
861
1037
  let alpha1 = Math.abs(det) > 1e-12 ? (x0 * c11 - x1 * c01) / det : 0;
862
1038
  let alpha2 = Math.abs(det) > 1e-12 ? (c00 * x1 - c01 * x0) / det : 0;
863
- const seg = dist(p0, p3);
864
- if (alpha1 < 1e-6 * seg || alpha2 < 1e-6 * seg) alpha1 = alpha2 = seg / 3;
1039
+ const seg = dist$2(p0, p3);
1040
+ if (alpha1 < 1e-6 * seg || alpha2 < 1e-6 * seg || alpha1 > arc || alpha2 > arc) alpha1 = alpha2 = seg / 3;
865
1041
  return [
866
1042
  p0,
867
1043
  add(p0, mul(t1, alpha1)),
@@ -891,62 +1067,197 @@ function maxError(pts, b, u, skipStart = 0, skipEnd = 0) {
891
1067
  /** One Newton–Raphson step towards the parameter of the point on `b` nearest `p`. */
892
1068
  function newton(b, p, u) {
893
1069
  const d1 = [
894
- mul(sub(b[1], b[0]), 3),
895
- mul(sub(b[2], b[1]), 3),
896
- mul(sub(b[3], b[2]), 3)
1070
+ mul(sub$1(b[1], b[0]), 3),
1071
+ mul(sub$1(b[2], b[1]), 3),
1072
+ mul(sub$1(b[3], b[2]), 3)
897
1073
  ];
898
- const d2 = [mul(sub(d1[1], d1[0]), 2), mul(sub(d1[2], d1[1]), 2)];
1074
+ const d2 = [mul(sub$1(d1[1], d1[0]), 2), mul(sub$1(d1[2], d1[1]), 2)];
899
1075
  const q = pointAt(b, u);
900
1076
  const q1 = add(add(mul(d1[0], (1 - u) ** 2), mul(d1[1], 2 * u * (1 - u))), mul(d1[2], u * u));
901
1077
  const q2 = add(mul(d2[0], 1 - u), mul(d2[1], u));
902
- const num = dot(sub(q, p), q1);
903
- const den = dot(q1, q1) + dot(sub(q, p), q2);
1078
+ const num = dot(sub$1(q, p), q1);
1079
+ const den = dot(q1, q1) + dot(sub$1(q, p), q2);
904
1080
  if (Math.abs(den) < 1e-12) return u;
905
1081
  return Math.min(1, Math.max(0, u - num / den));
906
1082
  }
907
1083
  //#endregion
908
1084
  //#region src/palette.ts
909
- function peakPalette(rgba, maxColors, { minDistance = .07, minShare = .002 } = {}) {
910
- const bins = /* @__PURE__ */ new Map();
911
- let opaque = 0;
912
- for (let i = 0; i < rgba.length; i += 4) {
913
- if (rgba[i + 3] < 128) continue;
914
- const r = rgba[i];
915
- const g = rgba[i + 1];
916
- const b = rgba[i + 2];
917
- const key = r >> 3 << 10 | g >> 3 << 5 | b >> 3;
918
- const bin = bins.get(key);
919
- if (bin) {
920
- bin.n++;
921
- bin.r += r;
922
- bin.g += g;
923
- bin.b += b;
924
- } else bins.set(key, {
925
- n: 1,
926
- r,
927
- g,
928
- b
929
- });
930
- opaque++;
931
- }
932
- const sorted = [...bins.values()].sort((a, b) => b.n - a.n);
1085
+ function peakPalette(rgba, maxColors, { minDistance = .07, minShare = .002, minDetail = 5e-4, width, minTint = .02, minFlat = .001 } = {}) {
1086
+ const bins = histogram(rgba);
1087
+ for (let i = 0; i < rgba.length; i += 4) if (rgba[i + 3] >= 128) bins.add(i);
1088
+ const opaque = bins.total;
1089
+ const flat = width ? flatBins(rgba, width) : null;
1090
+ const items = bins.keys.map((key) => {
1091
+ const rgb = bins.mean(key);
1092
+ return {
1093
+ n: bins.n[key],
1094
+ flat: flat?.n[key] ?? 0,
1095
+ rgb,
1096
+ lab: oklab(rgb),
1097
+ weight: 0,
1098
+ flatWeight: 0,
1099
+ peak: true
1100
+ };
1101
+ });
1102
+ weigh(items, minDistance / 2);
1103
+ const sorted = items.filter((it) => it.peak).sort((a, b) => b.weight - a.weight || b.n - a.n);
933
1104
  const picked = [];
934
- for (const bin of sorted) {
1105
+ for (const it of sorted) {
935
1106
  if (picked.length >= maxColors) break;
936
- if (bin.n / opaque < minShare && picked.length > 0) break;
937
- const rgb = [
938
- bin.r / bin.n,
939
- bin.g / bin.n,
940
- bin.b / bin.n
941
- ];
942
- const lab = oklab(rgb);
943
- if (picked.every((p) => distance(p.lab, lab) >= minDistance)) picked.push({
944
- lab,
945
- rgb
1107
+ const share = it.weight / opaque;
1108
+ if (share < minDetail && picked.length > 0) break;
1109
+ if (!picked.every((p) => distance(p.lab, it.lab) >= minDistance)) continue;
1110
+ if ((share < minShare || flat !== null && share < EDGE_SHARE && it.flatWeight < EDGE_FLAT * it.weight) && isBlend(it.rgb, it.lab, picked, minDistance)) continue;
1111
+ picked.push({
1112
+ lab: it.lab,
1113
+ rgb: it.rgb
946
1114
  });
947
1115
  }
1116
+ if (flat && picked.length < maxColors) picked.push(...flatTints(flat, opaque, picked, maxColors - picked.length, minTint, minFlat));
948
1117
  return picked.map((p) => toHex(p.rgb));
949
1118
  }
1119
+ /** Below this share of flat pixels, a colour is an edge's, not a fill's. */
1120
+ const EDGE_FLAT = .05;
1121
+ /**
1122
+ * But only below this share of the image: 1 px grey rules or a dithered fill
1123
+ * are never flat either, and at 8% of a logo they are a colour of their own.
1124
+ */
1125
+ const EDGE_SHARE = .02;
1126
+ /**
1127
+ * Pixels binned at 5 bits per channel (a 15-bit key), with each bin's colour
1128
+ * sums for its true mean. Typed arrays, not a Map: with the flat pass this
1129
+ * took a third less time on a 2048 px logo. `keys`
1130
+ * lists the used bins in the order first seen, as a Map would iterate them.
1131
+ */
1132
+ function histogram(rgba) {
1133
+ const n = /* @__PURE__ */ new Uint32Array(32768);
1134
+ const sum = /* @__PURE__ */ new Float64Array(98304);
1135
+ const keys = [];
1136
+ const bins = {
1137
+ n,
1138
+ keys,
1139
+ total: 0,
1140
+ add(i) {
1141
+ const key = rgba[i] >> 3 << 10 | rgba[i + 1] >> 3 << 5 | rgba[i + 2] >> 3;
1142
+ if (!n[key]++) keys.push(key);
1143
+ sum[key * 3] += rgba[i];
1144
+ sum[key * 3 + 1] += rgba[i + 1];
1145
+ sum[key * 3 + 2] += rgba[i + 2];
1146
+ bins.total++;
1147
+ },
1148
+ mean: (key) => [
1149
+ sum[key * 3] / n[key],
1150
+ sum[key * 3 + 1] / n[key],
1151
+ sum[key * 3 + 2] / n[key]
1152
+ ]
1153
+ };
1154
+ return bins;
1155
+ }
1156
+ /**
1157
+ * The image's flat pixels, binned as peakPalette bins them. A pixel is flat
1158
+ * when its four neighbours are within 8 of it in every channel: inside a fill,
1159
+ * never on an anti-aliased edge or in JPEG ringing.
1160
+ */
1161
+ function flatBins(rgba, w) {
1162
+ const h = Math.floor(rgba.length / 4 / w);
1163
+ const bins = histogram(rgba);
1164
+ const near = new Uint8Array(w * h);
1165
+ const close = (i, j) => rgba[i + 3] >= 128 && rgba[j + 3] >= 128 && Math.abs(rgba[i] - rgba[j]) <= 8 && Math.abs(rgba[i + 1] - rgba[j + 1]) <= 8 && Math.abs(rgba[i + 2] - rgba[j + 2]) <= 8;
1166
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
1167
+ const p = y * w + x;
1168
+ near[p] = (x < w - 1 && close(p * 4, p * 4 + 4) ? 1 : 0) | (y < h - 1 && close(p * 4, (p + w) * 4) ? 2 : 0);
1169
+ }
1170
+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
1171
+ const p = y * w + x;
1172
+ if ((near[p] & 3) === 3 && near[p - 1] & 1 && near[p - w] & 2) bins.add(p * 4);
1173
+ }
1174
+ return bins;
1175
+ }
1176
+ /**
1177
+ * Each item's weight (the pixels of every bin within `radius` of it in OKLab)
1178
+ * and flat weight, and whether it is a local peak (no bin within
1179
+ * `radius` has more). A grid of `radius` cells keeps it near linear.
1180
+ */
1181
+ function weigh(items, radius) {
1182
+ radius = Math.max(radius, .001);
1183
+ const cell = (v) => Math.floor(v / radius);
1184
+ const grid = /* @__PURE__ */ new Map();
1185
+ for (const it of items) {
1186
+ const k = `${cell(it.lab[0])},${cell(it.lab[1])},${cell(it.lab[2])}`;
1187
+ const list = grid.get(k);
1188
+ if (list) list.push(it);
1189
+ else grid.set(k, [it]);
1190
+ }
1191
+ for (const it of items) {
1192
+ const [cl, ca, cb] = it.lab.map(cell);
1193
+ 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) {
1194
+ it.weight += o.n;
1195
+ it.flatWeight += o.flat;
1196
+ if (o.n > it.n) it.peak = false;
1197
+ }
1198
+ }
1199
+ }
1200
+ /**
1201
+ * Pale tints: flat colours at least `minTint` from every colour picked, each
1202
+ * flat over at least `minFlat` of the image, heaviest first. On a
1203
+ * sinking-ship illustration (blue outlines on white, the ship and moon filled
1204
+ * with pale blues) this found the three fills and nothing else.
1205
+ */
1206
+ /**
1207
+ * Tints are pale (OKLab lightness): a photo's smooth sky or skin is flat too,
1208
+ * and its dark shades filled Illustration's 16 colours with near-copies that
1209
+ * doubled the SVG. The fills tints exist for are light washes behind ink.
1210
+ */
1211
+ const TINT_LIGHTNESS = .85;
1212
+ function flatTints(flat, opaque, picked, room, minTint, minFlat) {
1213
+ const items = flat.keys.map((key) => {
1214
+ const rgb = flat.mean(key);
1215
+ return {
1216
+ n: flat.n[key],
1217
+ flat: flat.n[key],
1218
+ rgb,
1219
+ lab: oklab(rgb),
1220
+ weight: 0,
1221
+ flatWeight: 0,
1222
+ peak: true
1223
+ };
1224
+ });
1225
+ weigh(items, minTint / 2);
1226
+ const out = [];
1227
+ const tint = (it) => it.peak && it.lab[0] >= TINT_LIGHTNESS && it.weight >= minFlat * opaque;
1228
+ for (const it of items.filter(tint).sort((a, b) => b.weight - a.weight)) {
1229
+ if (out.length >= room) break;
1230
+ if ([...picked, ...out].every((p) => distance(p.lab, it.lab) >= minTint)) out.push({
1231
+ lab: it.lab,
1232
+ rgb: it.rgb
1233
+ });
1234
+ }
1235
+ return out;
1236
+ }
1237
+ /**
1238
+ * Whether a colour lies near the line between two picked colours, mixed as a
1239
+ * renderer mixes them (in sRGB): the nearest mix is within `tolerance` (OKLab).
1240
+ */
1241
+ function isBlend(rgb, lab, picked, tolerance) {
1242
+ for (let i = 0; i < picked.length; i++) for (let j = i + 1; j < picked.length; j++) {
1243
+ const a = picked[i].rgb;
1244
+ const b = picked[j].rgb;
1245
+ const d = [
1246
+ b[0] - a[0],
1247
+ b[1] - a[1],
1248
+ b[2] - a[2]
1249
+ ];
1250
+ const len = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
1251
+ if (!len) continue;
1252
+ 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));
1253
+ if (distance(oklab([
1254
+ a[0] + t * d[0],
1255
+ a[1] + t * d[1],
1256
+ a[2] + t * d[2]
1257
+ ]), lab) < tolerance) return true;
1258
+ }
1259
+ return false;
1260
+ }
950
1261
  function oklab([r, g, b]) {
951
1262
  const lin = (c) => {
952
1263
  c /= 255;
@@ -1105,6 +1416,12 @@ function exactPalette(rgba, maxColors) {
1105
1416
  }
1106
1417
  return [...counts].sort((a, b) => b[1] - a[1] || a[0] - b[0]).slice(0, Math.max(1, maxColors)).map(([k]) => `#${k.toString(16).padStart(6, "0")}`);
1107
1418
  }
1419
+ /** '#rrggbb' as [r, g, b]. */
1420
+ const hexToRgb = (hex) => [
1421
+ parseInt(hex.slice(1, 3), 16),
1422
+ parseInt(hex.slice(3, 5), 16),
1423
+ parseInt(hex.slice(5, 7), 16)
1424
+ ];
1108
1425
  //#endregion
1109
1426
  //#region src/path.ts
1110
1427
  const TOKEN = /[MmLlHhVvCcSsQqTtAaZz]|[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
@@ -1305,11 +1622,11 @@ function close(sub) {
1305
1622
  nodes.pop();
1306
1623
  }
1307
1624
  }
1308
- const num = (n) => {
1625
+ const num$1 = (n) => {
1309
1626
  const r = Math.round(n * 1e3) / 1e3;
1310
1627
  return Object.is(r, -0) ? "0" : String(r);
1311
1628
  };
1312
- const pt = (p) => `${num(p.x)} ${num(p.y)}`;
1629
+ const pt = (p) => `${num$1(p.x)} ${num$1(p.y)}`;
1313
1630
  function segment(a, b) {
1314
1631
  return a.out || b.in ? `C${pt(a.out ?? a)} ${pt(b.in ?? b)} ${pt(b)}` : `L${pt(b)}`;
1315
1632
  }
@@ -1339,181 +1656,1904 @@ function mapPoints(subs, f) {
1339
1656
  }))
1340
1657
  }));
1341
1658
  }
1342
- //#endregion
1343
- //#region src/inlay.ts
1344
- /**
1345
- * Inlay, our shared-edge tracer: every preset, from logos to photos.
1346
- * Like inlaid wood, every piece is cut to fit its neighbours exactly.
1347
- *
1348
- * VTracer traces every colour region on its own, so an edge between two
1349
- * regions is traced twice. Fitting the two copies separately leaves hairline
1350
- * gaps and slivers; leaving them to VTracer's spline fitter gives the wobbly
1351
- * lines and rounded corners this replaces. Instead:
1352
- *
1353
- * 1. Label every pixel with a palette colour (or ink / paper for line art).
1354
- * Anti-aliased pixels, which sit between two colours, take the closest
1355
- * colour *among their neighbours*, so an edge between red and blue never
1356
- * grows a one-pixel purple sliver.
1357
- * 2. Merge specks smaller than `speckle`² pixels into whatever surrounds them.
1358
- * 3. Walk the cracks between differently labelled pixels. Where three or more
1359
- * regions meet (or two meet diagonally) is a junction; every boundary
1360
- * between two junctions is one chain, with one region on each side.
1361
- * 4. Fit each chain once (src/lib/fit.ts): corners first, then straight lines
1362
- * where they fit and curves where they don't.
1363
- * 5. Build each region's outline from its chains, reversing the ones it sees
1364
- * from the other side. Neighbours share the exact same fitted edge: no
1365
- * gaps, no overlaps, which is also what a vinyl cutter wants.
1366
- *
1367
- * Regions are 4-connected, so two pixels touching only at a corner are
1368
- * separate shapes, and each region is one <path> (its outline plus its holes,
1369
- * wound oppositely so the default nonzero fill rule cuts the holes). With
1370
- * `stacked`, a region keeps only its outline (and any holes onto
1371
- * transparency), and paint order does the rest.
1372
- */
1373
- const VOID = -1;
1374
- /** The trace as an SVG document. */
1375
- function toSvg(r) {
1376
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${r.width}" height="${r.height}" viewBox="0 0 ${r.width} ${r.height}">\n${r.paths.map((p) => `<path d="${p.d}" fill="${p.fill}"/>`).join("\n")}\n</svg>\n`;
1659
+ const sub = (a, b) => ({
1660
+ x: a.x - b.x,
1661
+ y: a.y - b.y
1662
+ });
1663
+ const dist$1 = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
1664
+ const unit = (a) => {
1665
+ const l = Math.hypot(a.x, a.y);
1666
+ return l > 1e-9 ? {
1667
+ x: a.x / l,
1668
+ y: a.y / l
1669
+ } : null;
1670
+ };
1671
+ /** The direction a run of cubics leaves its first point in. */
1672
+ function startDir(cubics) {
1673
+ const [a, b, c, d] = cubics[0];
1674
+ return unit(sub(b, a)) ?? unit(sub(c, a)) ?? unit(sub(d, a));
1377
1675
  }
1378
- /** Trace to an SVG string; `trace` gives the shapes as data. */
1379
- const traceInlay = (rgba, w, h, o) => toSvg(trace(rgba, w, h, o));
1380
- /**
1381
- * Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
1382
- * into filled shapes that share their edges exactly.
1383
- */
1384
- function trace(rgba, w, h, o) {
1385
- const { labels, colors, drawn } = o.mode === "palette" ? labelPalette(rgba, w, h, o.palette) : labelBinary(rgba, w, h, o.threshold);
1386
- if (o.mode === "palette" && o.merge) mergeLabels(labels, colors, o.merge);
1387
- if (!o.pixels) despur(labels, w, h);
1388
- mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
1389
- const { comp, compLabel, compArea } = components(labels, w, h, (l) => drawn[l]);
1390
- const chains = findChains(comp, w, h);
1391
- const byComp = /* @__PURE__ */ new Map();
1392
- for (const c of chains) {
1393
- const cubics = o.pixels ? staircase(c.pts, c.closed) : fitChain(c.pts, c.closed, o);
1394
- if (!cubics.length) continue;
1395
- if (c.left !== VOID) addOriented(byComp, c.left, {
1396
- ...c,
1397
- cubics,
1398
- reversed: false
1399
- });
1400
- if (c.right !== VOID) addOriented(byComp, c.right, {
1401
- ...c,
1402
- cubics: reverse(cubics),
1403
- reversed: true
1404
- });
1405
- }
1406
- const voids = o.stacked ? voidSeeds(comp, w, h) : [];
1407
- const shapes = [];
1408
- for (const [id, chains] of byComp) {
1409
- let loops = assemble(chains);
1410
- if (!loops.length) continue;
1411
- let area = compArea[id];
1412
- if (o.stacked) {
1413
- const outer = loops.reduce((a, b) => Math.abs(b.area) > Math.abs(a.area) ? b : a);
1414
- loops = loops.filter((l) => l === outer || l.touchesVoid || voids.some((p) => encloses(l.pts, p)));
1415
- area = Math.abs(outer.area);
1416
- }
1417
- shapes.push({
1418
- subs: loops.map((l) => l.sub),
1419
- fill: colors[compLabel[id]],
1420
- area
1421
- });
1676
+ /** The direction a run of cubics arrives at its last point in. */
1677
+ function endDir(cubics) {
1678
+ const [a, b, c, d] = cubics[cubics.length - 1];
1679
+ return unit(sub(d, c)) ?? unit(sub(d, b)) ?? unit(sub(d, a));
1680
+ }
1681
+ /** How far (degrees) an outline arriving along `u` turns to leave along `v`: 0 is straight on. */
1682
+ function turn(u, v) {
1683
+ return Math.acos(Math.max(-1, Math.min(1, u.x * v.x + u.y * v.y))) * 180 / Math.PI;
1684
+ }
1685
+ /** Whether a cubic's end is straight: its last (or first) cubic is flat. */
1686
+ const straightEnd = (cubics, atEnd) => isFlat(cubics[atEnd ? cubics.length - 1 : 0]);
1687
+ /** The least-squares circle through `pts` (Kåsa's algebraic fit), or null if they are near a line. */
1688
+ function fitCircle(pts) {
1689
+ if (pts.length < 5) return null;
1690
+ let mx = 0;
1691
+ let my = 0;
1692
+ for (const p of pts) mx += p.x, my += p.y;
1693
+ mx /= pts.length;
1694
+ my /= pts.length;
1695
+ let suu = 0;
1696
+ let suv = 0;
1697
+ let svv = 0;
1698
+ let suuu = 0;
1699
+ let svvv = 0;
1700
+ let suvv = 0;
1701
+ let svuu = 0;
1702
+ for (const p of pts) {
1703
+ const u = p.x - mx;
1704
+ const v = p.y - my;
1705
+ suu += u * u;
1706
+ suv += u * v;
1707
+ svv += v * v;
1708
+ suuu += u * u * u;
1709
+ svvv += v * v * v;
1710
+ suvv += u * v * v;
1711
+ svuu += v * u * u;
1422
1712
  }
1423
- shapes.sort((a, b) => b.area - a.area);
1713
+ const det = suu * svv - suv * suv;
1714
+ if (Math.abs(det) < 1e-9) return null;
1715
+ const bu = (suuu + suvv) / 2;
1716
+ const bv = (svvv + svuu) / 2;
1717
+ const uc = (bu * svv - bv * suv) / det;
1718
+ const vc = (bv * suu - bu * suv) / det;
1719
+ const r = Math.sqrt(uc * uc + vc * vc + (suu + svv) / pts.length);
1424
1720
  return {
1425
- width: w,
1426
- height: h,
1427
- paths: shapes.map((x) => ({
1428
- d: serializePath(x.subs),
1429
- fill: x.fill
1430
- }))
1721
+ cx: uc + mx,
1722
+ cy: vc + my,
1723
+ r
1431
1724
  };
1432
1725
  }
1433
- /**
1434
- * A chain as its exact pixel boundary: a line between each pair of turns.
1435
- * The points are pixel corners about a pixel apart, so a run of them in one
1436
- * direction is one straight edge. A closed loop starts at a turn, so its seam
1437
- * isn't a node in the middle of an edge.
1438
- */
1439
- function staircase(pts, closed) {
1440
- const n = pts.length;
1441
- if (n < 2) return [];
1442
- const dir = (a, b) => `${Math.sign(b.x - a.x)},${Math.sign(b.y - a.y)}`;
1443
- const isTurn = (i) => {
1444
- const a = pts[(i - 1 + n) % n];
1445
- const b = pts[i];
1446
- const c = pts[(i + 1) % n];
1447
- return dir(a, b) !== dir(b, c);
1448
- };
1449
- const keep = [];
1450
- if (closed) {
1451
- const start = pts.findIndex((_, i) => isTurn(i));
1452
- if (start < 0) return [];
1453
- for (let k = 0; k < n; k++) {
1454
- const i = (start + k) % n;
1455
- if (isTurn(i)) keep.push(pts[i]);
1456
- }
1457
- keep.push(keep[0]);
1458
- } else {
1459
- keep.push(pts[0]);
1460
- for (let i = 1; i < n - 1; i++) if (isTurn(i)) keep.push(pts[i]);
1461
- keep.push(pts[n - 1]);
1462
- }
1726
+ /** An arc of `c` from p0 to p1, leaving p0 along `t0`, as cubics of at most a quarter turn each. */
1727
+ function arc(c, p0, p1, t0) {
1728
+ const a0 = Math.atan2(p0.y - c.cy, p0.x - c.cx);
1729
+ const a1 = Math.atan2(p1.y - c.cy, p1.x - c.cx);
1730
+ const dir = -Math.sin(a0) * t0.x + Math.cos(a0) * t0.y >= 0 ? 1 : -1;
1731
+ let sweep = dir * (a1 - a0);
1732
+ while (sweep <= 0) sweep += 2 * Math.PI;
1733
+ while (sweep > 2 * Math.PI) sweep -= 2 * Math.PI;
1734
+ const n = Math.max(1, Math.ceil(sweep / (Math.PI / 2) - 1e-6));
1735
+ const step = dir * sweep / n;
1736
+ const k = 4 / 3 * Math.tan(step / 4);
1737
+ const at = (a) => ({
1738
+ x: c.cx + c.r * Math.cos(a),
1739
+ y: c.cy + c.r * Math.sin(a)
1740
+ });
1463
1741
  const out = [];
1464
- for (let i = 1; i < keep.length; i++) {
1465
- const a = keep[i - 1];
1466
- const b = keep[i];
1742
+ for (let i = 0; i < n; i++) {
1743
+ const s = a0 + i * step;
1744
+ const e = s + step;
1745
+ const ps = i === 0 ? p0 : at(s);
1746
+ const pe = i === n - 1 ? p1 : at(e);
1467
1747
  out.push([
1468
- a,
1748
+ ps,
1469
1749
  {
1470
- x: a.x + (b.x - a.x) / 3,
1471
- y: a.y + (b.y - a.y) / 3
1750
+ x: ps.x - k * c.r * Math.sin(s),
1751
+ y: ps.y + k * c.r * Math.cos(s)
1472
1752
  },
1473
1753
  {
1474
- x: a.x + (b.x - a.x) * 2 / 3,
1475
- y: a.y + (b.y - a.y) * 2 / 3
1754
+ x: pe.x + k * c.r * Math.sin(e),
1755
+ y: pe.y - k * c.r * Math.cos(e)
1476
1756
  },
1477
- b
1757
+ pe
1478
1758
  ]);
1479
1759
  }
1480
1760
  return out;
1481
1761
  }
1482
- /** Relabel merged colours as their targets, following chains, in place. */
1483
- function mergeLabels(labels, colors, merge) {
1484
- const index = new Map(colors.map((c, i) => [c, i]));
1485
- const remap = colors.map((c, i) => {
1486
- let to = c;
1487
- let at = i;
1488
- const seen = /* @__PURE__ */ new Set();
1489
- while (merge[to] && !seen.has(to)) {
1490
- seen.add(to);
1491
- to = merge[to].toLowerCase();
1492
- const k = index.get(to);
1493
- if (k !== void 0) at = k;
1494
- }
1495
- return at;
1496
- });
1497
- if (remap.every((t, i) => t === i)) return;
1498
- for (let i = 0; i < labels.length; i++) labels[i] = remap[labels[i]];
1762
+ /** Where the line on from p0 along t0 meets the line back from p1 along t1, if ahead of both. */
1763
+ function meet(p0, t0, p1, t1) {
1764
+ const den = t0.x * t1.y - t0.y * t1.x;
1765
+ if (Math.abs(den) < .05) return null;
1766
+ const d = sub(p1, p0);
1767
+ const s = (d.x * t1.y - d.y * t1.x) / den;
1768
+ const u = (t0.x * d.y - t0.y * d.x) / den;
1769
+ const span = dist$1(p0, p1);
1770
+ if (s < .5 || u < .5 || s > 4 * span + 4 || u > 4 * span + 4) return null;
1771
+ return {
1772
+ x: p0.x + s * t0.x,
1773
+ y: p0.y + s * t0.y
1774
+ };
1499
1775
  }
1500
- function labelPalette(rgba, w, h, palette) {
1501
- const pal = palette.map(hexToRgb);
1502
- const labs = pal.map(oklab);
1503
- const n = w * h;
1504
- const labels = new Int32Array(n);
1505
- const unsure = new Uint8Array(n);
1506
- const cache = /* @__PURE__ */ new Map();
1507
- const transparent = pal.length;
1508
- for (let i = 0; i < n; i++) {
1509
- const r = rgba[i * 4];
1510
- const g = rgba[i * 4 + 1];
1511
- const b = rgba[i * 4 + 2];
1512
- if (rgba[i * 4 + 3] < 128) {
1513
- labels[i] = transparent;
1514
- continue;
1776
+ /** How a circle fits `pts`: RMS and worst distance from it. */
1777
+ function circleError(c, pts) {
1778
+ let sq = 0;
1779
+ let worst = 0;
1780
+ for (const p of pts) {
1781
+ const e = Math.abs(Math.hypot(p.x - c.cx, p.y - c.cy) - c.r);
1782
+ sq += e * e;
1783
+ worst = Math.max(worst, e);
1784
+ }
1785
+ return {
1786
+ rms: Math.sqrt(sq / pts.length),
1787
+ worst
1788
+ };
1789
+ }
1790
+ /** The angle (radians) the points span round a centre: 2π less the widest gap between them. */
1791
+ function spanned(c, pts) {
1792
+ const a = pts.map((p) => Math.atan2(p.y - c.cy, p.x - c.cx)).sort((x, y) => x - y);
1793
+ let gap = a[0] + 2 * Math.PI - a[a.length - 1];
1794
+ for (let i = 1; i < a.length; i++) gap = Math.max(gap, a[i] - a[i - 1]);
1795
+ return 2 * Math.PI - gap;
1796
+ }
1797
+ /** Points along cubics, about a pixel apart. */
1798
+ function sample(cubics) {
1799
+ const out = [];
1800
+ for (const c of cubics) {
1801
+ const n = Math.max(2, Math.ceil(dist$1(c[0], c[1]) + dist$1(c[1], c[2]) + dist$1(c[2], c[3])));
1802
+ for (let i = 0; i < n; i++) out.push(pointAt(c, i / n));
1803
+ }
1804
+ return out;
1805
+ }
1806
+ /** A circle must fit the visible outline this closely (px)... */
1807
+ const CIRCLE_RMS = .5;
1808
+ const CIRCLE_WORST = 1.5;
1809
+ /** ...and the visible outline span at least this much of it (radians). */
1810
+ const CIRCLE_SPAN = Math.PI / 2;
1811
+ /** A completion may stray outside the shapes in front by this share of its length (fitting error near the ends). */
1812
+ const STRAY = .05;
1813
+ /**
1814
+ * The hidden part of an outline, from p0 (where it goes under a shape in
1815
+ * front, arriving along t0) to p1 (where it comes out, leaving along t1), or
1816
+ * null if no continuation stays hidden. `visible` is the rest of the outline;
1817
+ * `straight0`/`straight1` say whether it is straight where it goes under and
1818
+ * comes out; `hidden(p)` whether a point is under a shape in front.
1819
+ */
1820
+ function complete(p0, t0, p1, t1, visible, straight0, straight1, hidden) {
1821
+ const candidates = [];
1822
+ if (!straight0 && !straight1) {
1823
+ const c = fitCircle(visible);
1824
+ if (c && c.r > 2) {
1825
+ const e = circleError(c, visible);
1826
+ const ends = Math.max(Math.abs(dist$1(p0, {
1827
+ x: c.cx,
1828
+ y: c.cy
1829
+ }) - c.r), Math.abs(dist$1(p1, {
1830
+ x: c.cx,
1831
+ y: c.cy
1832
+ }) - c.r));
1833
+ if (e.rms < CIRCLE_RMS && e.worst < CIRCLE_WORST && ends < CIRCLE_WORST && spanned(c, visible) >= CIRCLE_SPAN) candidates.push(arc(c, p0, p1, t0));
1515
1834
  }
1516
- const key = r << 16 | g << 8 | b;
1835
+ }
1836
+ if (straight0 && straight1) {
1837
+ const q = meet(p0, t0, p1, t1);
1838
+ if (q) candidates.push([line(p0, q), line(q, p1)]);
1839
+ else if (turn(t0, t1) < 20 && turn(t0, unit(sub(p1, p0)) ?? t0) < 20) candidates.push([line(p0, p1)]);
1840
+ }
1841
+ const l = dist$1(p0, p1) / 3;
1842
+ if (l > 0) candidates.push([[
1843
+ p0,
1844
+ {
1845
+ x: p0.x + t0.x * l,
1846
+ y: p0.y + t0.y * l
1847
+ },
1848
+ {
1849
+ x: p1.x - t1.x * l,
1850
+ y: p1.y - t1.y * l
1851
+ },
1852
+ p1
1853
+ ]]);
1854
+ for (const c of candidates) {
1855
+ if (!c) continue;
1856
+ const pts = sample(c);
1857
+ let out = 0;
1858
+ for (const p of pts) if (!hidden(p)) out++;
1859
+ if (out <= STRAY * pts.length) return c;
1860
+ }
1861
+ return null;
1862
+ }
1863
+ //#endregion
1864
+ //#region src/skeleton.ts
1865
+ /**
1866
+ * Skeleton strokes: thin ink to a one-pixel skeleton and fit it as strokes
1867
+ * down the middle. Centerline traces a whole drawing this way; outline art
1868
+ * (`strokes` in the colour tracer) traces just its thin lines.
1869
+ *
1870
+ * 1. Thin the ink to a one-pixel skeleton (Zhang and Suen, "A fast parallel
1871
+ * algorithm for thinning digital patterns", CACM 1984).
1872
+ * 2. Measure the stroke width: the ink's area over the skeleton's length.
1873
+ * 3. Prune spurs: short branches that thinning grows from bumps in the
1874
+ * outline, anything shorter than the stroke is wide.
1875
+ * 4. Walk the skeleton into chains between ends and junctions. Thinning bends
1876
+ * the skeleton toward each junction, so within a stroke width of one the
1877
+ * arms are dropped and drawn straight on to where their own lines meet.
1878
+ * Where strokes cross or branch, chains that carry on in the same
1879
+ * direction are joined, so a plotter lifts its pen less.
1880
+ * 5. Fit each chain with the same curve fitter as outlines.
1881
+ */
1882
+ /** 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. */
1883
+ function skeletonStrokes(ink, w, h, o, thinned) {
1884
+ const skel = thinned ?? thin(ink, w, h);
1885
+ const measured = strokeWidthOf(skel, ink, w);
1886
+ prune(skel, w, h, Math.max(3, Math.round(measured)));
1887
+ const subs = [];
1888
+ for (const c of joinStraight(refitJunctions(walk(skel, w, h), measured))) {
1889
+ if (c.pts.length < 2) continue;
1890
+ const cubics = c.pts.length < 4 ? polyline(c.pts) : fitChain(c.pts, c.closed, {
1891
+ tolerance: o.tolerance,
1892
+ cornerAngle: o.cornerAngle,
1893
+ smoothing: 6
1894
+ });
1895
+ if (cubics.length) subs.push(toSubpath$1(cubics, c.closed));
1896
+ }
1897
+ return {
1898
+ subs,
1899
+ measured
1900
+ };
1901
+ }
1902
+ /**
1903
+ * The stroke width: the ink's area over the skeleton's length. (The distance
1904
+ * transform's median is out by a pixel on even widths, where the skeleton
1905
+ * can't sit on the middle.)
1906
+ */
1907
+ function strokeWidthOf(skel, ink, w) {
1908
+ let area = 0;
1909
+ let length = 0;
1910
+ for (let i = 0; i < ink.length; i++) {
1911
+ area += ink[i];
1912
+ if (!skel[i]) continue;
1913
+ const x = i % w;
1914
+ if (x + 1 < w && skel[i + 1]) length += 1;
1915
+ if (skel[i + w]) length += 1;
1916
+ if (x + 1 < w && skel[i + w + 1]) length += Math.SQRT2;
1917
+ if (x > 0 && skel[i + w - 1]) length += Math.SQRT2;
1918
+ }
1919
+ return length > 0 ? Math.max(1, area / length) : 1;
1920
+ }
1921
+ /**
1922
+ * Each of `m` regions of the ink (`comp`, VOID outside): its skeleton's length
1923
+ * and its stroke width (and the skeleton itself, thinning being local to each region), measured as `strokeWidthOf` does (0 where it thins to
1924
+ * a single pixel, which no stroke can be drawn along).
1925
+ */
1926
+ function regionWidths(ink, w, h, comp, m) {
1927
+ const skel = thin(ink, w, h);
1928
+ const area = new Float64Array(m);
1929
+ const length = new Float64Array(m);
1930
+ for (let i = 0; i < ink.length; i++) {
1931
+ const c = comp[i];
1932
+ if (!ink[i] || c < 0) continue;
1933
+ area[c]++;
1934
+ if (!skel[i]) continue;
1935
+ const x = i % w;
1936
+ if (x + 1 < w && skel[i + 1]) length[c] += 1;
1937
+ if (skel[i + w]) length[c] += 1;
1938
+ if (x + 1 < w && skel[i + w + 1]) length[c] += Math.SQRT2;
1939
+ if (x > 0 && skel[i + w - 1]) length[c] += Math.SQRT2;
1940
+ }
1941
+ return {
1942
+ width: area.map((a, c) => length[c] > 0 ? Math.max(1, a / length[c]) : 0),
1943
+ length,
1944
+ skel
1945
+ };
1946
+ }
1947
+ /** The eight neighbours P2…P9, clockwise from north, as offsets. */
1948
+ const DX = [
1949
+ 0,
1950
+ 1,
1951
+ 1,
1952
+ 1,
1953
+ 0,
1954
+ -1,
1955
+ -1,
1956
+ -1
1957
+ ];
1958
+ const DY = [
1959
+ -1,
1960
+ -1,
1961
+ 0,
1962
+ 1,
1963
+ 1,
1964
+ 1,
1965
+ 0,
1966
+ -1
1967
+ ];
1968
+ function neighbours(img, w, h, x, y) {
1969
+ const p = [];
1970
+ for (let k = 0; k < 8; k++) {
1971
+ const nx = x + DX[k];
1972
+ const ny = y + DY[k];
1973
+ p.push(nx >= 0 && nx < w && ny >= 0 && ny < h ? img[ny * w + nx] : 0);
1974
+ }
1975
+ return p;
1976
+ }
1977
+ /** 0 → 1 transitions round the neighbourhood: 1 on a line or an end, 3+ at a junction. */
1978
+ const crossings = (p) => {
1979
+ let n = 0;
1980
+ for (let k = 0; k < 8; k++) if (!p[k] && p[(k + 1) % 8]) n++;
1981
+ return n;
1982
+ };
1983
+ /** How many 8-connected groups the set neighbours form among themselves. */
1984
+ function pieces(p) {
1985
+ const seen = [
1986
+ false,
1987
+ false,
1988
+ false,
1989
+ false,
1990
+ false,
1991
+ false,
1992
+ false,
1993
+ false
1994
+ ];
1995
+ let groups = 0;
1996
+ for (let k = 0; k < 8; k++) {
1997
+ if (!p[k] || seen[k]) continue;
1998
+ groups++;
1999
+ const stack = [k];
2000
+ seen[k] = true;
2001
+ while (stack.length) {
2002
+ const a = stack.pop();
2003
+ for (let b = 0; b < 8; b++) if (p[b] && !seen[b] && Math.abs(DX[a] - DX[b]) <= 1 && Math.abs(DY[a] - DY[b]) <= 1) {
2004
+ seen[b] = true;
2005
+ stack.push(b);
2006
+ }
2007
+ }
2008
+ }
2009
+ return groups;
2010
+ }
2011
+ /** A neighbourhood as a byte: bit k set when neighbour P(k+2) (clockwise from north) is ink. */
2012
+ const unbits = (m) => [
2013
+ 0,
2014
+ 1,
2015
+ 2,
2016
+ 3,
2017
+ 4,
2018
+ 5,
2019
+ 6,
2020
+ 7
2021
+ ].map((k) => m >> k & 1);
2022
+ /** For every neighbourhood: removable on Zhang–Suen's first and second sub-pass, and redundant afterwards. */
2023
+ const ZS1 = /* @__PURE__ */ new Uint8Array(256);
2024
+ const ZS2 = /* @__PURE__ */ new Uint8Array(256);
2025
+ const SPARE = /* @__PURE__ */ new Uint8Array(256);
2026
+ for (let m = 0; m < 256; m++) {
2027
+ const p = unbits(m);
2028
+ const b = p.reduce((s, v) => s + v, 0);
2029
+ const ok = b >= 2 && b <= 6 && crossings(p) === 1;
2030
+ ZS1[m] = ok && !(p[0] * p[2] * p[4]) && !(p[2] * p[4] * p[6]) ? 1 : 0;
2031
+ ZS2[m] = ok && !(p[0] * p[2] * p[6]) && !(p[0] * p[4] * p[6]) ? 1 : 0;
2032
+ SPARE[m] = b >= 2 && pieces(p) === 1 ? 1 : 0;
2033
+ }
2034
+ function thin(ink, w, h) {
2035
+ const W = w + 2;
2036
+ const img = new Uint8Array(W * (h + 2));
2037
+ const live = [];
2038
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (ink[y * w + x]) {
2039
+ img[(y + 1) * W + x + 1] = 1;
2040
+ live.push((y + 1) * W + x + 1);
2041
+ }
2042
+ const off = DX.map((dx, k) => DY[k] * W + dx);
2043
+ const mask = (i) => {
2044
+ let m = 0;
2045
+ for (let k = 0; k < 8; k++) if (img[i + off[k]]) m |= 1 << k;
2046
+ return m;
2047
+ };
2048
+ const stamp = new Int32Array(img.length);
2049
+ const gone = [];
2050
+ let edge = live.filter((i) => mask(i) !== 255);
2051
+ for (let round = 0, quiet = 0; quiet < 2 && edge.length; round++) {
2052
+ const table = round % 2 ? ZS2 : ZS1;
2053
+ gone.length = 0;
2054
+ for (const i of edge) if (img[i] && table[mask(i)]) gone.push(i);
2055
+ for (const i of gone) img[i] = 0;
2056
+ quiet = gone.length ? 0 : quiet + 1;
2057
+ const next = [];
2058
+ const add = (i) => {
2059
+ if (img[i] && stamp[i] !== round + 1) {
2060
+ stamp[i] = round + 1;
2061
+ next.push(i);
2062
+ }
2063
+ };
2064
+ for (const i of edge) add(i);
2065
+ for (const i of gone) for (let k = 0; k < 8; k++) add(i + off[k]);
2066
+ edge = next;
2067
+ }
2068
+ edge.sort((a, b) => a - b);
2069
+ for (let changed = true; changed;) {
2070
+ changed = false;
2071
+ for (const i of edge) if (img[i] && SPARE[mask(i)]) {
2072
+ img[i] = 0;
2073
+ changed = true;
2074
+ }
2075
+ }
2076
+ const out = new Uint8Array(w * h);
2077
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) out[y * w + x] = img[(y + 1) * W + x + 1];
2078
+ return out;
2079
+ }
2080
+ const degree = (img, w, h, i) => neighbours(img, w, h, i % w, i / w | 0).reduce((s, v) => s + v, 0);
2081
+ /** Remove branches from an end to a junction shorter than `min` pixels, until none are left. */
2082
+ function prune(skel, w, h, min) {
2083
+ for (let pass = 0; pass < 4; pass++) {
2084
+ let removed = false;
2085
+ for (let i = 0; i < skel.length; i++) {
2086
+ if (!skel[i] || degree(skel, w, h, i) !== 1) continue;
2087
+ const path = [i];
2088
+ let prev = -1;
2089
+ let cur = i;
2090
+ let atJunction = false;
2091
+ while (path.length <= min) {
2092
+ const x = cur % w;
2093
+ const y = cur / w | 0;
2094
+ const next = [];
2095
+ for (let k = 0; k < 8; k++) {
2096
+ const nx = x + DX[k];
2097
+ const ny = y + DY[k];
2098
+ const j = ny * w + nx;
2099
+ if (nx >= 0 && nx < w && ny >= 0 && ny < h && skel[j] && j !== prev && !path.includes(j)) next.push(j);
2100
+ }
2101
+ if (next.length !== 1 || degree(skel, w, h, next[0]) > 2) {
2102
+ atJunction = next.length >= 1;
2103
+ break;
2104
+ }
2105
+ prev = cur;
2106
+ cur = next[0];
2107
+ path.push(cur);
2108
+ }
2109
+ if (atJunction && path.length <= min) {
2110
+ for (const j of path) skel[j] = 0;
2111
+ removed = true;
2112
+ }
2113
+ }
2114
+ if (!removed) break;
2115
+ }
2116
+ }
2117
+ /**
2118
+ * Walk the skeleton into chains. Nodes are ends (one neighbour) and junction
2119
+ * pixels (three or more); adjacent junction pixels form one junction, met at
2120
+ * its centre. What's left once every chain from a node is walked is loops.
2121
+ */
2122
+ function walk(skel, w, h) {
2123
+ const n = w * h;
2124
+ const isNode = new Uint8Array(n);
2125
+ for (let i = 0; i < n; i++) if (skel[i] && degree(skel, w, h, i) !== 2) isNode[i] = 1;
2126
+ const group = new Int32Array(n).fill(-1);
2127
+ const centres = [];
2128
+ for (let i = 0; i < n; i++) {
2129
+ if (!isNode[i] || group[i] >= 0) continue;
2130
+ const g = centres.length;
2131
+ const stack = [i];
2132
+ group[i] = g;
2133
+ let sx = 0;
2134
+ let sy = 0;
2135
+ let c = 0;
2136
+ while (stack.length) {
2137
+ const j = stack.pop();
2138
+ sx += j % w + .5;
2139
+ sy += (j / w | 0) + .5;
2140
+ c++;
2141
+ const x = j % w;
2142
+ const y = j / w | 0;
2143
+ for (let k = 0; k < 8; k++) {
2144
+ const nx = x + DX[k];
2145
+ const ny = y + DY[k];
2146
+ const m = ny * w + nx;
2147
+ if (nx >= 0 && nx < w && ny >= 0 && ny < h && isNode[m] && group[m] < 0 && degree(skel, w, h, m) > 2 && degree(skel, w, h, j) > 2) {
2148
+ group[m] = g;
2149
+ stack.push(m);
2150
+ }
2151
+ }
2152
+ }
2153
+ centres.push({
2154
+ x: sx / c,
2155
+ y: sy / c
2156
+ });
2157
+ }
2158
+ const used = new Uint8Array(n);
2159
+ const centre = (i) => ({
2160
+ x: i % w + .5,
2161
+ y: (i / w | 0) + .5
2162
+ });
2163
+ const next = (i, from) => {
2164
+ const x = i % w;
2165
+ const y = i / w | 0;
2166
+ for (const k of [
2167
+ 0,
2168
+ 2,
2169
+ 4,
2170
+ 6,
2171
+ 1,
2172
+ 3,
2173
+ 5,
2174
+ 7
2175
+ ]) {
2176
+ const nx = x + DX[k];
2177
+ const ny = y + DY[k];
2178
+ const j = ny * w + nx;
2179
+ if (nx >= 0 && nx < w && ny >= 0 && ny < h && skel[j] && j !== from && !used[j] && !(isNode[j] && group[j] === group[from] && group[from] >= 0)) return j;
2180
+ }
2181
+ return -1;
2182
+ };
2183
+ const chains = [];
2184
+ const linked = /* @__PURE__ */ new Set();
2185
+ for (let i = 0; i < n; i++) {
2186
+ if (!isNode[i]) continue;
2187
+ const x = i % w;
2188
+ const y = i / w | 0;
2189
+ for (let k = 0; k < 8; k++) {
2190
+ const nx = x + DX[k];
2191
+ const ny = y + DY[k];
2192
+ const j = ny * w + nx;
2193
+ if (nx < 0 || nx >= w || ny < 0 || ny >= h || !skel[j] || used[j]) continue;
2194
+ if (isNode[j]) {
2195
+ if (group[j] === group[i]) continue;
2196
+ const key = [group[i], group[j]].sort().join(",");
2197
+ if (linked.has(key)) continue;
2198
+ linked.add(key);
2199
+ chains.push({
2200
+ pts: [centres[group[i]], centres[group[j]]],
2201
+ closed: false
2202
+ });
2203
+ continue;
2204
+ }
2205
+ const pts = [centres[group[i]]];
2206
+ let prev = i;
2207
+ let cur = j;
2208
+ while (cur >= 0 && !isNode[cur]) {
2209
+ used[cur] = 1;
2210
+ pts.push(centre(cur));
2211
+ const nxt = next(cur, prev);
2212
+ prev = cur;
2213
+ cur = nxt;
2214
+ }
2215
+ if (cur >= 0) {
2216
+ if (group[cur] === group[i] && pts.length <= 3) continue;
2217
+ pts.push(centres[group[cur]]);
2218
+ }
2219
+ chains.push({
2220
+ pts,
2221
+ closed: false
2222
+ });
2223
+ }
2224
+ }
2225
+ for (let i = 0; i < n; i++) {
2226
+ if (!skel[i] || used[i] || isNode[i]) continue;
2227
+ const pts = [];
2228
+ let prev = -1;
2229
+ let cur = i;
2230
+ while (cur >= 0 && !used[cur]) {
2231
+ used[cur] = 1;
2232
+ pts.push(centre(cur));
2233
+ const nxt = next(cur, prev);
2234
+ prev = cur;
2235
+ cur = nxt;
2236
+ }
2237
+ chains.push({
2238
+ pts,
2239
+ closed: pts.length > 2
2240
+ });
2241
+ }
2242
+ return chains;
2243
+ }
2244
+ /**
2245
+ * Thinning pulls the skeleton toward a junction: a T's stem bends to meet the
2246
+ * bar, and an X's two strokes run together for a stroke's width at the
2247
+ * crossing. Within `width` of a junction the skeleton is the junction's shape,
2248
+ * not the strokes', so each arm is cut back there, its direction measured just
2249
+ * outside, and all the arms are drawn straight on to the point nearest every
2250
+ * arm's line (least squares), which is where the strokes really meet. If the
2251
+ * arms are near parallel, or that point is further than `width` from the
2252
+ * junction, the junction's centre stays.
2253
+ */
2254
+ function refitJunctions(chains, width) {
2255
+ const key = (p) => `${p.x.toFixed(2)},${p.y.toFixed(2)}`;
2256
+ const ends = /* @__PURE__ */ new Map();
2257
+ for (const c of chains) if (!c.closed) for (const atStart of [true, false]) {
2258
+ const k = key(atStart ? c.pts[0] : c.pts[c.pts.length - 1]);
2259
+ ends.set(k, [...ends.get(k) ?? [], {
2260
+ chain: c,
2261
+ atStart
2262
+ }]);
2263
+ }
2264
+ const cut = Math.max(2, width);
2265
+ const reach = Math.max(6, width);
2266
+ const cuts = /* @__PURE__ */ new Map();
2267
+ for (const [, list] of ends) {
2268
+ if (list.length < 3) continue;
2269
+ const at = list[0].atStart ? list[0].chain.pts[0] : list[0].chain.pts[list[0].chain.pts.length - 1];
2270
+ const arms = [];
2271
+ for (const e of list) {
2272
+ const pts = e.atStart ? e.chain.pts : [...e.chain.pts].reverse();
2273
+ if (e.chain.pts[0] === e.chain.pts[e.chain.pts.length - 1] || key(e.chain.pts[0]) === key(e.chain.pts[e.chain.pts.length - 1])) continue;
2274
+ const from = pts.findIndex((p) => Math.hypot(p.x - at.x, p.y - at.y) >= cut);
2275
+ const to = pts.findIndex((p) => Math.hypot(p.x - at.x, p.y - at.y) >= cut + reach);
2276
+ if (from < 0 || to < 0 || to >= pts.length - 1) continue;
2277
+ const a = pts[from];
2278
+ const b = pts[to];
2279
+ const l = Math.hypot(b.x - a.x, b.y - a.y) || 1;
2280
+ arms.push({
2281
+ end: e,
2282
+ from,
2283
+ a,
2284
+ d: {
2285
+ x: (b.x - a.x) / l,
2286
+ y: (b.y - a.y) / l
2287
+ }
2288
+ });
2289
+ }
2290
+ if (arms.length < 2) continue;
2291
+ let [m00, m01, m11, v0, v1] = [
2292
+ 0,
2293
+ 0,
2294
+ 0,
2295
+ 0,
2296
+ 0
2297
+ ];
2298
+ for (const { a, d } of arms) {
2299
+ const [p00, p01, p11] = [
2300
+ 1 - d.x * d.x,
2301
+ -d.x * d.y,
2302
+ 1 - d.y * d.y
2303
+ ];
2304
+ m00 += p00;
2305
+ m01 += p01;
2306
+ m11 += p11;
2307
+ v0 += p00 * a.x + p01 * a.y;
2308
+ v1 += p01 * a.x + p11 * a.y;
2309
+ }
2310
+ const det = m00 * m11 - m01 * m01;
2311
+ let meet = at;
2312
+ if (det > .05 * arms.length * arms.length) {
2313
+ const p = {
2314
+ x: (m11 * v0 - m01 * v1) / det,
2315
+ y: (m00 * v1 - m01 * v0) / det
2316
+ };
2317
+ if (Math.hypot(p.x - at.x, p.y - at.y) <= cut) meet = p;
2318
+ }
2319
+ for (const { end, from } of arms) {
2320
+ const c = cuts.get(end.chain) ?? {};
2321
+ if (end.atStart) {
2322
+ c.start = from;
2323
+ c.startAt = meet;
2324
+ } else {
2325
+ c.end = from;
2326
+ c.endAt = meet;
2327
+ }
2328
+ cuts.set(end.chain, c);
2329
+ }
2330
+ for (const e of list) if (!arms.some((x) => x.end === e)) {
2331
+ const c = cuts.get(e.chain) ?? {};
2332
+ if (e.atStart) {
2333
+ c.start ??= 0;
2334
+ c.startAt = meet;
2335
+ } else {
2336
+ c.end ??= 0;
2337
+ c.endAt = meet;
2338
+ }
2339
+ cuts.set(e.chain, c);
2340
+ }
2341
+ }
2342
+ return chains.map((c) => {
2343
+ const k = cuts.get(c);
2344
+ if (!k) return c;
2345
+ const n = c.pts.length;
2346
+ const s = k.start ?? 0;
2347
+ const e = n - 1 - (k.end ?? 0);
2348
+ const pts = e > s ? c.pts.slice(s, e + 1) : [...c.pts];
2349
+ const cutStart = e > s && s > 0;
2350
+ const cutEnd = e > s && e < n - 1;
2351
+ if (k.startAt) cutStart ? pts.unshift(k.startAt) : pts[0] = k.startAt;
2352
+ if (k.endAt) cutEnd ? pts.push(k.endAt) : pts[pts.length - 1] = k.endAt;
2353
+ return {
2354
+ pts,
2355
+ closed: false
2356
+ };
2357
+ });
2358
+ }
2359
+ /** The direction a chain leaves its start, measured a few pixels along it. */
2360
+ function leaving(pts) {
2361
+ const a = pts[0];
2362
+ const b = pts[Math.min(pts.length - 1, 6)];
2363
+ const l = Math.hypot(b.x - a.x, b.y - a.y) || 1;
2364
+ return {
2365
+ x: (b.x - a.x) / l,
2366
+ y: (b.y - a.y) / l
2367
+ };
2368
+ }
2369
+ /**
2370
+ * Join chains that meet end to end and carry straight on (within 30°), so a
2371
+ * line through a crossing is one stroke. Each end joins at most once.
2372
+ */
2373
+ function joinStraight(chains) {
2374
+ const key = (p) => `${p.x.toFixed(2)},${p.y.toFixed(2)}`;
2375
+ const live = new Set(chains.filter((c) => !c.closed));
2376
+ const ends = /* @__PURE__ */ new Map();
2377
+ const addEnds = (c) => {
2378
+ for (const atStart of [true, false]) {
2379
+ const k = key(atStart ? c.pts[0] : c.pts[c.pts.length - 1]);
2380
+ const list = ends.get(k) ?? [];
2381
+ list.push({
2382
+ chain: c,
2383
+ atStart
2384
+ });
2385
+ ends.set(k, list);
2386
+ }
2387
+ };
2388
+ live.forEach(addEnds);
2389
+ const out = chains.filter((c) => c.closed);
2390
+ const outward = (e) => leaving(e.atStart ? e.chain.pts : [...e.chain.pts].reverse());
2391
+ for (const [, list] of ends) for (;;) {
2392
+ const here = list.filter((e) => live.has(e.chain));
2393
+ let best = null;
2394
+ let bestDot = -Math.cos(150 * Math.PI / 180);
2395
+ for (let a = 0; a < here.length; a++) for (let b = a + 1; b < here.length; b++) {
2396
+ if (here[a].chain === here[b].chain) continue;
2397
+ const da = outward(here[a]);
2398
+ const db = outward(here[b]);
2399
+ const dot = da.x * db.x + da.y * db.y;
2400
+ if (dot < -bestDot) {
2401
+ bestDot = -dot;
2402
+ best = [here[a], here[b]];
2403
+ }
2404
+ }
2405
+ if (!best) break;
2406
+ const [ea, eb] = best;
2407
+ const a = ea.atStart ? [...ea.chain.pts].reverse() : ea.chain.pts;
2408
+ const b = eb.atStart ? eb.chain.pts : [...eb.chain.pts].reverse();
2409
+ const joined = {
2410
+ pts: [...a, ...b.slice(1)],
2411
+ closed: false
2412
+ };
2413
+ live.delete(ea.chain);
2414
+ live.delete(eb.chain);
2415
+ live.add(joined);
2416
+ addEnds(joined);
2417
+ if (key(joined.pts[0]) === key(joined.pts[joined.pts.length - 1]) && joined.pts.length > 3) {
2418
+ live.delete(joined);
2419
+ out.push({
2420
+ pts: joined.pts.slice(0, -1),
2421
+ closed: true
2422
+ });
2423
+ }
2424
+ }
2425
+ return [...out, ...live];
2426
+ }
2427
+ const polyline = (pts) => pts.slice(1).map((b, i) => [
2428
+ pts[i],
2429
+ pts[i],
2430
+ b,
2431
+ b
2432
+ ]);
2433
+ function toSubpath$1(cubics, closed) {
2434
+ const r = (p) => ({
2435
+ x: Math.round(p.x * 100) / 100,
2436
+ y: Math.round(p.y * 100) / 100
2437
+ });
2438
+ const nodes = [];
2439
+ for (const c of cubics) {
2440
+ if (!nodes.length) nodes.push({
2441
+ ...r(c[0]),
2442
+ in: null,
2443
+ out: null
2444
+ });
2445
+ const flat = isFlat(c);
2446
+ if (!flat) nodes[nodes.length - 1].out = r(c[1]);
2447
+ nodes.push({
2448
+ ...r(c[3]),
2449
+ in: flat ? null : r(c[2]),
2450
+ out: null
2451
+ });
2452
+ }
2453
+ if (closed && nodes.length > 1) {
2454
+ const last = nodes.pop();
2455
+ nodes[0].in = last.in;
2456
+ }
2457
+ return {
2458
+ closed,
2459
+ nodes
2460
+ };
2461
+ }
2462
+ //#endregion
2463
+ //#region src/gradient.ts
2464
+ /**
2465
+ * Gradient fills for softly shaded regions.
2466
+ *
2467
+ * A palette splits a smooth shade into bands of flat tints, each traced as
2468
+ * its own shape. Here the bands are found again and put back together: two
2469
+ * neighbouring regions whose boundary is soft (the image barely changes
2470
+ * across it, though their colours differ) are one shaded region, and if a
2471
+ * linear or radial gradient explains its colours much better than one flat
2472
+ * colour, and no worse than the bands did, it becomes one shape with that
2473
+ * gradient.
2474
+ *
2475
+ * The fits are closed-form least squares in sRGB, which is what SVG
2476
+ * interpolates in:
2477
+ * - linear: each channel as a plane in x and y; the planes' dominant
2478
+ * direction is the gradient's axis.
2479
+ * - radial: the colour's main component as a + bx + cy + d(x² + y²), whose
2480
+ * vertex is the centre, refined as a + k·r by Gauss–Newton.
2481
+ * Along the axis (or the radius), each channel is then piecewise linear
2482
+ * between a few evenly spaced stops, as few as fit.
2483
+ */
2484
+ /** A boundary is soft when the image changes by less than this share of its two colours' difference across it. */
2485
+ const SOFT = .4;
2486
+ /** …or by less than this (RGB levels), however alike the colours: JPEG noise alone moves a pixel about this much. */
2487
+ const SOFT_NOISE = 10;
2488
+ /** Pixels either side of a crack whose step is measured: three pixels apart, so anti-aliasing counts as a hard edge. */
2489
+ const SPAN = 1;
2490
+ /** A soft boundary needs at least this many cracks, so a few pixels touching don't join two regions. */
2491
+ const SOFT_MIN = 6;
2492
+ /** Smallest shaded region (pixels) worth a gradient. */
2493
+ const MIN_AREA = 64;
2494
+ /** One flat colour must be at least this far off (RMS, RGB levels) for a gradient to be worth it. */
2495
+ const FLAT_MIN = 6;
2496
+ /** The gradient must at least halve the flat colour's error… */
2497
+ const GAIN = .5;
2498
+ /** …and come within this of the bands' own error. */
2499
+ const BANDS_SLACK = 1.1;
2500
+ /** A radial fit replaces the linear one only when this much closer. */
2501
+ const RADIAL_GAIN = .8;
2502
+ /** Pixels a shade is fitted on, at most. */
2503
+ const SAMPLE = 4e3;
2504
+ /** Weight of the tie between neighbouring stops: next to nothing beside a pixel's weight of 1. */
2505
+ const TIE = .001;
2506
+ /** Most stops along a gradient. */
2507
+ const MAX_STOPS = 5;
2508
+ /**
2509
+ * Groups of regions that are one soft shade, each with the gradient that
2510
+ * draws it. `comp` is each pixel's region (negative: none), `colorOf` each
2511
+ * region's flat colour.
2512
+ */
2513
+ function shadings(rgba, w, h, comp, regions, colorOf) {
2514
+ const step = /* @__PURE__ */ new Map();
2515
+ const count = /* @__PURE__ */ new Map();
2516
+ const rgb = (i) => [
2517
+ rgba[i * 4],
2518
+ rgba[i * 4 + 1],
2519
+ rgba[i * 4 + 2]
2520
+ ];
2521
+ const d3 = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
2522
+ const colors = Array.from({ length: regions }, (_, id) => colorOf(id));
2523
+ const crack = (a, b, before, after) => {
2524
+ const ca = comp[a];
2525
+ const cb = comp[b];
2526
+ if (ca < 0 || cb < 0 || ca === cb) return;
2527
+ const key = Math.min(ca, cb) * regions + Math.max(ca, cb);
2528
+ const p = before * 4;
2529
+ const q = after * 4;
2530
+ step.set(key, (step.get(key) ?? 0) + Math.hypot(rgba[p] - rgba[q], rgba[p + 1] - rgba[q + 1], rgba[p + 2] - rgba[q + 2]));
2531
+ count.set(key, (count.get(key) ?? 0) + 1);
2532
+ };
2533
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
2534
+ const i = y * w + x;
2535
+ if (x + 1 < w) crack(i, i + 1, y * w + Math.max(0, x - SPAN), y * w + Math.min(w - 1, x + 1 + SPAN));
2536
+ if (y + 1 < h) crack(i, i + w, Math.max(0, y - SPAN) * w + x, Math.min(h - 1, y + 1 + SPAN) * w + x);
2537
+ }
2538
+ const parent = Array.from({ length: regions }, (_, i) => i);
2539
+ const find = (i) => parent[i] === i ? i : parent[i] = find(parent[i]);
2540
+ for (const [key, n] of count) {
2541
+ const a = Math.floor(key / regions);
2542
+ const b = key % regions;
2543
+ if (n < SOFT_MIN || step.get(key) >= n * Math.max(SOFT * d3(colors[a], colors[b]), SOFT_NOISE)) continue;
2544
+ parent[find(a)] = find(b);
2545
+ }
2546
+ const groups = /* @__PURE__ */ new Map();
2547
+ for (let id = 0; id < regions; id++) {
2548
+ const r = find(id);
2549
+ const g = groups.get(r);
2550
+ if (g) g.push(id);
2551
+ else groups.set(r, [id]);
2552
+ }
2553
+ const root = new Int32Array(regions);
2554
+ for (let id = 0; id < regions; id++) root[id] = groups.get(find(id)).length > 1 ? find(id) : -1;
2555
+ const inner = /* @__PURE__ */ new Map();
2556
+ const rootAt = (i) => comp[i] >= 0 ? root[comp[i]] : -1;
2557
+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
2558
+ const i = y * w + x;
2559
+ const r = rootAt(i);
2560
+ if (r < 0 || rootAt(i - 1) !== r || rootAt(i + 1) !== r || rootAt(i - w) !== r || rootAt(i + w) !== r) continue;
2561
+ const list = inner.get(r);
2562
+ if (list) list.push(i);
2563
+ else inner.set(r, [i]);
2564
+ }
2565
+ const out = [];
2566
+ for (const [r, all] of inner) {
2567
+ if (all.length < MIN_AREA) continue;
2568
+ const stride = Math.max(1, Math.floor(all.length / SAMPLE));
2569
+ const xs = [];
2570
+ const ys = [];
2571
+ const cs = [];
2572
+ const bands = [];
2573
+ for (let k = 0; k < all.length; k += stride) {
2574
+ const i = all[k];
2575
+ xs.push(i % w + .5);
2576
+ ys.push(Math.floor(i / w) + .5);
2577
+ cs.push(rgb(i));
2578
+ bands.push(colors[comp[i]]);
2579
+ }
2580
+ const g = fitShading(xs, ys, cs);
2581
+ if (!g) continue;
2582
+ const n = cs.length;
2583
+ const mean = [
2584
+ 0,
2585
+ 1,
2586
+ 2
2587
+ ].map((k) => cs.reduce((s, c) => s + c[k], 0) / n);
2588
+ const rms = (f) => Math.sqrt(cs.reduce((s, c, j) => s + d3(c, f(j)) ** 2, 0) / n);
2589
+ const flat = rms(() => mean);
2590
+ const banded = rms((j) => bands[j]);
2591
+ if (flat < FLAT_MIN || g.rms > GAIN * flat || g.rms > BANDS_SLACK * banded) continue;
2592
+ out.push({
2593
+ comps: [...groups.get(r)],
2594
+ gradient: g.gradient,
2595
+ mean: ""
2596
+ });
2597
+ }
2598
+ const shadeOf = new Int32Array(regions).fill(-1);
2599
+ out.forEach((s, k) => s.comps.forEach((id) => shadeOf[id] = k));
2600
+ const near = /* @__PURE__ */ new Map();
2601
+ for (const key of count.keys()) {
2602
+ const a = Math.floor(key / regions);
2603
+ const b = key % regions;
2604
+ for (const [x, y] of [[a, b], [b, a]]) if (shadeOf[x] >= 0 && shadeOf[y] < 0) {
2605
+ const set = near.get(y);
2606
+ if (set) set.add(shadeOf[x]);
2607
+ else near.set(y, /* @__PURE__ */ new Set([shadeOf[x]]));
2608
+ }
2609
+ }
2610
+ if (near.size) {
2611
+ const ramps = out.map((s) => ramp(s.gradient));
2612
+ const flatErr = new Float64Array(regions);
2613
+ const area = new Float64Array(regions);
2614
+ const gradErr = /* @__PURE__ */ new Map();
2615
+ for (const id of near.keys()) gradErr.set(id, new Float64Array(out.length));
2616
+ for (let i = 0; i < w * h; i++) {
2617
+ const id = comp[i];
2618
+ const errs = id >= 0 ? gradErr.get(id) : void 0;
2619
+ if (!errs) continue;
2620
+ const c = rgb(i);
2621
+ area[id]++;
2622
+ flatErr[id] += dist2(c, colors[id]);
2623
+ for (const k of near.get(id)) errs[k] += dist2(c, ramps[k](i % w + .5, Math.floor(i / w) + .5));
2624
+ }
2625
+ for (const [id, ks] of near) {
2626
+ const errs = gradErr.get(id);
2627
+ const k = [...ks].reduce((a, b) => errs[b] < errs[a] ? b : a);
2628
+ const flat = flatErr[id] < FLAT_MIN ** 2 * area[id];
2629
+ if (errs[k] <= flatErr[id] && (!flat || area[id] < MIN_AREA)) {
2630
+ out[k].comps.push(id);
2631
+ shadeOf[id] = k;
2632
+ }
2633
+ }
2634
+ }
2635
+ const sums = out.map(() => [
2636
+ 0,
2637
+ 0,
2638
+ 0,
2639
+ 0
2640
+ ]);
2641
+ for (let i = 0; i < w * h; i++) {
2642
+ const k = comp[i] >= 0 ? shadeOf[comp[i]] : -1;
2643
+ if (k < 0) continue;
2644
+ const s = sums[k];
2645
+ s[0] += rgba[i * 4];
2646
+ s[1] += rgba[i * 4 + 1];
2647
+ s[2] += rgba[i * 4 + 2];
2648
+ s[3]++;
2649
+ }
2650
+ out.forEach((s, k) => s.mean = toHex([
2651
+ sums[k][0] / sums[k][3],
2652
+ sums[k][1] / sums[k][3],
2653
+ sums[k][2] / sums[k][3]
2654
+ ]));
2655
+ return out;
2656
+ }
2657
+ /** A gradient's colour at a point. */
2658
+ const colorAt = (g, x, y) => ramp(g)(x, y);
2659
+ /** A gradient as a function of the point, its stops parsed once. */
2660
+ function ramp(g) {
2661
+ const offsets = g.stops.map((s) => s.offset);
2662
+ const colors = g.stops.map((s) => hexToRgb(s.color));
2663
+ const last = colors.length - 1;
2664
+ const dx = g.type === "linear" ? g.x2 - g.x1 : 0;
2665
+ const dy = g.type === "linear" ? g.y2 - g.y1 : 0;
2666
+ const len2 = dx * dx + dy * dy || 1;
2667
+ return (x, y) => {
2668
+ const t = g.type === "linear" ? ((x - g.x1) * dx + (y - g.y1) * dy) / len2 : Math.hypot(x - g.cx, y - g.cy) / g.r;
2669
+ if (t <= offsets[0]) return colors[0];
2670
+ for (let k = 1; k <= last; k++) if (t <= offsets[k]) {
2671
+ const a = colors[k - 1];
2672
+ const b = colors[k];
2673
+ const f = (t - offsets[k - 1]) / (offsets[k] - offsets[k - 1] || 1);
2674
+ return [
2675
+ a[0] + f * (b[0] - a[0]),
2676
+ a[1] + f * (b[1] - a[1]),
2677
+ a[2] + f * (b[2] - a[2])
2678
+ ];
2679
+ }
2680
+ return colors[last];
2681
+ };
2682
+ }
2683
+ /** The better of a linear and a radial gradient through these pixels, with its RMS error. */
2684
+ function fitShading(xs, ys, cs) {
2685
+ const lin = fitLinear(xs, ys, cs);
2686
+ const rad = fitRadial(xs, ys, cs);
2687
+ if (rad && (!lin || rad.rms < RADIAL_GAIN * lin.rms)) return rad;
2688
+ return lin;
2689
+ }
2690
+ function fitLinear(xs, ys, cs) {
2691
+ const n = xs.length;
2692
+ const mx = xs.reduce((a, b) => a + b, 0) / n;
2693
+ const my = ys.reduce((a, b) => a + b, 0) / n;
2694
+ let sxx = 0;
2695
+ let sxy = 0;
2696
+ let syy = 0;
2697
+ const sx = [
2698
+ 0,
2699
+ 0,
2700
+ 0
2701
+ ];
2702
+ const sy = [
2703
+ 0,
2704
+ 0,
2705
+ 0
2706
+ ];
2707
+ const cm = [
2708
+ 0,
2709
+ 1,
2710
+ 2
2711
+ ].map((k) => cs.reduce((s, c) => s + c[k], 0) / n);
2712
+ for (let j = 0; j < n; j++) {
2713
+ const dx = xs[j] - mx;
2714
+ const dy = ys[j] - my;
2715
+ sxx += dx * dx;
2716
+ sxy += dx * dy;
2717
+ syy += dy * dy;
2718
+ for (let k = 0; k < 3; k++) {
2719
+ sx[k] += dx * (cs[j][k] - cm[k]);
2720
+ sy[k] += dy * (cs[j][k] - cm[k]);
2721
+ }
2722
+ }
2723
+ const det = sxx * syy - sxy * sxy;
2724
+ if (!(det > 0)) return null;
2725
+ const gx = sx.map((_, k) => (syy * sx[k] - sxy * sy[k]) / det);
2726
+ const gy = sx.map((_, k) => (sxx * sy[k] - sxy * sx[k]) / det);
2727
+ const a = gx.reduce((s, v) => s + v * v, 0);
2728
+ const b = gx.reduce((s, v, k) => s + v * gy[k], 0);
2729
+ const c = gy.reduce((s, v) => s + v * v, 0);
2730
+ const theta = .5 * Math.atan2(2 * b, a - c);
2731
+ const ux = Math.cos(theta);
2732
+ const uy = Math.sin(theta);
2733
+ const ramp = fitRamp(xs.map((x, j) => (x - mx) * ux + (ys[j] - my) * uy), cs);
2734
+ if (!ramp) return null;
2735
+ const { t0, t1, stops, rms } = ramp;
2736
+ return {
2737
+ gradient: {
2738
+ type: "linear",
2739
+ x1: mx + t0 * ux,
2740
+ y1: my + t0 * uy,
2741
+ x2: mx + t1 * ux,
2742
+ y2: my + t1 * uy,
2743
+ stops
2744
+ },
2745
+ rms
2746
+ };
2747
+ }
2748
+ function fitRadial(xs, ys, cs) {
2749
+ const n = xs.length;
2750
+ const mx = xs.reduce((a, b) => a + b, 0) / n;
2751
+ const my = ys.reduce((a, b) => a + b, 0) / n;
2752
+ const scale = Math.sqrt(xs.reduce((s, x, j) => s + (x - mx) ** 2 + (ys[j] - my) ** 2, 0) / n) || 1;
2753
+ const cm = [
2754
+ 0,
2755
+ 1,
2756
+ 2
2757
+ ].map((k) => cs.reduce((s, c) => s + c[k], 0) / n);
2758
+ const axis = mainAxis(cs, cm);
2759
+ const s = cs.map((c) => (c[0] - cm[0]) * axis[0] + (c[1] - cm[1]) * axis[1] + (c[2] - cm[2]) * axis[2]);
2760
+ const rows = xs.map((x, j) => {
2761
+ const u = (x - mx) / scale;
2762
+ const v = (ys[j] - my) / scale;
2763
+ return [
2764
+ 1,
2765
+ u,
2766
+ v,
2767
+ u * u + v * v
2768
+ ];
2769
+ });
2770
+ const q = leastSquares(rows, s);
2771
+ if (!q || Math.abs(q[3]) < 1e-9) return null;
2772
+ let cx = -q[1] / (2 * q[3]);
2773
+ let cy = -q[2] / (2 * q[3]);
2774
+ if (Math.hypot(cx, cy) > 3) return null;
2775
+ let a = 0;
2776
+ let k = 0;
2777
+ for (let it = 0; it < 8; it++) {
2778
+ const r = rows.map(([, u, v]) => Math.hypot(u - cx, v - cy));
2779
+ const ak = leastSquares(r.map((ri) => [1, ri]), s);
2780
+ if (!ak) return null;
2781
+ [a, k] = ak;
2782
+ const delta = leastSquares(rows.map(([, u, v], j) => {
2783
+ const ri = Math.max(r[j], 1e-6);
2784
+ return [
2785
+ 1,
2786
+ r[j],
2787
+ -k * (u - cx) / ri,
2788
+ -k * (v - cy) / ri
2789
+ ];
2790
+ }), s.map((sj, j) => sj - (a + k * r[j])));
2791
+ if (!delta) break;
2792
+ cx += delta[2];
2793
+ cy += delta[3];
2794
+ if (Math.hypot(delta[2], delta[3]) < 1e-4) break;
2795
+ }
2796
+ if (Math.hypot(cx, cy) > 3) return null;
2797
+ const px = mx + cx * scale;
2798
+ const py = my + cy * scale;
2799
+ const ramp = fitRamp(xs.map((x, j) => Math.hypot(x - px, ys[j] - py)), cs, 0);
2800
+ if (!ramp || ramp.t1 <= 0) return null;
2801
+ return {
2802
+ gradient: {
2803
+ type: "radial",
2804
+ cx: px,
2805
+ cy: py,
2806
+ r: ramp.t1,
2807
+ stops: ramp.stops.map((st) => ({
2808
+ ...st,
2809
+ offset: round$1((ramp.t0 + st.offset * (ramp.t1 - ramp.t0)) / ramp.t1, 3)
2810
+ }))
2811
+ },
2812
+ rms: ramp.rms
2813
+ };
2814
+ }
2815
+ /**
2816
+ * Colour as a function of t: piecewise linear between evenly spaced stops
2817
+ * from the least t to the greatest, as few as come within a level of the most.
2818
+ * Offsets run 0–1 over [t0, t1]. With `from`, t0 is at least that.
2819
+ */
2820
+ function fitRamp(t, cs, from = -Infinity) {
2821
+ let t0 = Infinity;
2822
+ let t1 = -Infinity;
2823
+ for (const tj of t) {
2824
+ if (tj < t0) t0 = tj;
2825
+ if (tj > t1) t1 = tj;
2826
+ }
2827
+ t0 = Math.max(from, t0);
2828
+ if (!(t1 > t0)) return null;
2829
+ const fits = [];
2830
+ for (let m = 2; m <= MAX_STOPS; m++) {
2831
+ const at = (tj) => Math.min(m - 1, Math.max(0, (tj - t0) / (t1 - t0) * (m - 1)));
2832
+ const rows = t.map((tj) => {
2833
+ const p = at(tj);
2834
+ const i = Math.min(m - 2, Math.floor(p));
2835
+ const f = p - i;
2836
+ const row = new Array(m).fill(0);
2837
+ row[i] = 1 - f;
2838
+ row[i + 1] = f;
2839
+ return row;
2840
+ });
2841
+ const ties = Array.from({ length: m - 1 }, (_, i) => {
2842
+ const row = new Array(m).fill(0);
2843
+ row[i] = TIE;
2844
+ row[i + 1] = -.001;
2845
+ return row;
2846
+ });
2847
+ const chans = [
2848
+ 0,
2849
+ 1,
2850
+ 2
2851
+ ].map((k) => leastSquares([...rows, ...ties], [...cs.map((c) => c[k]), ...ties.map(() => 0)]));
2852
+ if (chans.some((c) => !c)) continue;
2853
+ const colorAt = (row) => [
2854
+ 0,
2855
+ 1,
2856
+ 2
2857
+ ].map((k) => clamp(row.reduce((s, v, i) => s + v * chans[k][i], 0)));
2858
+ const stopColors = Array.from({ length: m }, (_, i) => [
2859
+ 0,
2860
+ 1,
2861
+ 2
2862
+ ].map((k) => clamp(chans[k][i])));
2863
+ const rms = Math.sqrt(rows.reduce((s, row, j) => s + dist2(colorAt(row), cs[j]), 0) / t.length);
2864
+ fits.push({
2865
+ stops: stopColors.map((c, i) => ({
2866
+ offset: round$1(i / (m - 1), 3),
2867
+ color: toHex(c)
2868
+ })),
2869
+ rms
2870
+ });
2871
+ }
2872
+ if (!fits.length) return null;
2873
+ const least = Math.min(...fits.map((f) => f.rms));
2874
+ return {
2875
+ t0,
2876
+ t1,
2877
+ ...fits.find((f) => f.rms <= least + 1)
2878
+ };
2879
+ }
2880
+ /** The main axis of a set of colours (power iteration on their covariance). */
2881
+ function mainAxis(cs, cm) {
2882
+ const cov = [
2883
+ 0,
2884
+ 1,
2885
+ 2
2886
+ ].map(() => [
2887
+ 0,
2888
+ 0,
2889
+ 0
2890
+ ]);
2891
+ for (const c of cs) for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) cov[i][j] += (c[i] - cm[i]) * (c[j] - cm[j]);
2892
+ let v = [
2893
+ 0,
2894
+ 1,
2895
+ 2
2896
+ ].map((i) => cov[i][i]);
2897
+ v = cov[v.indexOf(Math.max(...v))].slice();
2898
+ for (let it = 0; it < 30; it++) {
2899
+ const next = cov.map((row) => row[0] * v[0] + row[1] * v[1] + row[2] * v[2]);
2900
+ const len = Math.hypot(...next) || 1;
2901
+ v = next.map((x) => x / len);
2902
+ }
2903
+ return v;
2904
+ }
2905
+ /** Least squares through the normal equations (small systems only). */
2906
+ function leastSquares(rows, y) {
2907
+ const m = rows[0]?.length ?? 0;
2908
+ const A = Array.from({ length: m }, () => new Array(m + 1).fill(0));
2909
+ rows.forEach((row, j) => {
2910
+ for (let a = 0; a < m; a++) {
2911
+ if (!row[a]) continue;
2912
+ for (let b = 0; b < m; b++) A[a][b] += row[a] * row[b];
2913
+ A[a][m] += row[a] * y[j];
2914
+ }
2915
+ });
2916
+ for (let c = 0; c < m; c++) {
2917
+ let p = c;
2918
+ for (let r = c + 1; r < m; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r;
2919
+ if (Math.abs(A[p][c]) < 1e-12) return null;
2920
+ [A[c], A[p]] = [A[p], A[c]];
2921
+ for (let r = 0; r < m; r++) {
2922
+ if (r === c) continue;
2923
+ const f = A[r][c] / A[c][c];
2924
+ for (let k = c; k <= m; k++) A[r][k] -= f * A[c][k];
2925
+ }
2926
+ }
2927
+ return A.map((row, i) => row[m] / row[i]);
2928
+ }
2929
+ const clamp = (v) => Math.max(0, Math.min(255, v));
2930
+ const dist2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
2931
+ const round$1 = (v, places) => Math.round(v * 10 ** places) / 10 ** places;
2932
+ //#endregion
2933
+ //#region src/inlay.ts
2934
+ /**
2935
+ * Inlay, our shared-edge tracer: every preset, from logos to photos.
2936
+ * Like inlaid wood, every piece is cut to fit its neighbours exactly.
2937
+ *
2938
+ * VTracer traces every colour region on its own, so an edge between two
2939
+ * regions is traced twice. Fitting the two copies separately leaves hairline
2940
+ * gaps and slivers; leaving them to VTracer's spline fitter gives the wobbly
2941
+ * lines and rounded corners this replaces. Instead:
2942
+ *
2943
+ * 1. Label every pixel with a palette colour (or ink / paper for line art).
2944
+ * Anti-aliased pixels, which sit between two colours, take the closest
2945
+ * colour *among their neighbours*, so an edge between red and blue never
2946
+ * grows a one-pixel purple sliver.
2947
+ * 2. Merge specks smaller than `speckle`² pixels into whatever surrounds them.
2948
+ * 3. Walk the cracks between differently labelled pixels. Where three or more
2949
+ * regions meet (or two meet diagonally) is a junction; every boundary
2950
+ * between two junctions is one chain, with one region on each side.
2951
+ * 4. Fit each chain once (src/lib/fit.ts): corners first, then straight lines
2952
+ * where they fit and curves where they don't.
2953
+ * 5. Build each region's outline from its chains, reversing the ones it sees
2954
+ * from the other side. Neighbours share the exact same fitted edge: no
2955
+ * gaps, no overlaps, which is also what a vinyl cutter wants.
2956
+ *
2957
+ * Regions are 4-connected, so two pixels touching only at a corner are
2958
+ * separate shapes, and each region is one <path> (its outline plus its holes,
2959
+ * wound oppositely so the default nonzero fill rule cuts the holes). With
2960
+ * `stacked`, a region keeps only its outline (and any holes onto
2961
+ * transparency), and paint order does the rest; for flat art, a region behind
2962
+ * another is also completed where it is hidden (layers.ts).
2963
+ */
2964
+ const VOID = -1;
2965
+ /**
2966
+ * A value made safe inside a double-quoted attribute. Colours come from the
2967
+ * caller's palette as given, so a stray quote mustn't end the attribute.
2968
+ */
2969
+ const attr = (v) => String(v).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
2970
+ /** The trace as an SVG document. */
2971
+ function toSvg(r) {
2972
+ const defs = [];
2973
+ const tag = r.paths.some((p) => p.gradient) ? fnv(r.paths.map((p) => p.d + (p.gradient ? JSON.stringify(p.gradient) : "")).join("|")) : "";
2974
+ const path = (p) => {
2975
+ if (p.stroke) return `<path d="${attr(p.d)}" fill="none" stroke="${attr(p.fill)}" stroke-width="${attr(p.stroke)}" stroke-linecap="round" stroke-linejoin="round"/>`;
2976
+ if (!p.gradient) return `<path d="${attr(p.d)}" fill="${attr(p.fill)}"/>`;
2977
+ const id = `g${tag}-${defs.length}`;
2978
+ defs.push(gradientMarkup(p.gradient, id));
2979
+ return `<path d="${attr(p.d)}" fill="url(#${id}) ${attr(p.fill)}"/>`;
2980
+ };
2981
+ const body = r.paths.map(path).join("\n");
2982
+ const head = defs.length ? `<defs>\n${defs.join("\n")}\n</defs>\n` : "";
2983
+ 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`;
2984
+ }
2985
+ const num = (v) => String(Math.round(v * 100) / 100);
2986
+ /** A short hash (FNV-1a, base 36). */
2987
+ function fnv(s) {
2988
+ let h = 2166136261;
2989
+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
2990
+ return (h >>> 0).toString(36);
2991
+ }
2992
+ /** A gradient element, in the drawing's pixels. */
2993
+ function gradientMarkup(g, id) {
2994
+ const stops = g.stops.map((s) => `<stop offset="${num(s.offset * 100)}%" stop-color="${attr(s.color)}"/>`).join("");
2995
+ 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>`;
2996
+ }
2997
+ /** Trace to an SVG string; `trace` gives the shapes as data. */
2998
+ const traceInlay = (rgba, w, h, o) => toSvg(trace(rgba, w, h, o));
2999
+ /**
3000
+ * Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
3001
+ * into filled shapes that share their edges exactly.
3002
+ */
3003
+ function trace(rgba, w, h, o) {
3004
+ const { labels, colors, drawn } = o.mode === "palette" ? labelPalette(rgba, w, h, o.palette, !o.photo) : labelBinary(rgba, w, h, o.threshold);
3005
+ const clean = o.mode === "palette" && !o.pixels && !o.photo && lossless(rgba, labels, w, h, colors);
3006
+ if (o.mode === "palette" && o.merge) mergeLabels(labels, colors, o.merge);
3007
+ if (!o.pixels) despur(labels, w, h);
3008
+ if (!o.pixels && !(o.mode === "palette" && o.photo)) joinDiagonals(labels, w, h, rgba, drawn);
3009
+ const labs = o.mode === "palette" && !o.photo ? colors.map((c) => c ? oklab(hexToRgb(c)) : null) : void 0;
3010
+ mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2, labs);
3011
+ if (labs && !o.pixels) mergeSlivers(labels, w, h, labs);
3012
+ const lines = o.mode === "palette" && o.strokes && labs && !o.pixels ? strokesOf(rgba, labels, w, h, colors, labs, drawn, o) : [];
3013
+ let { comp, compLabel, compArea } = components(labels, w, h, (l) => drawn[l]);
3014
+ const gradientOf = /* @__PURE__ */ new Map();
3015
+ if (o.gradients && o.mode === "palette" && !o.pixels) {
3016
+ const found = shadings(rgba, w, h, comp, compLabel.length, (id) => hexToRgb(colors[compLabel[id]]));
3017
+ if (found.length) {
3018
+ const relabel = new Int32Array(compLabel.length).fill(-1);
3019
+ for (const s of found) {
3020
+ const l = colors.length;
3021
+ colors.push(s.mean);
3022
+ drawn.push(true);
3023
+ gradientOf.set(l, s.gradient);
3024
+ for (const id of s.comps) relabel[id] = l;
3025
+ }
3026
+ for (let i = 0; i < labels.length; i++) if (comp[i] !== VOID && relabel[comp[i]] >= 0) labels[i] = relabel[comp[i]];
3027
+ ({comp, compLabel, compArea} = components(labels, w, h, (l) => drawn[l]));
3028
+ }
3029
+ }
3030
+ const chains = findChains(comp, w, h);
3031
+ const rgbOf = clean ? (id) => hexToRgb(colors[compLabel[id]]) : null;
3032
+ const flatSides = (c) => !gradientOf.has(compLabel[c.left]) && !gradientOf.has(compLabel[c.right]);
3033
+ const fitted = [];
3034
+ const chainsOf = /* @__PURE__ */ new Map();
3035
+ for (const c of chains) {
3036
+ const cubics = o.pixels ? staircase(c.pts, c.closed) : fitChain(c.pts, c.closed, o, rgbOf && flatSides(c) ? edgePoints(c, comp, w, rgba, rgbOf) : void 0);
3037
+ if (!cubics.length) continue;
3038
+ const i = fitted.push({
3039
+ chain: c,
3040
+ cubics,
3041
+ back: reverse(cubics)
3042
+ }) - 1;
3043
+ for (const id of /* @__PURE__ */ new Set([c.left, c.right])) if (id !== VOID) {
3044
+ const list = chainsOf.get(id);
3045
+ if (list) list.push(i);
3046
+ else chainsOf.set(id, [i]);
3047
+ }
3048
+ }
3049
+ /** The outline of a set of regions: the chains with exactly one side in it, walked with the set on the left. */
3050
+ const outline = (inSet, ids) => {
3051
+ const seen = /* @__PURE__ */ new Set();
3052
+ const out = [];
3053
+ for (const id of ids) for (const i of chainsOf.get(id) ?? []) {
3054
+ if (seen.has(i)) continue;
3055
+ seen.add(i);
3056
+ const { chain, cubics, back } = fitted[i];
3057
+ const l = chain.left !== VOID && inSet(chain.left);
3058
+ if (l !== (chain.right !== VOID && inSet(chain.right))) out.push({
3059
+ ...chain,
3060
+ cubics: l ? cubics : back,
3061
+ reversed: !l,
3062
+ i
3063
+ });
3064
+ }
3065
+ return assemble(out);
3066
+ };
3067
+ const shapes = [];
3068
+ const paint = (id) => ({
3069
+ fill: colors[compLabel[id]],
3070
+ ...gradientOf.has(compLabel[id]) ? { gradient: gradientOf.get(compLabel[id]) } : {}
3071
+ });
3072
+ if (!o.stacked) for (const id of chainsOf.keys()) {
3073
+ const loops = outline((r) => r === id, [id]);
3074
+ if (loops.length) shapes.push({
3075
+ subs: loops.map((l) => l.sub),
3076
+ ...paint(id),
3077
+ area: compArea[id]
3078
+ });
3079
+ }
3080
+ else if (o.mode === "palette" && !o.photo && !o.pixels) {
3081
+ const loopsOf = /* @__PURE__ */ new Map();
3082
+ for (const id of chainsOf.keys()) {
3083
+ const loops = outline((r) => r === id, [id]);
3084
+ if (loops.length) loopsOf.set(id, loops);
3085
+ }
3086
+ const layered = layerShapes(loopsOf, comp, w, h, voidSeeds(comp, w, h));
3087
+ layered.forEach(({ id, subs }, k) => shapes.push({
3088
+ subs,
3089
+ ...paint(id),
3090
+ area: layered.length - k
3091
+ }));
3092
+ } else {
3093
+ const own = /* @__PURE__ */ new Map();
3094
+ for (const id of chainsOf.keys()) {
3095
+ const loops = outline((r) => r === id, [id]);
3096
+ if (loops.length) own.set(id, Math.max(...loops.map((l) => Math.abs(l.area))));
3097
+ }
3098
+ const order = [...own.keys()].sort((a, b) => own.get(b) - own.get(a) || a - b);
3099
+ const rank = new Map(order.map((id, i) => [id, i]));
3100
+ const voids = voidSeeds(comp, w, h);
3101
+ for (const id of order) {
3102
+ const set = /* @__PURE__ */ new Set([id]);
3103
+ for (const i of chainsOf.get(id)) {
3104
+ const { left, right } = fitted[i].chain;
3105
+ const other = left === id ? right : left;
3106
+ if (other !== VOID && rank.has(other) && rank.get(other) > rank.get(id)) set.add(other);
3107
+ }
3108
+ const loops = outline((r) => set.has(r), set);
3109
+ if (!loops.length) continue;
3110
+ const outer = loops.reduce((a, b) => Math.abs(b.area) > Math.abs(a.area) ? b : a);
3111
+ const kept = loops.filter((l) => l === outer || l.touchesVoid || [...l.across].some((r) => r !== VOID && rank.get(r) < rank.get(id)) || voids.some((p) => encloses(l.pts, p)));
3112
+ shapes.push({
3113
+ subs: kept.map((l) => l.sub),
3114
+ ...paint(id),
3115
+ area: own.get(id)
3116
+ });
3117
+ }
3118
+ }
3119
+ shapes.sort((a, b) => b.area - a.area);
3120
+ return {
3121
+ width: w,
3122
+ height: h,
3123
+ paths: [...shapes.map((x) => ({
3124
+ d: serializePath(x.subs),
3125
+ fill: x.fill,
3126
+ ...x.gradient ? { gradient: x.gradient } : {}
3127
+ })), ...lines]
3128
+ };
3129
+ }
3130
+ /**
3131
+ * Flat art, stacked: each region whole, back to front. Which of two touching
3132
+ * regions is in front is voted at the ends of the boundary between them (the
3133
+ * one whose outline carries straight on is in front), and each run of a back
3134
+ * region's outline that a front one hides is replaced by its continuation
3135
+ * (layers.ts). Then, as for photos, a hole is dropped when the shapes in it
3136
+ * are all painted later and cover it, so a background is one whole shape.
3137
+ */
3138
+ function layerShapes(loopsOf, comp, w, h, voids) {
3139
+ const turns = /* @__PURE__ */ new Map();
3140
+ const chains = /* @__PURE__ */ new Map();
3141
+ for (const [id, loops] of loopsOf) for (const l of loops) {
3142
+ for (const c of l.chains) chains.set(c.i, c);
3143
+ const n = l.chains.length;
3144
+ if (n < 2) continue;
3145
+ for (let k = 0; k < n; k++) {
3146
+ const c = l.chains[k];
3147
+ const next = l.chains[(k + 1) % n];
3148
+ const u = endDir(c.cubics);
3149
+ const v = startDir(next.cubics);
3150
+ if (!u || !v) continue;
3151
+ const at = c.reversed ? c.from : c.to;
3152
+ const t = turn(u, v);
3153
+ turns.set(`${c.i}:${at}:${id}`, t);
3154
+ turns.set(`${next.i}:${at}:${id}`, t);
3155
+ }
3156
+ }
3157
+ const votes = /* @__PURE__ */ new Map();
3158
+ const vote = (a, b) => votes.set(`${a}>${b}`, (votes.get(`${a}>${b}`) ?? 0) + 1);
3159
+ for (const c of chains.values()) {
3160
+ if (c.closed || c.left === VOID || c.right === VOID) continue;
3161
+ for (const at of [c.from, c.to]) {
3162
+ const tl = turns.get(`${c.i}:${at}:${c.left}`);
3163
+ const tr = turns.get(`${c.i}:${at}:${c.right}`);
3164
+ if (tl === void 0 || tr === void 0) continue;
3165
+ if (tl < 20 && tr > 40) vote(c.left, c.right);
3166
+ else if (tr < 20 && tl > 40) vote(c.right, c.left);
3167
+ }
3168
+ }
3169
+ const inFront = (a, b) => (votes.get(`${a}>${b}`) ?? 0) > 0 && !votes.get(`${b}>${a}`);
3170
+ const size = new Map([...loopsOf].map(([id, loops]) => [id, Math.max(...loops.map((l) => Math.abs(l.area)))]));
3171
+ const ids = [...loopsOf.keys()].sort((a, b) => size.get(b) - size.get(a) || a - b);
3172
+ const behind = new Map(ids.map((id) => [id, []]));
3173
+ const before = new Map(ids.map((id) => [id, 0]));
3174
+ for (const key of votes.keys()) {
3175
+ const [a, b] = key.split(">").map(Number);
3176
+ if (!inFront(a, b) || !behind.has(a) || !behind.has(b)) continue;
3177
+ behind.get(b).push(a);
3178
+ before.set(a, before.get(a) + 1);
3179
+ }
3180
+ const order = [];
3181
+ const done = /* @__PURE__ */ new Set();
3182
+ while (order.length < ids.length) {
3183
+ const next = ids.find((id) => !done.has(id) && before.get(id) === 0) ?? ids.find((id) => !done.has(id));
3184
+ done.add(next);
3185
+ order.push(next);
3186
+ for (const a of behind.get(next)) before.set(a, before.get(a) - 1);
3187
+ }
3188
+ const rank = new Map(order.map((id, k) => [id, k]));
3189
+ const under = (id, fronts) => {
3190
+ if ([...fronts].some((f) => rank.get(f) < rank.get(id))) return null;
3191
+ const at = (x, y) => x >= 0 && y >= 0 && x < w && y < h && fronts.has(comp[y * w + x]);
3192
+ return {
3193
+ hidden: (p) => at(Math.floor(p.x), Math.floor(p.y)),
3194
+ covered: (poly) => {
3195
+ let inside = 0;
3196
+ let under = 0;
3197
+ const y0 = Math.max(0, Math.floor(Math.min(...poly.map((p) => p.y))));
3198
+ const y1 = Math.min(h - 1, Math.ceil(Math.max(...poly.map((p) => p.y))));
3199
+ for (let y = y0; y <= y1; y++) {
3200
+ const cy = y + .5;
3201
+ const xs = [];
3202
+ for (let i = 0; i < poly.length; i++) {
3203
+ const a = poly[i];
3204
+ const b = poly[(i + 1) % poly.length];
3205
+ if (a.y <= cy !== b.y <= cy) xs.push(a.x + (cy - a.y) / (b.y - a.y) * (b.x - a.x));
3206
+ }
3207
+ xs.sort((a, b) => a - b);
3208
+ for (let k = 0; k + 1 < xs.length; k += 2) for (let x = Math.max(0, Math.ceil(xs[k] - .5)); x <= Math.min(w - 1, Math.floor(xs[k + 1] - .5)); x++) {
3209
+ inside++;
3210
+ if (at(x, y)) under++;
3211
+ }
3212
+ }
3213
+ return inside ? under / inside : 1;
3214
+ }
3215
+ };
3216
+ };
3217
+ return order.map((id) => {
3218
+ const loops = loopsOf.get(id);
3219
+ const outer = loops.reduce((a, b) => Math.abs(b.area) > Math.abs(a.area) ? b : a);
3220
+ return {
3221
+ id,
3222
+ subs: loops.filter((l) => l === outer || l.touchesVoid || [...l.across].some((r) => r !== VOID && rank.get(r) < rank.get(id)) || voids.some((p) => encloses(l.pts, p))).map((l) => l === outer ? completeLoop(l, id, inFront, under) : l.sub)
3223
+ };
3224
+ });
3225
+ }
3226
+ /** The share of what a completion adds that must be under the shapes in front. */
3227
+ const COVERED = .95;
3228
+ /** A loop with each run of chains hidden by a region in front replaced by its continuation. */
3229
+ function completeLoop(l, id, inFront, under) {
3230
+ const cs = l.chains;
3231
+ const n = cs.length;
3232
+ const hiddenAt = cs.map((c) => across(c) !== VOID && inFront(across(c), id));
3233
+ const start = hiddenAt.indexOf(false);
3234
+ if (start < 0 || !hiddenAt.some(Boolean)) return l.sub;
3235
+ const visible = sample(cs.filter((_, k) => !hiddenAt[k]).flatMap((c) => c.cubics));
3236
+ const out = [];
3237
+ const joins = /* @__PURE__ */ new Set();
3238
+ let changed = false;
3239
+ for (let j = 0; j < n;) {
3240
+ const k = (start + j) % n;
3241
+ if (!hiddenAt[k]) {
3242
+ out.push(...cs[k].cubics);
3243
+ j++;
3244
+ continue;
3245
+ }
3246
+ let e = j;
3247
+ while (e < n && hiddenAt[(start + e) % n]) e++;
3248
+ const run = Array.from({ length: e - j }, (_, q) => cs[(start + j + q) % n]);
3249
+ const prev = cs[(start + j - 1 + n) % n];
3250
+ const next = cs[(start + e) % n];
3251
+ const t0 = endDir(prev.cubics);
3252
+ const t1 = startDir(next.cubics);
3253
+ const p0 = run[0].cubics[0][0];
3254
+ const last = run[run.length - 1].cubics;
3255
+ const p1 = last[last.length - 1][3];
3256
+ const front = under(id, new Set(run.map(across)));
3257
+ let fill = t0 && t1 && front ? complete(p0, t0, p1, t1, visible, straightEnd(prev.cubics, true), straightEnd(next.cubics, false), front.hidden) : null;
3258
+ if (fill && front.covered([...sample(fill), ...sample(run.flatMap((c) => c.cubics)).reverse()]) < COVERED) fill = null;
3259
+ if (fill) {
3260
+ joins.add(out.length);
3261
+ out.push(...fill);
3262
+ joins.add(out.length);
3263
+ changed = true;
3264
+ } else for (const c of run) out.push(...c.cubics);
3265
+ j = e;
3266
+ }
3267
+ if (!changed) return l.sub;
3268
+ const merged = [];
3269
+ out.forEach((c, k) => {
3270
+ const last = merged[merged.length - 1];
3271
+ if (k > 0 && joins.has(k) && collinear(last, c)) merged[merged.length - 1] = line(last[0], c[3]);
3272
+ else merged.push(c);
3273
+ });
3274
+ if (merged.length > 2 && joins.has(out.length) && collinear(merged[merged.length - 1], merged[0])) merged[0] = line(merged.pop()[0], merged[0][3]);
3275
+ return toSubpath(merged);
3276
+ }
3277
+ /** Two flat cubics, end to start, along one line (within a degree). */
3278
+ function collinear(a, b) {
3279
+ if (!isFlat(a) || !isFlat(b)) return false;
3280
+ const u = {
3281
+ x: a[3].x - a[0].x,
3282
+ y: a[3].y - a[0].y
3283
+ };
3284
+ const v = {
3285
+ x: b[3].x - b[0].x,
3286
+ y: b[3].y - b[0].y
3287
+ };
3288
+ const lu = Math.hypot(u.x, u.y);
3289
+ const lv = Math.hypot(v.x, v.y);
3290
+ return lu > 0 && lv > 0 && (u.x * v.x + u.y * v.y) / (lu * lv) > Math.cos(Math.PI / 180);
3291
+ }
3292
+ /** The share of solid pixels within SOLID of their colour, from which an image counts as saved without loss. */
3293
+ const LOSSLESS = .99;
3294
+ /**
3295
+ * Whether an image looks saved without loss: the pixels inside each region
3296
+ * (all four neighbours the same colour) are its colour, within SOLID. In the
3297
+ * score's drawings saved as PNG, 99.99% are; as JPEG q72, 84–97%. JPEG's
3298
+ * noise skews the blends at edges, and edges read from them moved the wrong
3299
+ * way (on the overlap fixture, 0.18% wrong became 0.19%).
3300
+ */
3301
+ function lossless(rgba, labels, w, h, colors) {
3302
+ const pal = colors.map((c) => c ? hexToRgb(c) : null);
3303
+ let inside = 0;
3304
+ let exact = 0;
3305
+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
3306
+ const i = y * w + x;
3307
+ const l = labels[i];
3308
+ const c = pal[l];
3309
+ if (!c || labels[i - 1] !== l || labels[i + 1] !== l || labels[i - w] !== l || labels[i + w] !== l) continue;
3310
+ inside++;
3311
+ if (Math.abs(rgba[i * 4] - c[0]) <= SOLID && Math.abs(rgba[i * 4 + 1] - c[1]) <= SOLID && Math.abs(rgba[i * 4 + 2] - c[2]) <= SOLID) exact++;
3312
+ }
3313
+ return inside > 0 && exact >= LOSSLESS * inside;
3314
+ }
3315
+ /** How far (px) an edge point may move off its pixel crack. */
3316
+ const SUBPIXEL = .35;
3317
+ /** Runs of cracks at least this long either side of a turn make it a corner. */
3318
+ const CORNER_RUN = 3;
3319
+ /** A pixel within this much (per channel, 0–255) of its colour is solid. */
3320
+ const SOLID = 3;
3321
+ /** Two colours closer than this (RGB) are too alike to place an edge between by blending. */
3322
+ const SUBPIXEL_CONTRAST = 48;
3323
+ /**
3324
+ * A chain's points at sub-pixel precision: each pixel corner along it, moved
3325
+ * across to where the anti-aliasing puts the edge. A pixel between
3326
+ * colours A and B is a blend, a share α of A; with A's pixel and B's pixel
3327
+ * either side of the crack, the edge is α_A + α_B − 1 px from the crack, into
3328
+ * B (Open Vectorizer's reading of anti-aliasing as coverage). The ends stay on
3329
+ * their junctions, so neighbours still share them.
3330
+ */
3331
+ function edgePoints(c, comp, w, rgba, rgbOf) {
3332
+ if (c.left === VOID || c.right === VOID) return void 0;
3333
+ const A = rgbOf(c.left);
3334
+ const B = rgbOf(c.right);
3335
+ const d = [
3336
+ B[0] - A[0],
3337
+ B[1] - A[1],
3338
+ B[2] - A[2]
3339
+ ];
3340
+ const len2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
3341
+ if (len2 < 2304) return void 0;
3342
+ const dLum = .299 * d[0] + .587 * d[1] + .114 * d[2];
3343
+ const share = (x, y, id) => {
3344
+ const i = y * w + x;
3345
+ if (comp[i] !== id) return null;
3346
+ const p = [
3347
+ rgba[i * 4] - A[0],
3348
+ rgba[i * 4 + 1] - A[1],
3349
+ rgba[i * 4 + 2] - A[2]
3350
+ ];
3351
+ let t = (p[0] * d[0] + p[1] * d[1] + p[2] * d[2]) / len2;
3352
+ if (Math.hypot(p[0] - t * d[0], p[1] - t * d[1], p[2] - t * d[2]) > Math.sqrt(len2) / 4) return null;
3353
+ if (Math.abs(dLum) >= SUBPIXEL_CONTRAST) t = (.299 * p[0] + .587 * p[1] + .114 * p[2]) / dLum;
3354
+ return 1 - Math.min(1, Math.max(0, t));
3355
+ };
3356
+ const pts = c.pts;
3357
+ const cracks = [];
3358
+ let good = 0;
3359
+ const m = c.closed ? pts.length : pts.length - 1;
3360
+ for (let k = 0; k < m; k++) {
3361
+ const a = pts[k];
3362
+ const b = pts[(k + 1) % pts.length];
3363
+ const L = Math.abs(b.x - a.x) + Math.abs(b.y - a.y);
3364
+ const dx = Math.sign(b.x - a.x);
3365
+ const dy = Math.sign(b.y - a.y);
3366
+ const nx = -dy;
3367
+ const ny = dx;
3368
+ for (let s = 0; s < L; s++) {
3369
+ const mx = a.x + dx * (s + .5);
3370
+ const my = a.y + dy * (s + .5);
3371
+ const l = share(Math.floor(mx - nx / 2), Math.floor(my - ny / 2), c.left);
3372
+ const r = share(Math.floor(mx + nx / 2), Math.floor(my + ny / 2), c.right);
3373
+ const solid = (depth, id, C) => {
3374
+ const x = Math.floor(mx + nx * depth / 2);
3375
+ const y = Math.floor(my + ny * depth / 2);
3376
+ if (x < 0 || y < 0 || x >= w || y >= comp.length / w) return false;
3377
+ const i = (y * w + x) * 4;
3378
+ return comp[i / 4] === id && Math.abs(rgba[i] - C[0]) <= SOLID && Math.abs(rgba[i + 1] - C[1]) <= SOLID && Math.abs(rgba[i + 2] - C[2]) <= SOLID;
3379
+ };
3380
+ const ok = l !== null && r !== null && solid(-3, c.left, A) && solid(3, c.right, B) && solid(-5, c.left, A) && solid(5, c.right, B);
3381
+ if (ok) good++;
3382
+ cracks.push({
3383
+ x: mx,
3384
+ y: my,
3385
+ nx,
3386
+ ny,
3387
+ e: ok ? Math.max(-.35, Math.min(SUBPIXEL, l + r - 1)) : NaN,
3388
+ run: L
3389
+ });
3390
+ }
3391
+ const run = cracks.slice(cracks.length - L);
3392
+ const measured = run.map((q) => q.e);
3393
+ run.forEach((q, s) => {
3394
+ if (!Number.isNaN(q.e)) return;
3395
+ let best = NaN;
3396
+ for (let step = 1; step < L && Number.isNaN(best); step++) best = [measured[s - step], measured[s + step]].find((e) => e !== void 0 && !Number.isNaN(e)) ?? NaN;
3397
+ q.e = Number.isNaN(best) ? 0 : best;
3398
+ });
3399
+ }
3400
+ if (good < cracks.length / 2) return void 0;
3401
+ const out = c.closed ? [] : [pts[0]];
3402
+ const n = cracks.length;
3403
+ cracks.forEach((q, k) => {
3404
+ const p = cracks[(k - 1 + n) % n];
3405
+ if ((c.closed || k > 0) && (p.nx !== q.nx || p.ny !== q.ny) && p.run >= CORNER_RUN && q.run >= CORNER_RUN) out.push({
3406
+ x: q.x - q.ny / 2 + p.nx * p.e + q.nx * q.e,
3407
+ y: q.y + q.nx / 2 + p.ny * p.e + q.ny * q.e
3408
+ });
3409
+ out.push({
3410
+ x: q.x + q.nx * q.e,
3411
+ y: q.y + q.ny * q.e
3412
+ });
3413
+ });
3414
+ if (!c.closed) out.push(pts[pts.length - 1]);
3415
+ return out;
3416
+ }
3417
+ /**
3418
+ * A chain as its exact pixel boundary: a line between each pair of turns.
3419
+ * The points are pixel corners about a pixel apart, so a run of them in one
3420
+ * direction is one straight edge. A closed loop starts at a turn, so its seam
3421
+ * isn't a node in the middle of an edge.
3422
+ */
3423
+ function staircase(pts, closed) {
3424
+ const n = pts.length;
3425
+ if (n < 2) return [];
3426
+ const dir = (a, b) => `${Math.sign(b.x - a.x)},${Math.sign(b.y - a.y)}`;
3427
+ const isTurn = (i) => {
3428
+ const a = pts[(i - 1 + n) % n];
3429
+ const b = pts[i];
3430
+ const c = pts[(i + 1) % n];
3431
+ return dir(a, b) !== dir(b, c);
3432
+ };
3433
+ const keep = [];
3434
+ if (closed) {
3435
+ const start = pts.findIndex((_, i) => isTurn(i));
3436
+ if (start < 0) return [];
3437
+ for (let k = 0; k < n; k++) {
3438
+ const i = (start + k) % n;
3439
+ if (isTurn(i)) keep.push(pts[i]);
3440
+ }
3441
+ keep.push(keep[0]);
3442
+ } else {
3443
+ keep.push(pts[0]);
3444
+ for (let i = 1; i < n - 1; i++) if (isTurn(i)) keep.push(pts[i]);
3445
+ keep.push(pts[n - 1]);
3446
+ }
3447
+ const out = [];
3448
+ for (let i = 1; i < keep.length; i++) {
3449
+ const a = keep[i - 1];
3450
+ const b = keep[i];
3451
+ out.push([
3452
+ a,
3453
+ {
3454
+ x: a.x + (b.x - a.x) / 3,
3455
+ y: a.y + (b.y - a.y) / 3
3456
+ },
3457
+ {
3458
+ x: a.x + (b.x - a.x) * 2 / 3,
3459
+ y: a.y + (b.y - a.y) * 2 / 3
3460
+ },
3461
+ b
3462
+ ]);
3463
+ }
3464
+ return out;
3465
+ }
3466
+ /** Relabel merged colours as their targets, following chains, in place. */
3467
+ function mergeLabels(labels, colors, merge) {
3468
+ const index = new Map(colors.map((c, i) => [c, i]));
3469
+ const remap = colors.map((c, i) => {
3470
+ let to = c;
3471
+ let at = i;
3472
+ const seen = /* @__PURE__ */ new Set();
3473
+ while (merge[to] && !seen.has(to)) {
3474
+ seen.add(to);
3475
+ to = merge[to].toLowerCase();
3476
+ const k = index.get(to);
3477
+ if (k !== void 0) at = k;
3478
+ }
3479
+ return at;
3480
+ });
3481
+ if (remap.every((t, i) => t === i)) return;
3482
+ for (let i = 0; i < labels.length; i++) labels[i] = remap[labels[i]];
3483
+ }
3484
+ /**
3485
+ * The colour an in-between pixel holds most of, read as an anti-aliased mix
3486
+ * of two palette colours (mixed as a renderer mixes them, in sRGB): the
3487
+ * pair whose mix comes nearest the pixel, if nearer than any one colour
3488
+ * (`solid`). Nearest-colour alone took the pale edge of a grey letter for
3489
+ * light blue, the palette's only colour that light. Only for a pixel more
3490
+ * than `MIX_FAR` from every colour: a pale blue fill lies on the line from
3491
+ * white to the blue ink too, and read as a mix a pale "+" eroded to white.
3492
+ */
3493
+ const MIX_FAR = .05;
3494
+ /** Every pair of palette colours, with what mixOf needs of each. */
3495
+ function pairsOf(pal, labs) {
3496
+ const pairs = [];
3497
+ for (let i = 0; i < pal.length; i++) for (let j = i + 1; j < pal.length; j++) {
3498
+ const a = pal[i];
3499
+ const d = [
3500
+ pal[j][0] - a[0],
3501
+ pal[j][1] - a[1],
3502
+ pal[j][2] - a[2]
3503
+ ];
3504
+ const len = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
3505
+ const span = Math.hypot(labs[i][0] - labs[j][0], labs[i][1] - labs[j][1], labs[i][2] - labs[j][2]);
3506
+ if (len) pairs.push({
3507
+ i,
3508
+ j,
3509
+ a,
3510
+ d,
3511
+ len,
3512
+ span
3513
+ });
3514
+ }
3515
+ return pairs;
3516
+ }
3517
+ function mixOf(rgb, lab, pairs, labs, solid) {
3518
+ let best;
3519
+ let bd = solid;
3520
+ let bspan = Infinity;
3521
+ for (const { i, j, a, d, len, span } of pairs) {
3522
+ 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));
3523
+ const m = oklab([
3524
+ a[0] + t * d[0],
3525
+ a[1] + t * d[1],
3526
+ a[2] + t * d[2]
3527
+ ]);
3528
+ const e = Math.hypot(m[0] - lab[0], m[1] - lab[1], m[2] - lab[2]);
3529
+ if (e < bd - .001 || best !== void 0 && e < bd + .001 && span < bspan) {
3530
+ bd = Math.min(bd, e);
3531
+ bspan = span;
3532
+ const di = Math.hypot(lab[0] - labs[i][0], lab[1] - labs[i][1], lab[2] - labs[i][2]);
3533
+ const dj = Math.hypot(lab[0] - labs[j][0], lab[1] - labs[j][1], lab[2] - labs[j][2]);
3534
+ best = t < .5 ? i : t > .5 ? j : di <= dj ? i : j;
3535
+ }
3536
+ }
3537
+ return best;
3538
+ }
3539
+ function labelPalette(rgba, w, h, palette, flat) {
3540
+ const pal = palette.map(hexToRgb);
3541
+ const labs = pal.map(oklab);
3542
+ const pairs = flat ? pairsOf(pal, labs) : null;
3543
+ const n = w * h;
3544
+ const labels = new Int32Array(n);
3545
+ const unsure = new Uint8Array(n);
3546
+ const cache = /* @__PURE__ */ new Map();
3547
+ const transparent = pal.length;
3548
+ for (let i = 0; i < n; i++) {
3549
+ const r = rgba[i * 4];
3550
+ const g = rgba[i * 4 + 1];
3551
+ const b = rgba[i * 4 + 2];
3552
+ if (rgba[i * 4 + 3] < 128) {
3553
+ labels[i] = transparent;
3554
+ continue;
3555
+ }
3556
+ const key = r << 16 | g << 8 | b;
1517
3557
  let hit = cache.get(key);
1518
3558
  if (hit === void 0) {
1519
3559
  const lab = oklab([
@@ -1532,7 +3572,13 @@ function labelPalette(rgba, w, h, palette) {
1532
3572
  best = k;
1533
3573
  } else if (d < d2) d2 = d;
1534
3574
  });
1535
- hit = best | (d2 < Infinity && d1 > .4 * d2 ? 256 : 0);
3575
+ const between = d2 < Infinity && d1 > .4 * d2;
3576
+ if (between && pairs && d1 > MIX_FAR) best = mixOf([
3577
+ r,
3578
+ g,
3579
+ b
3580
+ ], lab, pairs, labs, d1) ?? best;
3581
+ hit = best | (between ? 256 : 0);
1536
3582
  cache.set(key, hit);
1537
3583
  }
1538
3584
  labels[i] = hit & 255;
@@ -1549,6 +3595,8 @@ function labelPalette(rgba, w, h, palette) {
1549
3595
  ]);
1550
3596
  let best = -1;
1551
3597
  let bd = Infinity;
3598
+ let kinds = 0;
3599
+ let seen = -1;
1552
3600
  for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
1553
3601
  const nx = x + dx;
1554
3602
  const ny = y + dy;
@@ -1556,7 +3604,9 @@ function labelPalette(rgba, w, h, palette) {
1556
3604
  const j = ny * w + nx;
1557
3605
  if (unsure[j]) continue;
1558
3606
  const l = labels[j];
1559
- if (l === transparent || l === best) continue;
3607
+ if (l === transparent) continue;
3608
+ if (l !== seen) seen = l, kinds++;
3609
+ if (l === best) continue;
1560
3610
  const p = labs[l];
1561
3611
  const d = Math.hypot(lab[0] - p[0], lab[1] - p[1], lab[2] - p[2]);
1562
3612
  if (d < bd) {
@@ -1564,6 +3614,7 @@ function labelPalette(rgba, w, h, palette) {
1564
3614
  best = l;
1565
3615
  }
1566
3616
  }
3617
+ if (flat && kinds === 1 && best !== labels[i]) continue;
1567
3618
  if (best >= 0) fixed[i] = best;
1568
3619
  }
1569
3620
  return {
@@ -1581,8 +3632,10 @@ function labelBinary(rgba, w, h, threshold) {
1581
3632
  alpha[i] = rgba[i * 4 + 3] >= 128 ? 1 : 0;
1582
3633
  }
1583
3634
  const labels = new Int32Array(n);
1584
- if (threshold !== null) for (let i = 0; i < n; i++) labels[i] = alpha[i] && lum[i] < threshold ? 0 : 1;
1585
- else {
3635
+ if (threshold !== null) {
3636
+ const t = threshold === "auto" ? autoThreshold(lum, alpha) : threshold;
3637
+ for (let i = 0; i < n; i++) labels[i] = alpha[i] && lum[i] < t ? 0 : 1;
3638
+ } else {
1586
3639
  const global = otsu(lum, alpha);
1587
3640
  const mean = boxMean(lum, w, h, Math.max(7, Math.round(Math.min(w, h) / 32)));
1588
3641
  for (let i = 0; i < n; i++) labels[i] = alpha[i] && lum[i] < mean[i] - 12 && lum[i] < global + 32 ? 0 : 1;
@@ -1616,6 +3669,31 @@ function boxMean(v, w, h, r) {
1616
3669
  }
1617
3670
  return out;
1618
3671
  }
3672
+ /** Below this gap between the two sides' mean luminance, Otsu has split one population. */
3673
+ const MIN_INK_CONTRAST = 40;
3674
+ /**
3675
+ * Otsu's split, unless it falls inside a single population: a blank page
3676
+ * photographed with some noise splits down its own middle, and half of it
3677
+ * would trace as ink. Then the fixed 128 it replaced.
3678
+ */
3679
+ function autoThreshold(lum, alpha) {
3680
+ const t = otsu(lum, alpha);
3681
+ let dark = 0;
3682
+ let darkSum = 0;
3683
+ let light = 0;
3684
+ let lightSum = 0;
3685
+ for (let i = 0; i < lum.length; i++) {
3686
+ if (!alpha[i]) continue;
3687
+ if (lum[i] < t) {
3688
+ dark++;
3689
+ darkSum += lum[i];
3690
+ } else {
3691
+ light++;
3692
+ lightSum += lum[i];
3693
+ }
3694
+ }
3695
+ return dark && light && lightSum / light - darkSum / dark >= MIN_INK_CONTRAST ? t : 128;
3696
+ }
1619
3697
  /** Otsu's threshold over opaque pixels: the split that best separates two populations. */
1620
3698
  function otsu(lum, alpha) {
1621
3699
  const hist = new Array(256).fill(0);
@@ -1646,11 +3724,6 @@ function otsu(lum, alpha) {
1646
3724
  }
1647
3725
  return best;
1648
3726
  }
1649
- const hexToRgb = (hex) => [
1650
- parseInt(hex.slice(1, 3), 16),
1651
- parseInt(hex.slice(3, 5), 16),
1652
- parseInt(hex.slice(5, 7), 16)
1653
- ];
1654
3727
  /**
1655
3728
  * A pixel whose eight neighbours are at least seven of one other colour takes
1656
3729
  * that colour: a lone pixel jutting out of an edge, or a one-pixel nick in one.
@@ -1681,6 +3754,39 @@ function despur(labels, w, h) {
1681
3754
  }
1682
3755
  }
1683
3756
  }
3757
+ /**
3758
+ * Regions are 4-connected, so a line one pixel wide that runs diagonally, a
3759
+ * staircase of pixels touching only at corners, fell apart into specks, and
3760
+ * mergeSpecks then erased them: a 1 px outline at a slant traced as dashes or
3761
+ * not at all. Where two pixels of a colour touch only at a corner, across two
3762
+ * of another (a 2 × 2 checkerboard), one pair has to be joined. Join the pair
3763
+ * that isn't the background (the commonest label, or one that isn't drawn),
3764
+ * so the paper parts and the line goes on; between two inks, the pair whose
3765
+ * colour the corner pixel is nearer. The corner pixel that joins them is the
3766
+ * one whose colour is nearer the pair's: the anti-aliased half of the step.
3767
+ */
3768
+ function joinDiagonals(labels, w, h, rgba, drawn) {
3769
+ const count = /* @__PURE__ */ new Map();
3770
+ for (let i = 0; i < labels.length; i++) count.set(labels[i], (count.get(labels[i]) ?? 0) + 1);
3771
+ let paper = -1;
3772
+ for (const [l, c] of count) if (paper < 0 || c > count.get(paper)) paper = l;
3773
+ const back = (l) => l === paper || !drawn[l];
3774
+ const far = (i, a, b) => Math.hypot(rgba[i * 4] - (rgba[a * 4] + rgba[b * 4]) / 2, rgba[i * 4 + 1] - (rgba[a * 4 + 1] + rgba[b * 4 + 1]) / 2, rgba[i * 4 + 2] - (rgba[a * 4 + 2] + rgba[b * 4 + 2]) / 2);
3775
+ for (let y = 0; y < h - 1; y++) for (let x = 0; x < w - 1; x++) {
3776
+ const tl = y * w + x;
3777
+ const tr = tl + 1;
3778
+ const bl = tl + w;
3779
+ const br = bl + 1;
3780
+ if (labels[tl] !== labels[br] || labels[tr] !== labels[bl] || labels[tl] === labels[tr]) continue;
3781
+ const a = labels[tl];
3782
+ const b = labels[tr];
3783
+ let joinMain;
3784
+ if (back(a) !== back(b)) joinMain = back(b);
3785
+ else joinMain = Math.min(far(tr, tl, br), far(bl, tl, br)) <= Math.min(far(tl, tr, bl), far(br, tr, bl));
3786
+ if (joinMain) labels[far(tr, tl, br) <= far(bl, tl, br) ? tr : bl] = a;
3787
+ else labels[far(tl, tr, bl) <= far(br, tr, bl) ? tl : br] = b;
3788
+ }
3789
+ }
1684
3790
  const NEIGHBOURS = [
1685
3791
  [-1, -1],
1686
3792
  [0, -1],
@@ -1762,12 +3868,25 @@ function components(labels, w, h, keep) {
1762
3868
  * label they took and are stranded as a new speck. On photos that left
1763
3869
  * thousands of fragments, and a larger `speckle` left more, not fewer.
1764
3870
  */
1765
- function mergeSpecks(labels, w, h, minArea) {
3871
+ function mergeSpecks(labels, w, h, minArea, labs) {
1766
3872
  if (minArea <= 1) return;
1767
- for (let pass = 0; pass < 8; pass++) if (!mergeSpecksOnce(labels, w, h, minArea)) return;
3873
+ for (let pass = 0; pass < 8; pass++) if (!mergeSpecksOnce(labels, w, h, minArea, labs)) return;
1768
3874
  }
3875
+ /**
3876
+ * A speck at least this far (OKLab) from every colour around it is a shape,
3877
+ * not noise: a letter or a dot on paper. Ringing and anti-aliasing specks are
3878
+ * blends, close to a neighbour; grey text on white is 0.47 from it.
3879
+ */
3880
+ const SPECK_CONTRAST = .25;
3881
+ /**
3882
+ * But only from this share of the speck size up, and never under 6 px, so
3883
+ * raising Speckle still clears dust and text: at the default 8 (64 px) a
3884
+ * letter of 1.5 px strokes (10–40 px) stays and a 2 × 2 dot goes.
3885
+ */
3886
+ const SPECK_SHAPE = 1 / 8;
3887
+ const SPECK_MIN = 6;
1769
3888
  /** One pass of mergeSpecks; false when there was nothing left to merge. */
1770
- function mergeSpecksOnce(labels, w, h, minArea) {
3889
+ function mergeSpecksOnce(labels, w, h, minArea, labs) {
1771
3890
  const { comp, compArea } = components(labels, w, h, () => true);
1772
3891
  const small = compArea.map((a, id) => ({
1773
3892
  a,
@@ -1782,31 +3901,382 @@ function mergeSpecksOnce(labels, w, h, minArea) {
1782
3901
  for (let i = 0; i < w * h; i++) pixels[fill[comp[i]]++] = i;
1783
3902
  small.sort((p, q) => p.a - q.a);
1784
3903
  for (const { id } of small) {
1785
- const own = labels[pixels[start[id]]];
3904
+ const begin = start[id];
3905
+ const end = start[id + 1];
3906
+ const own = labels[pixels[begin]];
1786
3907
  const votes = /* @__PURE__ */ new Map();
1787
- for (let k = start[id]; k < start[id + 1]; k++) {
3908
+ let joined = false;
3909
+ for (let k = begin; k < end; k++) {
1788
3910
  const i = pixels[k];
1789
3911
  const x = i % w;
1790
3912
  const y = (i - x) / w;
1791
3913
  const vote = (j) => {
1792
3914
  const l = labels[j];
1793
3915
  if (l !== own) votes.set(l, (votes.get(l) ?? 0) + 1);
3916
+ else if (comp[j] !== id) joined = true;
1794
3917
  };
1795
3918
  if (x > 0) vote(i - 1);
1796
3919
  if (x < w - 1) vote(i + 1);
1797
3920
  if (y > 0) vote(i - w);
1798
3921
  if (y < h - 1) vote(i + w);
1799
3922
  }
3923
+ if (joined && labs) continue;
1800
3924
  let best = own;
1801
3925
  let most = 0;
1802
- for (const [l, v] of votes) if (v > most) most = v, best = l;
3926
+ const mine = labs?.[own];
3927
+ if (mine) {
3928
+ let near = Infinity;
3929
+ for (const [l, v] of votes) {
3930
+ const lab = labs[l];
3931
+ const d = lab ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : Infinity;
3932
+ if (d < near || d === near && v > most) near = d, most = v, best = l;
3933
+ }
3934
+ if (near > SPECK_CONTRAST && near < Infinity && end - begin >= Math.max(SPECK_MIN, minArea * SPECK_SHAPE)) continue;
3935
+ } else for (const [l, v] of votes) if (v > most) most = v, best = l;
1803
3936
  if (best !== own) {
1804
- for (let k = start[id]; k < start[id + 1]; k++) labels[pixels[k]] = best;
3937
+ for (let k = begin; k < end; k++) labels[pixels[k]] = best;
1805
3938
  changed = true;
1806
3939
  }
1807
3940
  }
1808
3941
  return changed;
1809
3942
  }
3943
+ /** Regions narrower than this on average (2 × area / perimeter, px) are slivers. */
3944
+ const SLIVER_WIDTH = 2;
3945
+ /** 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
+ const SLIVER_DISTANCE = .12;
3947
+ /**
3948
+ * Fold slivers into a neighbour of nearly the same colour. JPEG and WebP
3949
+ * smear a thin stroke into two shades of its ink (a 3 px letter stem came
3950
+ * out dark at its edges and lighter down the middle), and a one-pixel strip
3951
+ * of one shade inside the other fitted as a spike shooting out of the
3952
+ * 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.
3955
+ */
3956
+ function mergeSlivers(labels, w, h, labs) {
3957
+ for (let pass = 0; pass < 4; pass++) {
3958
+ const { comp, compArea } = components(labels, w, h, () => true);
3959
+ const m = compArea.length;
3960
+ const perimeter = new Int32Array(m);
3961
+ const label = new Int32Array(m);
3962
+ const around = /* @__PURE__ */ new Map();
3963
+ const touch = (a, b) => {
3964
+ const id = comp[a];
3965
+ perimeter[id]++;
3966
+ let c = around.get(id);
3967
+ if (!c) around.set(id, c = /* @__PURE__ */ new Set());
3968
+ c.add(comp[b]);
3969
+ };
3970
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
3971
+ const i = y * w + x;
3972
+ label[comp[i]] = labels[i];
3973
+ if (x < w - 1 && comp[i + 1] !== comp[i]) touch(i, i + 1), touch(i + 1, i);
3974
+ if (y < h - 1 && comp[i + w] !== comp[i]) touch(i, i + w), touch(i + w, i);
3975
+ }
3976
+ const to = new Int32Array(m).fill(-1);
3977
+ let changed = false;
3978
+ 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;
3980
+ const mine = labs[label[id]];
3981
+ 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
+ }
3989
+ if (best < 0) continue;
3990
+ to[id] = best;
3991
+ changed = true;
3992
+ }
3993
+ if (!changed) return;
3994
+ for (let i = 0; i < w * h; i++) if (to[comp[i]] >= 0) labels[i] = to[comp[i]];
3995
+ }
3996
+ }
3997
+ /** A part of a region is thin enough to be a line up to this wide (px), times `scale`. */
3998
+ const LINE_WIDEST = 8;
3999
+ /** And long enough: at least this many times as long as it is wide, so a dot stays a shape. */
4000
+ const LINE_LENGTH = 3;
4001
+ /** A colour is drawn as lines when at least this share of it is in thin, long parts. */
4002
+ const LINE_SHARE = .3;
4003
+ /** A line colour is at least this far (OKLab) from the paper. */
4004
+ const LINE_CONTRAST = .25;
4005
+ /** Lines measured thinner than this (px, times `scale`) stay shapes: a centreline can't follow small lettering. */
4006
+ const LINE_WIDTH = 2.5;
4007
+ /** Pieces of a colour's ink more than this many times wider or thinner than its usual width stay shapes. */
4008
+ const LINE_SPREAD = 1.2;
4009
+ /** And pieces shorter than this many times their width stay shapes: a letter's skeleton is all branches. */
4010
+ const LINE_PIECE = 8;
4011
+ /** How far off the line–paper blend (a share of the distance between them) its shades and edges may stray. */
4012
+ const LINE_OFF = .15;
4013
+ /**
4014
+ * The thin, long parts of the `keep` labels' 4-connected regions, as a mask,
4015
+ * and their thick parts. A pixel is thick when it lies within a disc wider
4016
+ * than `widest` that fits inside its region (a solid area, a dot, a heading's
4017
+ * strokes); what remains of each region falls into parts, and a part is thin
4018
+ * when no wider than `widest` and at least LINE_LENGTH times as long as wide.
4019
+ * So an outline that runs into a solid area of the same ink is still a line.
4020
+ * Depths are in thirds of a pixel, by a 3-4 chamfer distance from the edge.
4021
+ */
4022
+ function thinParts(labels, w, h, keep, widest) {
4023
+ const n = w * h;
4024
+ const comp = new Int32Array(n);
4025
+ for (let i = 0; i < n; i++) comp[i] = keep(labels[i]) ? labels[i] : VOID;
4026
+ const depth = chamfer(comp, w, h, 1);
4027
+ const core = 1.5 * (widest + 1);
4028
+ const reach = new Int32Array(n);
4029
+ for (let i = 0; i < n; i++) if (comp[i] !== VOID && depth[i] > core) reach[i] = depth[i];
4030
+ chamfer(comp, w, h, -1, reach);
4031
+ const thick = new Uint8Array(n);
4032
+ const rest = new Int32Array(n).fill(-1);
4033
+ for (let i = 0; i < n; i++) {
4034
+ if (comp[i] === VOID) continue;
4035
+ if (reach[i] > 0) thick[i] = 1;
4036
+ else rest[i] = labels[i];
4037
+ }
4038
+ const parts = components(rest, w, h, (l) => l >= 0);
4039
+ const deepest = new Int32Array(parts.compArea.length);
4040
+ for (let i = 0; i < n; i++) if (parts.comp[i] !== VOID && depth[i] > deepest[parts.comp[i]]) deepest[parts.comp[i]] = depth[i];
4041
+ const thinPart = deepest.map((d, id) => {
4042
+ const wide = 2 * d / 3 - 1;
4043
+ return wide <= widest && parts.compArea[id] >= LINE_LENGTH * wide ** 2 ? 1 : 0;
4044
+ });
4045
+ const thin = new Uint8Array(n);
4046
+ for (let i = 0; i < n; i++) if (parts.comp[i] !== VOID && thinPart[parts.comp[i]]) thin[i] = 1;
4047
+ return {
4048
+ thin,
4049
+ thick
4050
+ };
4051
+ }
4052
+ /**
4053
+ * A 3-4 chamfer pass over `comp`'s regions, two sweeps. With `sign` 1 it is
4054
+ * each pixel's distance in from its region's edge; with −1 it spreads `into`
4055
+ * outwards, falling by the distance, so each pixel gets the most any pixel
4056
+ * reaches it with (a disc of that radius round each start).
4057
+ */
4058
+ function chamfer(comp, w, h, sign, into) {
4059
+ const n = w * h;
4060
+ const d = into ?? new Int32Array(n);
4061
+ if (!into) for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
4062
+ const i = y * w + x;
4063
+ const c = comp[i];
4064
+ d[i] = c === VOID || x === 0 || y === 0 || x === w - 1 || y === h - 1 || comp[i - 1] !== c || comp[i + 1] !== c || comp[i - w] !== c || comp[i + w] !== c ? 3 : 1 << 30;
4065
+ }
4066
+ const s = sign;
4067
+ for (let i = 0; i < n; i++) d[i] *= s;
4068
+ const sweep = (i, j, step) => {
4069
+ const c = comp[i];
4070
+ if (c !== VOID && comp[j] === c) {
4071
+ const v = d[j] + step;
4072
+ if (v < d[i]) d[i] = v;
4073
+ }
4074
+ };
4075
+ for (let y = 1; y < h - 1; y++) for (let x = 1, i = y * w + 1; x < w - 1; x++, i++) {
4076
+ sweep(i, i - 1, 3);
4077
+ sweep(i, i - w, 3);
4078
+ sweep(i, i - w - 1, 4);
4079
+ sweep(i, i - w + 1, 4);
4080
+ }
4081
+ for (let y = h - 2; y > 0; y--) for (let x = w - 2, i = y * w + x; x > 0; x--, i--) {
4082
+ sweep(i, i + 1, 3);
4083
+ sweep(i, i + w, 3);
4084
+ sweep(i, i + w + 1, 4);
4085
+ sweep(i, i + w - 1, 4);
4086
+ }
4087
+ for (let i = 0; i < n; i++) d[i] *= s;
4088
+ return d;
4089
+ }
4090
+ /**
4091
+ * Outline art's lines. Finds the colours that are mostly thin, long parts (an
4092
+ * outline 3 px wide), traces those parts down their middle as strokes (one
4093
+ * path a colour, at the width measured from its ink), and hands their pixels
4094
+ * to the shapes either side, which meet under the line's middle. The paper is
4095
+ * never a line, however thin its gaps.
4096
+ */
4097
+ function strokesOf(rgba, labels, w, h, colors, labs, drawn, o) {
4098
+ const n = w * h;
4099
+ const k = Math.max(1, o.scale ?? 1);
4100
+ const widest = LINE_WIDEST * k;
4101
+ const { thin } = thinParts(labels, w, h, (l) => drawn[l], widest);
4102
+ const total = /* @__PURE__ */ new Map();
4103
+ const inLines = /* @__PURE__ */ new Map();
4104
+ let clear = 0;
4105
+ for (let i = 0; i < n; i++) {
4106
+ const l = labels[i];
4107
+ if (!drawn[l]) {
4108
+ clear++;
4109
+ continue;
4110
+ }
4111
+ total.set(l, (total.get(l) ?? 0) + 1);
4112
+ if (thin[i]) inLines.set(l, (inLines.get(l) ?? 0) + 1);
4113
+ }
4114
+ const [commonest, most] = [...total].reduce((a, b) => b[1] > a[1] ? b : a, [-1, -1]);
4115
+ const paper = most >= clear ? commonest : -1;
4116
+ const contrasts = (l) => paper < 0 || dist(labs[l], labs[paper]) >= LINE_CONTRAST;
4117
+ const lineColours = [...inLines].filter(([l, a]) => l !== paper && contrasts(l) && a >= LINE_SHARE * total.get(l)).map(([l]) => l);
4118
+ if (!lineColours.length) return [];
4119
+ const line = new Uint8Array(n);
4120
+ const out = [];
4121
+ const lab = labCache(rgba);
4122
+ for (const l of lineColours.sort((a, b) => inLines.get(b) - inLines.get(a))) {
4123
+ const ground = paper >= 0 ? labs[paper] : labs[l][0] > .5 ? [
4124
+ 0,
4125
+ 0,
4126
+ 0
4127
+ ] : [
4128
+ 1,
4129
+ 0,
4130
+ 0
4131
+ ];
4132
+ const inky = blendTest(labs[l], ground);
4133
+ const like = labs.map((c, j) => j === l || j !== paper && drawn[j] && !!c && inky(c));
4134
+ const mask = new Int32Array(n);
4135
+ for (let i = 0; i < n; i++) mask[i] = like[labels[i]] && !line[i] ? 1 : 0;
4136
+ const parts = thinParts(mask, w, h, (v) => v === 1, widest);
4137
+ const ink = new Uint8Array(n);
4138
+ for (let i = 0; i < n; i++) if (!line[i] && (thin[i] && like[labels[i]] || parts.thin[i])) ink[i] = 1;
4139
+ edgesOf(ink, (i) => line[i] === 1 || parts.thick[i] === 1, w, (i) => rgba[i * 4 + 3] >= 128 && inky(lab(i)));
4140
+ const pieces = components(Int32Array.from(ink), w, h, (v) => v === 1);
4141
+ const { width, length, skel } = regionWidths(ink, w, h, pieces.comp, pieces.compArea.length);
4142
+ const long = (c) => width[c] >= LINE_WIDTH * k && length[c] >= LINE_PIECE * width[c];
4143
+ const usual = weightedMedian(width, pieces.compArea, (c) => long(c));
4144
+ const fits = (c) => long(c) && width[c] >= usual / LINE_SPREAD && width[c] <= usual * LINE_SPREAD;
4145
+ let kept = 0;
4146
+ let all = 0;
4147
+ for (let c = 0; c < pieces.compArea.length; c++) {
4148
+ all += pieces.compArea[c];
4149
+ if (fits(c)) kept += pieces.compArea[c];
4150
+ }
4151
+ if (kept < LINE_SHARE * all) continue;
4152
+ for (let i = 0; i < n; i++) if (ink[i] && !fits(pieces.comp[i])) ink[i] = skel[i] = 0;
4153
+ const { subs, measured } = skeletonStrokes(ink, w, h, o, skel);
4154
+ if (!subs.length) continue;
4155
+ out.push({
4156
+ d: serializePath(subs),
4157
+ fill: colors[l],
4158
+ stroke: Math.round(measured * 100) / 100
4159
+ });
4160
+ for (let i = 0; i < n; i++) if (ink[i]) line[i] = 1;
4161
+ }
4162
+ if (!out.length) return out;
4163
+ const taken = new Uint8Array(n);
4164
+ const queued = new Uint8Array(n);
4165
+ for (let i = 0; i < n; i++) if (!line[i]) taken[i] = 1;
4166
+ let front = [];
4167
+ const push = (j, to) => {
4168
+ if (taken[j] || queued[j]) return;
4169
+ queued[j] = 1;
4170
+ to.push(j);
4171
+ };
4172
+ for (let i = 0; i < n; i++) {
4173
+ if (!taken[i]) continue;
4174
+ const x = i % w;
4175
+ if (x > 0) push(i - 1, front);
4176
+ if (x < w - 1) push(i + 1, front);
4177
+ if (i >= w) push(i - w, front);
4178
+ if (i + w < n) push(i + w, front);
4179
+ }
4180
+ while (front.length) {
4181
+ const grown = [];
4182
+ for (const i of front) {
4183
+ const x = i % w;
4184
+ const from = x > 0 && taken[i - 1] ? i - 1 : x < w - 1 && taken[i + 1] ? i + 1 : i >= w && taken[i - w] ? i - w : i + w < n && taken[i + w] ? i + w : -1;
4185
+ if (from < 0) continue;
4186
+ labels[i] = labels[from];
4187
+ grown.push(i);
4188
+ }
4189
+ const next = [];
4190
+ for (const i of grown) taken[i] = 1;
4191
+ for (const i of grown) {
4192
+ const x = i % w;
4193
+ if (x > 0) push(i - 1, next);
4194
+ if (x < w - 1) push(i + 1, next);
4195
+ if (i >= w) push(i - w, next);
4196
+ if (i + w < n) push(i + w, next);
4197
+ }
4198
+ front = next;
4199
+ }
4200
+ return out;
4201
+ }
4202
+ /** The median of `values` weighted by `weights`, over the indices `ok` takes; 0 if none. */
4203
+ function weightedMedian(values, weights, ok) {
4204
+ const order = [];
4205
+ let total = 0;
4206
+ for (let i = 0; i < values.length; i++) if (ok(i)) {
4207
+ order.push(i);
4208
+ total += weights[i];
4209
+ }
4210
+ order.sort((a, b) => values[a] - values[b]);
4211
+ let run = 0;
4212
+ for (const i of order) if ((run += weights[i]) >= total / 2) return values[i];
4213
+ return 0;
4214
+ }
4215
+ const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
4216
+ /** OKLab of each pixel, cached by its colour (a drawing has few). */
4217
+ function labCache(rgba) {
4218
+ const cache = /* @__PURE__ */ new Map();
4219
+ return (i) => {
4220
+ const key = rgba[i * 4] << 16 | rgba[i * 4 + 1] << 8 | rgba[i * 4 + 2];
4221
+ let v = cache.get(key);
4222
+ if (!v) cache.set(key, v = oklab([
4223
+ rgba[i * 4],
4224
+ rgba[i * 4 + 1],
4225
+ rgba[i * 4 + 2]
4226
+ ]));
4227
+ return v;
4228
+ };
4229
+ }
4230
+ /** Whether a colour lies between the paper and the line (or beyond, darker), nearer the line. */
4231
+ function blendTest(line, paper) {
4232
+ const span = [
4233
+ line[0] - paper[0],
4234
+ line[1] - paper[1],
4235
+ line[2] - paper[2]
4236
+ ];
4237
+ const len2 = span[0] ** 2 + span[1] ** 2 + span[2] ** 2;
4238
+ return (lab) => {
4239
+ if (!len2) return false;
4240
+ const d = [
4241
+ lab[0] - paper[0],
4242
+ lab[1] - paper[1],
4243
+ lab[2] - paper[2]
4244
+ ];
4245
+ const t = (d[0] * span[0] + d[1] * span[1] + d[2] * span[2]) / len2;
4246
+ const off = (d[0] - t * span[0]) ** 2 + (d[1] - t * span[1]) ** 2 + (d[2] - t * span[2]) ** 2;
4247
+ return t >= .5 && t <= 2 && off <= LINE_OFF ** 2 * len2;
4248
+ };
4249
+ }
4250
+ /**
4251
+ * Grows a line's ink into every touching opaque pixel that passes `inky`,
4252
+ * short of `blocked` ones: its anti-aliased edges, and stretches the palette
4253
+ * gave a darker shade. Without them a line comes out broken and thinner than
4254
+ * drawn.
4255
+ */
4256
+ function edgesOf(ink, blocked, w, inky) {
4257
+ const n = ink.length;
4258
+ const seen = ink.slice();
4259
+ let front = [];
4260
+ for (let i = 0; i < n; i++) if (ink[i]) front.push(i);
4261
+ const visit = (j, to) => {
4262
+ if (seen[j]) return;
4263
+ seen[j] = 1;
4264
+ if (blocked(j) || !inky(j)) return;
4265
+ ink[j] = 1;
4266
+ to.push(j);
4267
+ };
4268
+ while (front.length) {
4269
+ const next = [];
4270
+ for (const i of front) {
4271
+ const x = i % w;
4272
+ if (x > 0) visit(i - 1, next);
4273
+ if (x < w - 1) visit(i + 1, next);
4274
+ if (i >= w) visit(i - w, next);
4275
+ if (i + w < n) visit(i + w, next);
4276
+ }
4277
+ front = next;
4278
+ }
4279
+ }
1810
4280
  function findChains(comp, w, h) {
1811
4281
  const C = (x, y) => x < 0 || y < 0 || x >= w || y >= h ? VOID : comp[y * w + x];
1812
4282
  const W1 = w + 1;
@@ -1896,11 +4366,6 @@ function findChains(comp, w, h) {
1896
4366
  for (let y = 0; y < h; y++) for (let x = 0; x <= w; x++) if (vEdge[y * W1 + x]) walk(x, y, 1);
1897
4367
  return chains;
1898
4368
  }
1899
- function addOriented(map, id, c) {
1900
- const list = map.get(id);
1901
- if (list) list.push(c);
1902
- else map.set(id, [c]);
1903
- }
1904
4369
  const reverse = (cubics) => cubics.map(([a, b, c, d]) => [
1905
4370
  d,
1906
4371
  c,
@@ -1916,7 +4381,7 @@ const across = (c) => c.reversed ? c.left : c.right;
1916
4381
  function assemble(chains) {
1917
4382
  const subs = [];
1918
4383
  const open = [];
1919
- for (const c of chains) if (c.closed) subs.push(loopOf(c.cubics, across(c) === VOID, c.pts));
4384
+ for (const c of chains) if (c.closed) subs.push(loopOf(c.cubics, across(c) === VOID, c.pts, /* @__PURE__ */ new Set([across(c)]), [c]));
1920
4385
  else open.push(c);
1921
4386
  const start = (c) => c.reversed ? c.to : c.from;
1922
4387
  const end = (c) => c.reversed ? c.from : c.to;
@@ -1935,29 +4400,35 @@ function assemble(chains) {
1935
4400
  const loop = [];
1936
4401
  const pts = [];
1937
4402
  let touchesVoid = false;
4403
+ const acrossIds = /* @__PURE__ */ new Set();
4404
+ const seq = [];
1938
4405
  let c = first;
1939
4406
  while (c && !used.has(c)) {
1940
4407
  used.add(c);
4408
+ seq.push(c);
1941
4409
  loop.push(...c.cubics);
1942
4410
  pts.push(...c.reversed ? [...c.pts].reverse() : c.pts);
1943
4411
  if (across(c) === VOID) touchesVoid = true;
4412
+ acrossIds.add(across(c));
1944
4413
  if (end(c) === start(first)) break;
1945
4414
  const into = lastDir(c);
1946
4415
  c = (byStart.get(end(c)) ?? []).filter((n) => !used.has(n)).sort((a, b) => cross(into, firstDir(a)) - cross(into, firstDir(b)))[0];
1947
4416
  }
1948
- if (loop.length) subs.push(loopOf(loop, touchesVoid, pts));
4417
+ if (loop.length) subs.push(loopOf(loop, touchesVoid, pts, acrossIds, seq));
1949
4418
  }
1950
4419
  return subs;
1951
4420
  }
1952
4421
  /** A loop and its signed area (shoelace over its cubics' end points: enough to rank and orient). */
1953
- function loopOf(cubics, touchesVoid, pts) {
4422
+ function loopOf(cubics, touchesVoid, pts, acrossIds, chains) {
1954
4423
  let area = 0;
1955
4424
  for (const [a, , , d] of cubics) area += a.x * d.y - d.x * a.y;
1956
4425
  return {
1957
4426
  sub: toSubpath(cubics),
1958
4427
  area: area / 2,
1959
4428
  touchesVoid,
1960
- pts
4429
+ pts,
4430
+ across: acrossIds,
4431
+ chains
1961
4432
  };
1962
4433
  }
1963
4434
  /** One pixel centre from each 4-connected area of VOID (transparent pixels) in the image. */
@@ -2040,6 +4511,54 @@ function toSubpath(cubics) {
2040
4511
  };
2041
4512
  }
2042
4513
  //#endregion
4514
+ //#region src/centerline.ts
4515
+ /**
4516
+ * Centerline tracing: single strokes down the middle of the ink, for pen
4517
+ * plotters, engravers and handwriting, instead of outlines round it.
4518
+ *
4519
+ * 1. Threshold the image to ink and paper (as line art does), and fold specks
4520
+ * and pinholes into their surroundings so they don't become stray strokes
4521
+ * or little loops.
4522
+ * 2. Thin the ink to a one-pixel skeleton (Zhang and Suen, "A fast parallel
4523
+ * algorithm for thinning digital patterns", CACM 1984).
4524
+ * 3. Measure the stroke width: the ink's area over the skeleton's length.
4525
+ * 4. Prune spurs: short branches that thinning grows from bumps in the
4526
+ * outline, anything shorter than the stroke is wide.
4527
+ * 5. Walk the skeleton into chains between ends and junctions. Where strokes
4528
+ * cross or branch, chains that carry on in the same direction are joined,
4529
+ * so a plotter lifts its pen less.
4530
+ * 6. Fit each chain with the same curve fitter as outlines, and draw it as an
4531
+ * open (or, for a loop, closed) stroke with round caps and joins.
4532
+ *
4533
+ * Everything here is written for this project (MIT); no GPL tracer is used.
4534
+ */
4535
+ /** Trace to an SVG string; `centerline` gives the strokes as data. */
4536
+ const traceCenterline = (rgba, w, h, o) => centerlineToSvg(centerline(rgba, w, h, o));
4537
+ function centerlineToSvg(r) {
4538
+ 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`;
4540
+ }
4541
+ const round = (n) => Math.round(n * 100) / 100;
4542
+ function centerline(rgba, w, h, o) {
4543
+ const { labels, drawn } = labelBinary(rgba, w, h, o.threshold);
4544
+ joinDiagonals(labels, w, h, rgba, drawn);
4545
+ mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
4546
+ const ink = new Uint8Array(w * h);
4547
+ for (let i = 0; i < ink.length; i++) ink[i] = labels[i] === 0 ? 1 : 0;
4548
+ const { subs, measured } = skeletonStrokes(ink, w, h, o);
4549
+ const width = o.strokeWidth && o.strokeWidth > 0 ? o.strokeWidth : measured;
4550
+ return {
4551
+ width: w,
4552
+ height: h,
4553
+ paths: subs.length ? [{
4554
+ d: serializePath(subs),
4555
+ stroke: o.color ?? "#000000",
4556
+ strokeWidth: round(width)
4557
+ }] : [],
4558
+ measuredWidth: round(measured)
4559
+ };
4560
+ }
4561
+ //#endregion
2043
4562
  //#region src/symmetry.ts
2044
4563
  /**
2045
4564
  * Score every candidate symmetry: the best vertical and horizontal mirror axes
@@ -2223,4 +4742,4 @@ function detectSymmetry(rgba, w, h, options = {}) {
2223
4742
  return out.sort((a, b) => b.score - a.score);
2224
4743
  }
2225
4744
  //#endregion
2226
- export { detectSymmetry, exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, quantizePalette, serializePath, staircase, toSvg, trace, traceInlay };
4745
+ export { centerline, centerlineToSvg, colorAt, detectSymmetry, exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, quantizePalette, serializePath, staircase, toSvg, trace, traceCenterline, traceInlay };