inlaytrace 0.3.1 → 0.4.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
@@ -1,4 +1,237 @@
1
- //#region src/shapes.ts
1
+ // src/path.ts
2
+ const TOKEN = /[MmLlHhVvCcSsQqTtAaZz]|[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
3
+ const PARAMS = {
4
+ M: 2,
5
+ L: 2,
6
+ H: 1,
7
+ V: 1,
8
+ C: 6,
9
+ S: 4,
10
+ Q: 4,
11
+ T: 2,
12
+ A: 7,
13
+ Z: 0
14
+ };
15
+ const SAME = 1e-6;
16
+ function parsePath(d) {
17
+ const tokens = d.match(TOKEN) ?? [];
18
+ const subs = [];
19
+ let sub = null;
20
+ let cur = {
21
+ x: 0,
22
+ y: 0
23
+ };
24
+ let start = {
25
+ x: 0,
26
+ y: 0
27
+ };
28
+ let lastCubic = null;
29
+ let lastQuad = null;
30
+ let i = 0;
31
+ let cmd = "";
32
+ const begin = (p) => {
33
+ sub = {
34
+ nodes: [{
35
+ x: p.x,
36
+ y: p.y,
37
+ in: null,
38
+ out: null
39
+ }],
40
+ closed: false
41
+ };
42
+ subs.push(sub);
43
+ };
44
+ const ensure = () => {
45
+ if (!sub || sub.closed) begin(cur);
46
+ return sub;
47
+ };
48
+ const lineTo = (p) => {
49
+ ensure().nodes.push({
50
+ x: p.x,
51
+ y: p.y,
52
+ in: null,
53
+ out: null
54
+ });
55
+ cur = p;
56
+ };
57
+ const at = (a, b) => a.x === b.x && a.y === b.y;
58
+ const curveTo = (c1, c2, p) => {
59
+ const s = ensure();
60
+ const prev = s.nodes[s.nodes.length - 1];
61
+ prev.out = at(c1, prev) ? null : c1;
62
+ s.nodes.push({
63
+ x: p.x,
64
+ y: p.y,
65
+ in: at(c2, p) ? null : c2,
66
+ out: null
67
+ });
68
+ cur = p;
69
+ };
70
+ while (i < tokens.length) {
71
+ const t = tokens[i];
72
+ if (/[a-z]/i.test(t)) {
73
+ cmd = t;
74
+ i++;
75
+ if (cmd === "Z" || cmd === "z") {
76
+ if (sub) close(sub);
77
+ cur = start;
78
+ lastCubic = lastQuad = null;
79
+ continue;
80
+ }
81
+ } else if (!cmd) {
82
+ i++;
83
+ continue;
84
+ }
85
+ const upper = cmd.toUpperCase();
86
+ const n = PARAMS[upper];
87
+ if (i + n > tokens.length) break;
88
+ const v = tokens.slice(i, i + n).map(Number);
89
+ if (v.some((x) => !Number.isFinite(x))) break;
90
+ i += n;
91
+ const rel = cmd !== upper;
92
+ const ox = rel ? cur.x : 0;
93
+ const oy = rel ? cur.y : 0;
94
+ let cubic = null;
95
+ let quad = null;
96
+ switch (upper) {
97
+ case "M":
98
+ cur = start = {
99
+ x: v[0] + ox,
100
+ y: v[1] + oy
101
+ };
102
+ begin(cur);
103
+ cmd = rel ? "l" : "L";
104
+ break;
105
+ case "L":
106
+ lineTo({
107
+ x: v[0] + ox,
108
+ y: v[1] + oy
109
+ });
110
+ break;
111
+ case "H":
112
+ lineTo({
113
+ x: v[0] + ox,
114
+ y: cur.y
115
+ });
116
+ break;
117
+ case "V":
118
+ lineTo({
119
+ x: cur.x,
120
+ y: v[0] + oy
121
+ });
122
+ break;
123
+ case "C":
124
+ cubic = {
125
+ x: v[2] + ox,
126
+ y: v[3] + oy
127
+ };
128
+ curveTo({
129
+ x: v[0] + ox,
130
+ y: v[1] + oy
131
+ }, cubic, {
132
+ x: v[4] + ox,
133
+ y: v[5] + oy
134
+ });
135
+ break;
136
+ case "S": {
137
+ const c1 = lastCubic ? {
138
+ x: 2 * cur.x - lastCubic.x,
139
+ y: 2 * cur.y - lastCubic.y
140
+ } : cur;
141
+ cubic = {
142
+ x: v[0] + ox,
143
+ y: v[1] + oy
144
+ };
145
+ curveTo(c1, cubic, {
146
+ x: v[2] + ox,
147
+ y: v[3] + oy
148
+ });
149
+ break;
150
+ }
151
+ case "Q":
152
+ case "T": {
153
+ const q = upper === "Q" ? {
154
+ x: v[0] + ox,
155
+ y: v[1] + oy
156
+ } : lastQuad ? {
157
+ x: 2 * cur.x - lastQuad.x,
158
+ y: 2 * cur.y - lastQuad.y
159
+ } : cur;
160
+ const p = upper === "Q" ? {
161
+ x: v[2] + ox,
162
+ y: v[3] + oy
163
+ } : {
164
+ x: v[0] + ox,
165
+ y: v[1] + oy
166
+ };
167
+ const p0 = cur;
168
+ curveTo({
169
+ x: p0.x + 2 / 3 * (q.x - p0.x),
170
+ y: p0.y + 2 / 3 * (q.y - p0.y)
171
+ }, {
172
+ x: p.x + 2 / 3 * (q.x - p.x),
173
+ y: p.y + 2 / 3 * (q.y - p.y)
174
+ }, p);
175
+ quad = q;
176
+ break;
177
+ }
178
+ case "A": lineTo({
179
+ x: v[5] + ox,
180
+ y: v[6] + oy
181
+ });
182
+ }
183
+ lastCubic = cubic;
184
+ lastQuad = quad;
185
+ }
186
+ return subs;
187
+ }
188
+ function close(sub) {
189
+ if (sub.closed) return;
190
+ sub.closed = true;
191
+ const { nodes } = sub;
192
+ if (nodes.length < 2) return;
193
+ const first = nodes[0];
194
+ const last = nodes[nodes.length - 1];
195
+ if (Math.abs(first.x - last.x) < SAME && Math.abs(first.y - last.y) < SAME) {
196
+ first.in = last.in;
197
+ nodes.pop();
198
+ }
199
+ }
200
+ const num$1 = (n) => {
201
+ const r = Math.round(n * 1e3) / 1e3;
202
+ return Object.is(r, -0) ? "0" : String(r);
203
+ };
204
+ const pt = (p) => `${num$1(p.x)} ${num$1(p.y)}`;
205
+ function segment(a, b) {
206
+ return a.out || b.in ? `C${pt(a.out ?? a)} ${pt(b.in ?? b)} ${pt(b)}` : `L${pt(b)}`;
207
+ }
208
+ function serializePath(subs) {
209
+ let d = "";
210
+ for (const s of subs) {
211
+ if (!s.nodes.length) continue;
212
+ d += `M${pt(s.nodes[0])}`;
213
+ for (let i = 1; i < s.nodes.length; i++) d += segment(s.nodes[i - 1], s.nodes[i]);
214
+ if (s.closed) {
215
+ const first = s.nodes[0];
216
+ const last = s.nodes[s.nodes.length - 1];
217
+ if (s.nodes.length > 1 && (last.out || first.in)) d += segment(last, first);
218
+ d += "Z";
219
+ }
220
+ }
221
+ return d;
222
+ }
223
+ function mapPoints(subs, f) {
224
+ const m = (p) => p ? f(p) : null;
225
+ return subs.map((s) => ({
226
+ closed: s.closed,
227
+ nodes: s.nodes.map((n) => ({
228
+ ...f(n),
229
+ in: m(n.in),
230
+ out: m(n.out)
231
+ }))
232
+ }));
233
+ }
234
+ // src/shapes.ts
2
235
  /** How closely an outline must follow a shape: RMS and worst distance, in px, of its pixel-edge midpoints. */
3
236
  const MAX_RMS$1 = .3;
4
237
  const MAX_OFF = .85;
@@ -146,7 +379,7 @@ function roundShape(f, p, mids) {
146
379
  const { u, v } = local(q, f.cx, f.cy, cos, sin);
147
380
  const F = u * u / (a * a) + v * v / (b * b) - 1;
148
381
  const g = 2 * Math.hypot(u / (a * a), v / (b * b));
149
- return g > 1e-12 ? F / g : Infinity;
382
+ return g > 1e-12 ? F / g : 1e400;
150
383
  };
151
384
  if (fits(mids, off)) {
152
385
  const cubics = [
@@ -271,7 +504,7 @@ function withCorners(f, corners, mids) {
271
504
  y: f.cy + R * Math.sin(phase + i * step)
272
505
  }));
273
506
  const off = (q) => {
274
- let best = Infinity;
507
+ let best = 1e400;
275
508
  for (let i = 0; i < k; i++) {
276
509
  const a = vertices[i];
277
510
  const b = vertices[(i + 1) % k];
@@ -288,8 +521,7 @@ function withCorners(f, corners, mids) {
288
521
  cubics: vertices.map((a, i) => lineTo(a, vertices[(i + 1) % k]))
289
522
  };
290
523
  }
291
- //#endregion
292
- //#region src/fit.ts
524
+ // src/fit.ts
293
525
  const R = 6;
294
526
  const END_TRIM = 3;
295
527
  const SMOOTH$1 = 12;
@@ -617,7 +849,7 @@ function along(pts, closed, i, ds) {
617
849
  return pts[k];
618
850
  }
619
851
  /** Px of chain available before (side -1) or after (side 1) sample i. Points are ≈ 1 px apart. */
620
- const room = (n, closed, i, side) => closed ? Infinity : side < 0 ? i : n - 1 - i;
852
+ const room = (n, closed, i, side) => closed ? 1e400 : side < 0 ? i : n - 1 - i;
621
853
  /**
622
854
  * How far the chain turns at sample i over r px each side, in degrees. Near an
623
855
  * open chain's end (a junction, where a peak often sits) it measures over what
@@ -652,7 +884,7 @@ function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
652
884
  const half = interior / 2 * Math.PI / 180;
653
885
  const reachOut = 1 / Math.sin(half) - 1;
654
886
  if (!x || dist$2(x, pts[i]) > Math.min(MAX_REACH_OUT, R / 2 + maxRounding * reachOut)) continue;
655
- let d = Infinity;
887
+ let d = 1e400;
656
888
  for (let k = -6; k <= R; k++) {
657
889
  const j = closed ? ((i + k) % n + n) % n : i + k;
658
890
  if (j >= 0 && j < n) d = Math.min(d, dist$2(pts[j], x));
@@ -768,7 +1000,7 @@ function smooth(run, loop, half) {
768
1000
  if (!h || n < 4) return {
769
1001
  flat: run,
770
1002
  true: run,
771
- minRadius: Infinity,
1003
+ minRadius: 1e400,
772
1004
  radius: new Float64Array(n).fill(1e9)
773
1005
  };
774
1006
  const m = loop ? n - 1 : n;
@@ -804,7 +1036,7 @@ function smooth(run, loop, half) {
804
1036
  for (let i = 0; i < m; i++) raw[i] = Math.max(radiusAt(i, r), radiusAt(i, 15));
805
1037
  const allow = new Int32Array(m);
806
1038
  const radius = new Float64Array(loop ? m + 1 : m);
807
- let minRadius = Infinity;
1039
+ let minRadius = 1e400;
808
1040
  for (let i = 0; i < m; i++) {
809
1041
  const win = [];
810
1042
  for (let k = -3; k <= 3; k++) {
@@ -1080,8 +1312,7 @@ function newton(b, p, u) {
1080
1312
  if (Math.abs(den) < 1e-12) return u;
1081
1313
  return Math.min(1, Math.max(0, u - num / den));
1082
1314
  }
1083
- //#endregion
1084
- //#region src/palette.ts
1315
+ // src/palette.ts
1085
1316
  function peakPalette(rgba, maxColors, { minDistance = .07, minShare = .002, minDetail = 5e-4, width, minTint = .02, minFlat = .001 } = {}) {
1086
1317
  const bins = histogram(rgba);
1087
1318
  for (let i = 0; i < rgba.length; i += 4) if (rgba[i + 3] >= 128) bins.add(i);
@@ -1341,335 +1572,101 @@ function quantizePalette(rgba, maxColors, { iterations = 16 } = {}) {
1341
1572
  const nearest = points.map((p) => distance2(p.lab, centres[0]));
1342
1573
  while (centres.length < k) {
1343
1574
  let best = 0;
1344
- let bestScore = -1;
1345
- points.forEach((p, i) => {
1346
- const score = p.n * nearest[i];
1347
- if (score > bestScore) {
1348
- bestScore = score;
1349
- best = i;
1350
- }
1351
- });
1352
- if (bestScore <= 0) break;
1353
- centres.push(points[best].lab);
1354
- points.forEach((p, i) => nearest[i] = Math.min(nearest[i], distance2(p.lab, points[best].lab)));
1355
- }
1356
- const assign = new Int32Array(points.length);
1357
- for (let it = 0; it < iterations; it++) {
1358
- let moved = false;
1359
- points.forEach((p, i) => {
1360
- let best = 0;
1361
- let bestD = Infinity;
1362
- centres.forEach((c, j) => {
1363
- const d = distance2(p.lab, c);
1364
- if (d < bestD) {
1365
- bestD = d;
1366
- best = j;
1367
- }
1368
- });
1369
- if (assign[i] !== best || it === 0) moved = true;
1370
- assign[i] = best;
1371
- });
1372
- const sums = centres.map(() => ({
1373
- n: 0,
1374
- l: 0,
1375
- a: 0,
1376
- b: 0
1377
- }));
1378
- points.forEach((p, i) => {
1379
- const s = sums[assign[i]];
1380
- s.n += p.n;
1381
- s.l += p.lab[0] * p.n;
1382
- s.a += p.lab[1] * p.n;
1383
- s.b += p.lab[2] * p.n;
1384
- });
1385
- sums.forEach((s, j) => {
1386
- if (s.n) centres[j] = [
1387
- s.l / s.n,
1388
- s.a / s.n,
1389
- s.b / s.n
1390
- ];
1391
- });
1392
- if (!moved) break;
1393
- }
1394
- const out = centres.map(() => ({
1395
- n: 0,
1396
- r: 0,
1397
- g: 0,
1398
- b: 0
1399
- }));
1400
- points.forEach((p, i) => {
1401
- const o = out[assign[i]];
1402
- o.n += p.n;
1403
- o.r += p.rgb[0] * p.n;
1404
- o.g += p.rgb[1] * p.n;
1405
- o.b += p.rgb[2] * p.n;
1406
- });
1407
- const hexes = out.filter((o) => o.n).sort((a, b) => b.n - a.n).map((o) => toHex([
1408
- o.r / o.n,
1409
- o.g / o.n,
1410
- o.b / o.n
1411
- ]));
1412
- return [...new Set(hexes)];
1413
- }
1414
- const distance2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
1415
- const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
1416
- const toHex = (rgb) => `#${rgb.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
1417
- /**
1418
- * Pixel art's palette: its colours exactly, most-used first. Pixel art has a
1419
- * handful of deliberate colours, and a one-pixel eye matters as much as the
1420
- * sky, so nothing is merged or dropped for being rare or close to another.
1421
- * Beyond `maxColors` distinct colours (a photo picked as pixel art), the
1422
- * rarest ones take their nearest kept colour when pixels are labelled.
1423
- */
1424
- function exactPalette(rgba, maxColors) {
1425
- const counts = /* @__PURE__ */ new Map();
1426
- for (let i = 0; i < rgba.length; i += 4) {
1427
- if (rgba[i + 3] < 128) continue;
1428
- const key = rgba[i] << 16 | rgba[i + 1] << 8 | rgba[i + 2];
1429
- counts.set(key, (counts.get(key) ?? 0) + 1);
1430
- }
1431
- 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")}`);
1432
- }
1433
- /** '#rrggbb' as [r, g, b]. */
1434
- const hexToRgb = (hex) => [
1435
- parseInt(hex.slice(1, 3), 16),
1436
- parseInt(hex.slice(3, 5), 16),
1437
- parseInt(hex.slice(5, 7), 16)
1438
- ];
1439
- //#endregion
1440
- //#region src/path.ts
1441
- const TOKEN = /[MmLlHhVvCcSsQqTtAaZz]|[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
1442
- const PARAMS = {
1443
- M: 2,
1444
- L: 2,
1445
- H: 1,
1446
- V: 1,
1447
- C: 6,
1448
- S: 4,
1449
- Q: 4,
1450
- T: 2,
1451
- A: 7,
1452
- Z: 0
1453
- };
1454
- const SAME = 1e-6;
1455
- function parsePath(d) {
1456
- const tokens = d.match(TOKEN) ?? [];
1457
- const subs = [];
1458
- let sub = null;
1459
- let cur = {
1460
- x: 0,
1461
- y: 0
1462
- };
1463
- let start = {
1464
- x: 0,
1465
- y: 0
1466
- };
1467
- let lastCubic = null;
1468
- let lastQuad = null;
1469
- let i = 0;
1470
- let cmd = "";
1471
- const begin = (p) => {
1472
- sub = {
1473
- nodes: [{
1474
- x: p.x,
1475
- y: p.y,
1476
- in: null,
1477
- out: null
1478
- }],
1479
- closed: false
1480
- };
1481
- subs.push(sub);
1482
- };
1483
- const ensure = () => {
1484
- if (!sub || sub.closed) begin(cur);
1485
- return sub;
1486
- };
1487
- const lineTo = (p) => {
1488
- ensure().nodes.push({
1489
- x: p.x,
1490
- y: p.y,
1491
- in: null,
1492
- out: null
1493
- });
1494
- cur = p;
1495
- };
1496
- const at = (a, b) => a.x === b.x && a.y === b.y;
1497
- const curveTo = (c1, c2, p) => {
1498
- const s = ensure();
1499
- const prev = s.nodes[s.nodes.length - 1];
1500
- prev.out = at(c1, prev) ? null : c1;
1501
- s.nodes.push({
1502
- x: p.x,
1503
- y: p.y,
1504
- in: at(c2, p) ? null : c2,
1505
- out: null
1506
- });
1507
- cur = p;
1508
- };
1509
- while (i < tokens.length) {
1510
- const t = tokens[i];
1511
- if (/[a-z]/i.test(t)) {
1512
- cmd = t;
1513
- i++;
1514
- if (cmd === "Z" || cmd === "z") {
1515
- if (sub) close(sub);
1516
- cur = start;
1517
- lastCubic = lastQuad = null;
1518
- continue;
1519
- }
1520
- } else if (!cmd) {
1521
- i++;
1522
- continue;
1523
- }
1524
- const upper = cmd.toUpperCase();
1525
- const n = PARAMS[upper];
1526
- if (i + n > tokens.length) break;
1527
- const v = tokens.slice(i, i + n).map(Number);
1528
- if (v.some((x) => !Number.isFinite(x))) break;
1529
- i += n;
1530
- const rel = cmd !== upper;
1531
- const ox = rel ? cur.x : 0;
1532
- const oy = rel ? cur.y : 0;
1533
- let cubic = null;
1534
- let quad = null;
1535
- switch (upper) {
1536
- case "M":
1537
- cur = start = {
1538
- x: v[0] + ox,
1539
- y: v[1] + oy
1540
- };
1541
- begin(cur);
1542
- cmd = rel ? "l" : "L";
1543
- break;
1544
- case "L":
1545
- lineTo({
1546
- x: v[0] + ox,
1547
- y: v[1] + oy
1548
- });
1549
- break;
1550
- case "H":
1551
- lineTo({
1552
- x: v[0] + ox,
1553
- y: cur.y
1554
- });
1555
- break;
1556
- case "V":
1557
- lineTo({
1558
- x: cur.x,
1559
- y: v[0] + oy
1560
- });
1561
- break;
1562
- case "C":
1563
- cubic = {
1564
- x: v[2] + ox,
1565
- y: v[3] + oy
1566
- };
1567
- curveTo({
1568
- x: v[0] + ox,
1569
- y: v[1] + oy
1570
- }, cubic, {
1571
- x: v[4] + ox,
1572
- y: v[5] + oy
1573
- });
1574
- break;
1575
- case "S": {
1576
- const c1 = lastCubic ? {
1577
- x: 2 * cur.x - lastCubic.x,
1578
- y: 2 * cur.y - lastCubic.y
1579
- } : cur;
1580
- cubic = {
1581
- x: v[0] + ox,
1582
- y: v[1] + oy
1583
- };
1584
- curveTo(c1, cubic, {
1585
- x: v[2] + ox,
1586
- y: v[3] + oy
1587
- });
1588
- break;
1589
- }
1590
- case "Q":
1591
- case "T": {
1592
- const q = upper === "Q" ? {
1593
- x: v[0] + ox,
1594
- y: v[1] + oy
1595
- } : lastQuad ? {
1596
- x: 2 * cur.x - lastQuad.x,
1597
- y: 2 * cur.y - lastQuad.y
1598
- } : cur;
1599
- const p = upper === "Q" ? {
1600
- x: v[2] + ox,
1601
- y: v[3] + oy
1602
- } : {
1603
- x: v[0] + ox,
1604
- y: v[1] + oy
1605
- };
1606
- const p0 = cur;
1607
- curveTo({
1608
- x: p0.x + 2 / 3 * (q.x - p0.x),
1609
- y: p0.y + 2 / 3 * (q.y - p0.y)
1610
- }, {
1611
- x: p.x + 2 / 3 * (q.x - p.x),
1612
- y: p.y + 2 / 3 * (q.y - p.y)
1613
- }, p);
1614
- quad = q;
1615
- break;
1575
+ let bestScore = -1;
1576
+ points.forEach((p, i) => {
1577
+ const score = p.n * nearest[i];
1578
+ if (score > bestScore) {
1579
+ bestScore = score;
1580
+ best = i;
1616
1581
  }
1617
- case "A": lineTo({
1618
- x: v[5] + ox,
1619
- y: v[6] + oy
1620
- });
1621
- }
1622
- lastCubic = cubic;
1623
- lastQuad = quad;
1582
+ });
1583
+ if (bestScore <= 0) break;
1584
+ centres.push(points[best].lab);
1585
+ points.forEach((p, i) => nearest[i] = Math.min(nearest[i], distance2(p.lab, points[best].lab)));
1624
1586
  }
1625
- return subs;
1626
- }
1627
- function close(sub) {
1628
- if (sub.closed) return;
1629
- sub.closed = true;
1630
- const { nodes } = sub;
1631
- if (nodes.length < 2) return;
1632
- const first = nodes[0];
1633
- const last = nodes[nodes.length - 1];
1634
- if (Math.abs(first.x - last.x) < SAME && Math.abs(first.y - last.y) < SAME) {
1635
- first.in = last.in;
1636
- nodes.pop();
1587
+ const assign = new Int32Array(points.length);
1588
+ for (let it = 0; it < iterations; it++) {
1589
+ let moved = false;
1590
+ points.forEach((p, i) => {
1591
+ let best = 0;
1592
+ let bestD = 1e400;
1593
+ centres.forEach((c, j) => {
1594
+ const d = distance2(p.lab, c);
1595
+ if (d < bestD) {
1596
+ bestD = d;
1597
+ best = j;
1598
+ }
1599
+ });
1600
+ if (assign[i] !== best || it === 0) moved = true;
1601
+ assign[i] = best;
1602
+ });
1603
+ const sums = centres.map(() => ({
1604
+ n: 0,
1605
+ l: 0,
1606
+ a: 0,
1607
+ b: 0
1608
+ }));
1609
+ points.forEach((p, i) => {
1610
+ const s = sums[assign[i]];
1611
+ s.n += p.n;
1612
+ s.l += p.lab[0] * p.n;
1613
+ s.a += p.lab[1] * p.n;
1614
+ s.b += p.lab[2] * p.n;
1615
+ });
1616
+ sums.forEach((s, j) => {
1617
+ if (s.n) centres[j] = [
1618
+ s.l / s.n,
1619
+ s.a / s.n,
1620
+ s.b / s.n
1621
+ ];
1622
+ });
1623
+ if (!moved) break;
1637
1624
  }
1625
+ const out = centres.map(() => ({
1626
+ n: 0,
1627
+ r: 0,
1628
+ g: 0,
1629
+ b: 0
1630
+ }));
1631
+ points.forEach((p, i) => {
1632
+ const o = out[assign[i]];
1633
+ o.n += p.n;
1634
+ o.r += p.rgb[0] * p.n;
1635
+ o.g += p.rgb[1] * p.n;
1636
+ o.b += p.rgb[2] * p.n;
1637
+ });
1638
+ const hexes = out.filter((o) => o.n).sort((a, b) => b.n - a.n).map((o) => toHex([
1639
+ o.r / o.n,
1640
+ o.g / o.n,
1641
+ o.b / o.n
1642
+ ]));
1643
+ return [...new Set(hexes)];
1638
1644
  }
1639
- const num$1 = (n) => {
1640
- const r = Math.round(n * 1e3) / 1e3;
1641
- return Object.is(r, -0) ? "0" : String(r);
1642
- };
1643
- const pt = (p) => `${num$1(p.x)} ${num$1(p.y)}`;
1644
- function segment(a, b) {
1645
- return a.out || b.in ? `C${pt(a.out ?? a)} ${pt(b.in ?? b)} ${pt(b)}` : `L${pt(b)}`;
1646
- }
1647
- function serializePath(subs) {
1648
- let d = "";
1649
- for (const s of subs) {
1650
- if (!s.nodes.length) continue;
1651
- d += `M${pt(s.nodes[0])}`;
1652
- for (let i = 1; i < s.nodes.length; i++) d += segment(s.nodes[i - 1], s.nodes[i]);
1653
- if (s.closed) {
1654
- const first = s.nodes[0];
1655
- const last = s.nodes[s.nodes.length - 1];
1656
- if (s.nodes.length > 1 && (last.out || first.in)) d += segment(last, first);
1657
- d += "Z";
1658
- }
1645
+ const distance2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
1646
+ const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
1647
+ const toHex = (rgb) => `#${rgb.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
1648
+ /**
1649
+ * Pixel art's palette: its colours exactly, most-used first. Pixel art has a
1650
+ * handful of deliberate colours, and a one-pixel eye matters as much as the
1651
+ * sky, so nothing is merged or dropped for being rare or close to another.
1652
+ * Beyond `maxColors` distinct colours (a photo picked as pixel art), the
1653
+ * rarest ones take their nearest kept colour when pixels are labelled.
1654
+ */
1655
+ function exactPalette(rgba, maxColors) {
1656
+ const counts = /* @__PURE__ */ new Map();
1657
+ for (let i = 0; i < rgba.length; i += 4) {
1658
+ if (rgba[i + 3] < 128) continue;
1659
+ const key = rgba[i] << 16 | rgba[i + 1] << 8 | rgba[i + 2];
1660
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1659
1661
  }
1660
- return d;
1661
- }
1662
- function mapPoints(subs, f) {
1663
- const m = (p) => p ? f(p) : null;
1664
- return subs.map((s) => ({
1665
- closed: s.closed,
1666
- nodes: s.nodes.map((n) => ({
1667
- ...f(n),
1668
- in: m(n.in),
1669
- out: m(n.out)
1670
- }))
1671
- }));
1662
+ 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")}`);
1672
1663
  }
1664
+ /** '#rrggbb' as [r, g, b]. */
1665
+ const hexToRgb = (hex) => [
1666
+ parseInt(hex.slice(1, 3), 16),
1667
+ parseInt(hex.slice(3, 5), 16),
1668
+ parseInt(hex.slice(5, 7), 16)
1669
+ ];
1673
1670
  const sub = (a, b) => ({
1674
1671
  x: a.x - b.x,
1675
1672
  y: a.y - b.y
@@ -1874,8 +1871,7 @@ function complete(p0, t0, p1, t1, visible, straight0, straight1, hidden) {
1874
1871
  }
1875
1872
  return null;
1876
1873
  }
1877
- //#endregion
1878
- //#region src/skeleton.ts
1874
+ // src/skeleton.ts
1879
1875
  /**
1880
1876
  * Skeleton strokes: thin ink to a one-pixel skeleton and fit it as strokes
1881
1877
  * down the middle. Centerline traces a whole drawing this way; outline art
@@ -2580,8 +2576,7 @@ function toSubpath$1(cubics, closed) {
2580
2576
  nodes
2581
2577
  };
2582
2578
  }
2583
- //#endregion
2584
- //#region src/gradient.ts
2579
+ // src/gradient.ts
2585
2580
  /**
2586
2581
  * Gradient fills for softly shaded regions.
2587
2582
  *
@@ -2787,8 +2782,6 @@ function shadings(rgba, w, h, comp, regions, colorOf) {
2787
2782
  ]));
2788
2783
  return out;
2789
2784
  }
2790
- /** A gradient's colour at a point. */
2791
- const colorAt = (g, x, y) => ramp(g)(x, y);
2792
2785
  /**
2793
2786
  * Whether the gradient draws any one band of the shade worse than the band's
2794
2787
  * own flat colour did: a gradient that suits the whole on average can still
@@ -2972,9 +2965,9 @@ function fitRadial(xs, ys, cs) {
2972
2965
  * from the least t to the greatest, as few as come within a level of the most.
2973
2966
  * Offsets run 0–1 over [t0, t1]. With `from`, t0 is at least that.
2974
2967
  */
2975
- function fitRamp(t, cs, from = -Infinity) {
2976
- let t0 = Infinity;
2977
- let t1 = -Infinity;
2968
+ function fitRamp(t, cs, from = -1e400) {
2969
+ let t0 = 1e400;
2970
+ let t1 = -1e400;
2978
2971
  for (const tj of t) {
2979
2972
  if (tj < t0) t0 = tj;
2980
2973
  if (tj > t1) t1 = tj;
@@ -3084,8 +3077,7 @@ function leastSquares(rows, y) {
3084
3077
  const clamp = (v) => Math.max(0, Math.min(255, v));
3085
3078
  const dist2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
3086
3079
  const round$1 = (v, places) => Math.round(v * 10 ** places) / 10 ** places;
3087
- //#endregion
3088
- //#region src/gaps.ts
3080
+ // src/gaps.ts
3089
3081
  /**
3090
3082
  * Gap closing (#145): join a line's ends across a small break, before tracing,
3091
3083
  * so a drawn outline that came out in pieces (a lossy save, a faint stretch of
@@ -3368,8 +3360,7 @@ function paint(ink, w, h, ax, ay, bx, by, r) {
3368
3360
  if ((px - ax - vx * t) ** 2 + (py - ay - vy * t) ** 2 <= rr * rr) ink[y * w + x] = 1;
3369
3361
  }
3370
3362
  }
3371
- //#endregion
3372
- //#region src/inlay.ts
3363
+ // src/inlay.ts
3373
3364
  /**
3374
3365
  * Inlay, our shared-edge tracer: every preset, from logos to photos.
3375
3366
  * Like inlaid wood, every piece is cut to fit its neighbours exactly.
@@ -3433,13 +3424,11 @@ function gradientMarkup(g, id) {
3433
3424
  const stops = g.stops.map((s) => `<stop offset="${num(s.offset * 100)}%" stop-color="${attr(s.color)}"/>`).join("");
3434
3425
  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>`;
3435
3426
  }
3436
- /** Trace to an SVG string; `trace` gives the shapes as data. */
3437
- const traceInlay = (rgba, w, h, o) => toSvg(trace(rgba, w, h, o));
3438
3427
  /**
3439
3428
  * Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
3440
3429
  * into filled shapes that share their edges exactly.
3441
3430
  */
3442
- function trace(rgba, w, h, o) {
3431
+ function traceRaw(rgba, w, h, o) {
3443
3432
  const { labels, colors, drawn } = o.mode === "palette" ? labelPalette(rgba, w, h, o.palette, !o.photo) : labelBinary(rgba, w, h, o.threshold);
3444
3433
  const clean = o.mode === "palette" && !o.pixels && !o.photo && lossless(rgba, labels, w, h, colors);
3445
3434
  if (o.mode === "palette" && o.merge) mergeLabels(labels, colors, o.merge);
@@ -3957,7 +3946,7 @@ function pairsOf(pal, labs) {
3957
3946
  function mixOf(rgb, lab, pairs, labs, solid) {
3958
3947
  let best;
3959
3948
  let bd = solid;
3960
- let bspan = Infinity;
3949
+ let bspan = 1e400;
3961
3950
  for (const { i, j, a, d, len, span } of pairs) {
3962
3951
  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));
3963
3952
  const m = oklab([
@@ -4002,8 +3991,8 @@ function labelPalette(rgba, w, h, palette, flat) {
4002
3991
  b
4003
3992
  ]);
4004
3993
  let best = 0;
4005
- let d1 = Infinity;
4006
- let d2 = Infinity;
3994
+ let d1 = 1e400;
3995
+ let d2 = 1e400;
4007
3996
  labs.forEach((p, k) => {
4008
3997
  const d = Math.hypot(lab[0] - p[0], lab[1] - p[1], lab[2] - p[2]);
4009
3998
  if (d < d1) {
@@ -4012,7 +4001,7 @@ function labelPalette(rgba, w, h, palette, flat) {
4012
4001
  best = k;
4013
4002
  } else if (d < d2) d2 = d;
4014
4003
  });
4015
- const between = d2 < Infinity && d1 > .4 * d2;
4004
+ const between = d2 < 1e400 && d1 > .4 * d2;
4016
4005
  if (between && pairs && d1 > MIX_FAR) best = mixOf([
4017
4006
  r,
4018
4007
  g,
@@ -4034,7 +4023,7 @@ function labelPalette(rgba, w, h, palette, flat) {
4034
4023
  rgba[i * 4 + 2]
4035
4024
  ]);
4036
4025
  let best = -1;
4037
- let bd = Infinity;
4026
+ let bd = 1e400;
4038
4027
  let kinds = 0;
4039
4028
  let seen = -1;
4040
4029
  for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
@@ -4373,13 +4362,13 @@ function mergeSpecksOnce(labels, w, h, minArea, labs) {
4373
4362
  let most = 0;
4374
4363
  const mine = labs?.[own];
4375
4364
  if (mine) {
4376
- let near = Infinity;
4365
+ let near = 1e400;
4377
4366
  for (const [l, v] of votes) {
4378
4367
  const lab = labs[l];
4379
- const d = lab ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : Infinity;
4368
+ const d = lab ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : 1e400;
4380
4369
  if (d < near || d === near && v > most) near = d, most = v, best = l;
4381
4370
  }
4382
- if (near > SPECK_CONTRAST && near < Infinity && end - begin >= Math.max(SPECK_MIN, minArea * SPECK_SHAPE)) continue;
4371
+ if (near > SPECK_CONTRAST && near < 1e400 && end - begin >= Math.max(SPECK_MIN, minArea * SPECK_SHAPE)) continue;
4383
4372
  } else for (const [l, v] of votes) if (v > most) most = v, best = l;
4384
4373
  if (best !== own) {
4385
4374
  for (let k = begin; k < end; k++) labels[pixels[k]] = best;
@@ -4457,7 +4446,7 @@ function mergeSlivers(labels, w, h, labs, lines) {
4457
4446
  let bd = SLIVER_DISTANCE;
4458
4447
  for (const n of near) {
4459
4448
  const lab = labs[label[n]];
4460
- const d = lab && ok(n) ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : Infinity;
4449
+ const d = lab && ok(n) ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : 1e400;
4461
4450
  if (d < bd) bd = d, best = label[n];
4462
4451
  }
4463
4452
  return best;
@@ -5068,8 +5057,65 @@ function toSubpath(cubics) {
5068
5057
  nodes
5069
5058
  };
5070
5059
  }
5071
- //#endregion
5072
- //#region src/smooth.ts
5060
+ // src/centerline.ts
5061
+ /**
5062
+ * Centerline tracing: single strokes down the middle of the ink, for pen
5063
+ * plotters, engravers and handwriting, instead of outlines round it.
5064
+ *
5065
+ * 1. Threshold the image to ink and paper (as line art does), and fold specks
5066
+ * and pinholes into their surroundings so they don't become stray strokes
5067
+ * or little loops.
5068
+ * 2. Thin the ink to a one-pixel skeleton (Zhang and Suen, "A fast parallel
5069
+ * algorithm for thinning digital patterns", CACM 1984).
5070
+ * 3. Measure the stroke width: the ink's area over the skeleton's length.
5071
+ * 4. Prune spurs: short branches that thinning grows from bumps in the
5072
+ * outline, anything shorter than the stroke is wide.
5073
+ * 5. Walk the skeleton into chains between ends and junctions. Where strokes
5074
+ * cross or branch, chains that carry on in the same direction are joined,
5075
+ * so a plotter lifts its pen less.
5076
+ * 6. Fit each chain with the same curve fitter as outlines, and draw it as an
5077
+ * open (or, for a loop, closed) stroke with round caps and joins.
5078
+ *
5079
+ * Everything here is written for this project (MIT); no GPL tracer is used.
5080
+ */
5081
+ /**
5082
+ * Trace to an SVG string; `centerline` gives the strokes as data.
5083
+ * @deprecated Since 0.4: use `toSvg(trace(image, { preset: 'centerline' }))`.
5084
+ */
5085
+ const traceCenterline = (rgba, w, h, o) => toSvg(centerline(rgba, w, h, o));
5086
+ /** @deprecated Since 0.4: `toSvg` draws stroked paths the same way. */
5087
+ const centerlineToSvg = (r) => toSvg(r);
5088
+ const round = (n) => Math.round(n * 100) / 100;
5089
+ function centerline(rgba, w, h, o) {
5090
+ const { labels, drawn } = labelBinary(rgba, w, h, o.threshold);
5091
+ joinDiagonals(labels, w, h, rgba, drawn);
5092
+ mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
5093
+ const ink = new Uint8Array(w * h);
5094
+ for (let i = 0; i < ink.length; i++) ink[i] = labels[i] === 0 ? 1 : 0;
5095
+ const skel = o.closeGaps ? thin(ink, w, h) : void 0;
5096
+ const joined = !!skel && closeGaps(ink, w, h, {
5097
+ scale: o.scale,
5098
+ skel
5099
+ }) > 0;
5100
+ if (joined) {
5101
+ for (let i = 0; i < ink.length; i++) if (ink[i]) labels[i] = 0;
5102
+ mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
5103
+ for (let i = 0; i < ink.length; i++) ink[i] = labels[i] === 0 ? 1 : 0;
5104
+ }
5105
+ const { subs, measured } = skeletonStrokes(ink, w, h, o, joined ? void 0 : skel);
5106
+ const width = o.strokeWidth && o.strokeWidth > 0 ? o.strokeWidth : measured;
5107
+ return {
5108
+ width: w,
5109
+ height: h,
5110
+ paths: subs.length ? [{
5111
+ d: serializePath(subs),
5112
+ fill: o.color ?? "#000000",
5113
+ stroke: round(width)
5114
+ }] : [],
5115
+ measuredWidth: round(measured)
5116
+ };
5117
+ }
5118
+ // src/smooth.ts
5073
5119
  /**
5074
5120
  * Edge-preserving smoothing for painted art, before its palette is picked.
5075
5121
  *
@@ -5254,66 +5300,214 @@ function boostLines(rgba, width, height, radius = 2, lines) {
5254
5300
  }
5255
5301
  return out;
5256
5302
  }
5257
- //#endregion
5258
- //#region src/centerline.ts
5303
+ // src/presets.ts
5259
5304
  /**
5260
- * Centerline tracing: single strokes down the middle of the ink, for pen
5261
- * plotters, engravers and handwriting, instead of outlines round it.
5262
- *
5263
- * 1. Threshold the image to ink and paper (as line art does), and fold specks
5264
- * and pinholes into their surroundings so they don't become stray strokes
5265
- * or little loops.
5266
- * 2. Thin the ink to a one-pixel skeleton (Zhang and Suen, "A fast parallel
5267
- * algorithm for thinning digital patterns", CACM 1984).
5268
- * 3. Measure the stroke width: the ink's area over the skeleton's length.
5269
- * 4. Prune spurs: short branches that thinning grows from bumps in the
5270
- * outline, anything shorter than the stroke is wide.
5271
- * 5. Walk the skeleton into chains between ends and junctions. Where strokes
5272
- * cross or branch, chains that carry on in the same direction are joined,
5273
- * so a plotter lifts its pen less.
5274
- * 6. Fit each chain with the same curve fitter as outlines, and draw it as an
5275
- * open (or, for a loop, closed) stroke with round caps and joins.
5305
+ * Presets and the one-call API (#162, #163): `trace(image, { preset })`.
5276
5306
  *
5277
- * Everything here is written for this project (MIT); no GPL tracer is used.
5307
+ * Each preset is a recipe the app tuned and `npm run score` measures: how the
5308
+ * palette is picked, what runs before tracing, and the fitting defaults. Any
5309
+ * option given overrides the preset's. The app reads its presets from here,
5310
+ * so the package and the app can't drift apart.
5311
+ */
5312
+ const ILLUSTRATION = {
5313
+ kind: "colour",
5314
+ colors: 24,
5315
+ speckle: 4,
5316
+ tolerance: .75,
5317
+ cornerAngle: 60,
5318
+ shapes: true,
5319
+ layers: true,
5320
+ gradients: true
5321
+ };
5322
+ /** Every preset's defaults, as the app shows them. */
5323
+ const presets = {
5324
+ logo: {
5325
+ kind: "colour",
5326
+ colors: 8,
5327
+ speckle: 8,
5328
+ tolerance: 1,
5329
+ cornerAngle: 45,
5330
+ shapes: true,
5331
+ layers: false
5332
+ },
5333
+ illustration: ILLUSTRATION,
5334
+ outline: {
5335
+ ...ILLUSTRATION,
5336
+ strokes: true,
5337
+ closeGaps: true
5338
+ },
5339
+ lineart: {
5340
+ kind: "ink",
5341
+ threshold: "auto",
5342
+ speckle: 6,
5343
+ tolerance: 1,
5344
+ cornerAngle: 45,
5345
+ shapes: true,
5346
+ closeGaps: true
5347
+ },
5348
+ centerline: {
5349
+ kind: "centerline",
5350
+ threshold: "auto",
5351
+ speckle: 4,
5352
+ tolerance: 1,
5353
+ cornerAngle: 45,
5354
+ closeGaps: true
5355
+ },
5356
+ poster: {
5357
+ kind: "colour",
5358
+ colors: 24,
5359
+ speckle: 8,
5360
+ tolerance: .75,
5361
+ cornerAngle: 90,
5362
+ layers: true
5363
+ },
5364
+ pixel: {
5365
+ kind: "colour",
5366
+ colors: 32,
5367
+ speckle: 0,
5368
+ tolerance: .25,
5369
+ cornerAngle: 0
5370
+ }
5371
+ };
5372
+ const PICKER = {
5373
+ logo: "peak",
5374
+ illustration: "peak",
5375
+ outline: "peak",
5376
+ poster: "quantize",
5377
+ pixel: "exact"
5378
+ };
5379
+ /** Below this share of opaque pixels in its exact colours, an image isn't treated as pixel art. */
5380
+ const EXACT_COVERAGE = .9;
5381
+ /**
5382
+ * The share of opaque pixels whose colour is exactly one of `palette`, not
5383
+ * counting its first (commonest) colour. A JPEG drawing on a white page is
5384
+ * 88% white, so counting the page passed it as pixel art; its other 31
5385
+ * "exact" colours were near-whites, and the blue drawing traced as white.
5278
5386
  */
5279
- /** Trace to an SVG string; `centerline` gives the strokes as data. */
5280
- const traceCenterline = (rgba, w, h, o) => centerlineToSvg(centerline(rgba, w, h, o));
5281
- function centerlineToSvg(r) {
5282
- 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"/>`);
5283
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${attr(r.width)}" height="${attr(r.height)}" viewBox="0 0 ${attr(r.width)} ${attr(r.height)}">\n${paths.join("\n")}\n</svg>\n`;
5387
+ function coverage(pixels, palette) {
5388
+ const set = new Set(palette.map((hex) => parseInt(hex.slice(1), 16)));
5389
+ const first = palette.length ? parseInt(palette[0].slice(1), 16) : -1;
5390
+ let opaque = 0;
5391
+ let hit = 0;
5392
+ for (let i = 0; i < pixels.length; i += 4) {
5393
+ if (pixels[i + 3] < 128) continue;
5394
+ const c = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
5395
+ if (c === first) continue;
5396
+ opaque++;
5397
+ if (set.has(c)) hit++;
5398
+ }
5399
+ return opaque ? hit / opaque : 1;
5284
5400
  }
5285
- const round = (n) => Math.round(n * 100) / 100;
5286
- function centerline(rgba, w, h, o) {
5287
- const { labels, drawn } = labelBinary(rgba, w, h, o.threshold);
5288
- joinDiagonals(labels, w, h, rgba, drawn);
5289
- mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
5290
- const ink = new Uint8Array(w * h);
5291
- for (let i = 0; i < ink.length; i++) ink[i] = labels[i] === 0 ? 1 : 0;
5292
- const skel = o.closeGaps ? thin(ink, w, h) : void 0;
5293
- const joined = !!skel && closeGaps(ink, w, h, {
5294
- scale: o.scale,
5295
- skel
5296
- }) > 0;
5297
- if (joined) {
5298
- for (let i = 0; i < ink.length; i++) if (ink[i]) labels[i] = 0;
5299
- mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
5300
- for (let i = 0; i < ink.length; i++) ink[i] = labels[i] === 0 ? 1 : 0;
5401
+ /**
5402
+ * How wide a painted outline is looked for, by how many times the image was
5403
+ * enlarged: 2 px at its own size (lines up to about 4 px wide), 3 px at 2×.
5404
+ */
5405
+ const outlineRadius = (scale) => Math.min(4, Math.max(2, Math.round(1.5 * scale)));
5406
+ /** The trace for `image` with `options`: a preset's recipe, with any option given in place of its default. */
5407
+ function tracePreset(image, options = {}) {
5408
+ const name = options.preset ?? "logo";
5409
+ const p = Object.hasOwn(presets, name) ? presets[name] : void 0;
5410
+ if (!p) throw new Error(`Unknown preset "${String(name)}". Use one of: ${Object.keys(presets).join(", ")}.`);
5411
+ const { width, height } = image;
5412
+ if (!(width > 0 && height > 0) || image.data.length < width * height * 4) throw new Error(`The image needs ${width} × ${height} × 4 bytes of RGBA, and has ${image.data.length}.`);
5413
+ const o = {
5414
+ ...p,
5415
+ ...defined(options)
5416
+ };
5417
+ const fit = {
5418
+ speckle: o.speckle ?? 0,
5419
+ tolerance: o.tolerance ?? 1,
5420
+ cornerAngle: o.cornerAngle ?? 45,
5421
+ ...o.smoothing !== void 0 ? { smoothing: o.smoothing } : {}
5422
+ };
5423
+ const scale = o.scale ?? 1;
5424
+ let px = image.data;
5425
+ if (p.kind !== "colour") {
5426
+ if (o.invert) {
5427
+ const flipped = Uint8ClampedArray.from(px);
5428
+ for (let i = 0; i < flipped.length; i += 4) for (let k = 0; k < 3; k++) flipped[i + k] = 255 - flipped[i + k];
5429
+ px = flipped;
5430
+ }
5431
+ const threshold = o.threshold === void 0 ? "auto" : o.threshold;
5432
+ if (p.kind === "centerline") return centerline(px, width, height, {
5433
+ ...fit,
5434
+ threshold,
5435
+ closeGaps: !!o.closeGaps,
5436
+ scale,
5437
+ ...o.strokeWidth ? { strokeWidth: o.strokeWidth } : {}
5438
+ });
5439
+ return traceRaw(px, width, height, {
5440
+ ...fit,
5441
+ shapes: !!o.shapes,
5442
+ mode: "binary",
5443
+ threshold,
5444
+ closeGaps: !!o.closeGaps,
5445
+ scale
5446
+ });
5301
5447
  }
5302
- const { subs, measured } = skeletonStrokes(ink, w, h, o, joined ? void 0 : skel);
5303
- const width = o.strokeWidth && o.strokeWidth > 0 ? o.strokeWidth : measured;
5304
- return {
5305
- width: w,
5306
- height: h,
5307
- paths: subs.length ? [{
5308
- d: serializePath(subs),
5309
- stroke: o.color ?? "#000000",
5310
- strokeWidth: round(width)
5311
- }] : [],
5312
- measuredWidth: round(measured)
5448
+ if (o.grayscale && name !== "pixel" && !o.palette?.length) px = toGray(px);
5449
+ const lines = o.keepOutlines ? new Uint8Array(width * height) : void 0;
5450
+ if (lines) px = boostLines(px, width, height, outlineRadius(scale), lines);
5451
+ if (o.smoothShading) px = smoothShading(px, width, height, lines);
5452
+ const picker = PICKER[name];
5453
+ const colors = o.colors ?? 8;
5454
+ const own = o.palette?.length ? o.palette : null;
5455
+ let palette = own ?? (picker === "exact" ? exactPalette(px, colors) : picker === "quantize" ? quantizePalette(px, colors) : peakPalette(px, colors, { width }));
5456
+ if (!own && picker === "exact" && coverage(px, palette) < EXACT_COVERAGE) palette = quantizePalette(px, colors);
5457
+ const pixels = name === "pixel";
5458
+ const merge = o.merge && Object.keys(o.merge).length ? { merge: o.merge } : {};
5459
+ const gradients = options.gradients ?? (!!p.gradients && !own && !!o.layers);
5460
+ const raw = {
5461
+ ...fit,
5462
+ mode: "palette",
5463
+ palette,
5464
+ ...merge,
5465
+ shapes: !!o.shapes && !pixels,
5466
+ pixels,
5467
+ stacked: !pixels && !!o.layers,
5468
+ photo: picker === "quantize",
5469
+ strokes: !!o.strokes && !pixels && picker !== "quantize",
5470
+ gradients: gradients && !pixels,
5471
+ closeGaps: !!o.closeGaps,
5472
+ scale,
5473
+ ...lines ? { lines } : {}
5313
5474
  };
5475
+ return traceRaw(px, width, height, raw);
5476
+ }
5477
+ /** sRGB (0–255) of the grey whose OKLab lightness is `l`: for a grey, L is the cube root of its linear light. */
5478
+ const greyOf = (l) => {
5479
+ const y = Math.min(1, Math.max(0, l)) ** 3;
5480
+ return Math.round(255 * (y <= .0031308 ? 12.92 * y : 1.055 * y ** (1 / 2.4) - .055));
5481
+ };
5482
+ /** A copy of the image in greys of each pixel's own OKLab lightness; alpha kept. */
5483
+ function toGray(px) {
5484
+ const out = new Uint8ClampedArray(px.length);
5485
+ const seen = /* @__PURE__ */ new Map();
5486
+ for (let i = 0; i < px.length; i += 4) {
5487
+ const key = px[i] << 16 | px[i + 1] << 8 | px[i + 2];
5488
+ let v = seen.get(key);
5489
+ if (v === void 0) seen.set(key, v = greyOf(oklab([
5490
+ px[i],
5491
+ px[i + 1],
5492
+ px[i + 2]
5493
+ ])[0]));
5494
+ out[i] = out[i + 1] = out[i + 2] = v;
5495
+ out[i + 3] = px[i + 3];
5496
+ }
5497
+ return out;
5498
+ }
5499
+ /** The options given, without the ones explicitly undefined (which would hide a preset's default). */
5500
+ function defined(o) {
5501
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
5502
+ }
5503
+ function trace(a, b, c, d) {
5504
+ if (typeof b === "number") return traceRaw(a, b, c, d);
5505
+ return tracePreset(a, b);
5506
+ }
5507
+ function traceInlay(a, b, c, d) {
5508
+ return toSvg(typeof b === "number" ? traceRaw(a, b, c, d) : tracePreset(a, b));
5314
5509
  }
5315
- //#endregion
5316
- //#region src/symmetry.ts
5510
+ // src/symmetry.ts
5317
5511
  /**
5318
5512
  * Score every candidate symmetry: the best vertical and horizontal mirror axes
5319
5513
  * and the best centre for each rotational order, highest score first. A clean
@@ -5495,5 +5689,4 @@ function detectSymmetry(rgba, w, h, options = {}) {
5495
5689
  });
5496
5690
  return out.sort((a, b) => b.score - a.score);
5497
5691
  }
5498
- //#endregion
5499
- export { boostLines, centerline, centerlineToSvg, colorAt, detectSymmetry, exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, quantizePalette, serializePath, smoothShading, staircase, toSvg, trace, traceCenterline, traceInlay };
5692
+ export { boostLines, centerline, centerlineToSvg, detectSymmetry, exactPalette, fitChain, isFlat, mapPoints, oklab, parsePath, peakPalette, pointAt, presets, quantizePalette, serializePath, smoothShading, toSvg, trace, traceCenterline, traceInlay };