@pooder/kit 4.0.0 → 4.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.
Files changed (44) hide show
  1. package/.test-dist/src/CanvasService.js +83 -0
  2. package/.test-dist/src/ViewportSystem.js +75 -0
  3. package/.test-dist/src/background.js +203 -0
  4. package/.test-dist/src/constraints.js +153 -0
  5. package/.test-dist/src/coordinate.js +74 -0
  6. package/.test-dist/src/dieline.js +758 -0
  7. package/.test-dist/src/feature.js +687 -0
  8. package/.test-dist/src/featureComplete.js +31 -0
  9. package/.test-dist/src/featureDraft.js +31 -0
  10. package/.test-dist/src/film.js +167 -0
  11. package/.test-dist/src/geometry.js +292 -0
  12. package/.test-dist/src/image.js +421 -0
  13. package/.test-dist/src/index.js +31 -0
  14. package/.test-dist/src/mirror.js +104 -0
  15. package/.test-dist/src/ruler.js +383 -0
  16. package/.test-dist/src/tracer.js +448 -0
  17. package/.test-dist/src/units.js +30 -0
  18. package/.test-dist/src/white-ink.js +310 -0
  19. package/.test-dist/tests/run.js +60 -0
  20. package/CHANGELOG.md +12 -0
  21. package/dist/index.d.mts +54 -5
  22. package/dist/index.d.ts +54 -5
  23. package/dist/index.js +584 -190
  24. package/dist/index.mjs +581 -189
  25. package/package.json +3 -2
  26. package/src/CanvasService.ts +7 -0
  27. package/src/ViewportSystem.ts +92 -0
  28. package/src/background.ts +230 -230
  29. package/src/constraints.ts +207 -0
  30. package/src/coordinate.ts +106 -106
  31. package/src/dieline.ts +194 -75
  32. package/src/feature.ts +239 -147
  33. package/src/featureComplete.ts +45 -0
  34. package/src/film.ts +194 -194
  35. package/src/geometry.ts +4 -0
  36. package/src/image.ts +512 -512
  37. package/src/index.ts +1 -0
  38. package/src/mirror.ts +128 -128
  39. package/src/ruler.ts +508 -500
  40. package/src/tracer.ts +570 -570
  41. package/src/units.ts +27 -0
  42. package/src/white-ink.ts +373 -373
  43. package/tests/run.ts +81 -0
  44. package/tsconfig.test.json +15 -0
package/src/tracer.ts CHANGED
@@ -1,570 +1,570 @@
1
- /**
2
- * Image Tracer Utility
3
- * Converts raster images (URL/Base64) to SVG Path Data using Marching Squares algorithm.
4
- */
5
-
6
- import paper from "paper";
7
-
8
- interface Point {
9
- x: number;
10
- y: number;
11
- }
12
-
13
- export class ImageTracer {
14
- /**
15
- * Main entry point: Traces an image URL to an SVG path string.
16
- * @param imageUrl The URL or Base64 string of the image.
17
- * @param options Configuration options.
18
- */
19
- public static async trace(
20
- imageUrl: string,
21
- options: {
22
- threshold?: number; // 0-255, default 10
23
- simplifyTolerance?: number; // default 2.5
24
- scale?: number; // Scale factor for the processing canvas, default 1.0
25
- scaleToWidth?: number;
26
- scaleToHeight?: number;
27
- morphologyRadius?: number; // Default 10.
28
- expand?: number; // Expansion radius in pixels. Default 0.
29
- smoothing?: boolean; // Use Paper.js smoothing (curve fitting). Default true.
30
- } = {},
31
- ): Promise<string> {
32
- const img = await this.loadImage(imageUrl);
33
- const width = img.width;
34
- const height = img.height;
35
-
36
- // 1. Draw to canvas and get pixel data
37
- const canvas = document.createElement("canvas");
38
- canvas.width = width;
39
- canvas.height = height;
40
- const ctx = canvas.getContext("2d");
41
- if (!ctx) throw new Error("Could not get 2D context");
42
-
43
- ctx.drawImage(img, 0, 0);
44
- const imageData = ctx.getImageData(0, 0, width, height);
45
-
46
- // 2. Morphology processing
47
- const threshold = options.threshold ?? 10;
48
- // Adaptive radius: 3% of the image's largest dimension, at least 5px
49
- const adaptiveRadius = Math.max(
50
- 5,
51
- Math.floor(Math.max(width, height) * 0.02),
52
- );
53
- const radius = options.morphologyRadius ?? adaptiveRadius;
54
- const expand = options.expand ?? 0;
55
-
56
- // Add padding to the processing canvas to avoid edge clipping during dilation
57
- // Padding should be at least the radius + expansion size
58
- const padding = radius + expand + 2;
59
- const paddedWidth = width + padding * 2;
60
- const paddedHeight = height + padding * 2;
61
-
62
- let mask = this.createMask(imageData, threshold, padding, paddedWidth, paddedHeight);
63
-
64
- if (radius > 0) {
65
- // 1. Primary Closing (Large Radius, Circular) to merge distant parts
66
- mask = this.circularMorphology(mask, paddedWidth, paddedHeight, radius, "closing");
67
-
68
- // 2. Fill internal holes to ensure we only get the overall outer contour
69
- mask = this.fillHoles(mask, paddedWidth, paddedHeight);
70
-
71
- // 3. Secondary Smoothing (Small Radius, Circular) to round off sharp corners
72
- const smoothRadius = Math.max(2, Math.floor(radius * 0.3));
73
- mask = this.circularMorphology(mask, paddedWidth, paddedHeight, smoothRadius, "closing");
74
- } else {
75
- // Even if no smoothing radius, we usually want to fill holes for a dieline
76
- mask = this.fillHoles(mask, paddedWidth, paddedHeight);
77
- }
78
-
79
- // 4. Expand (Dilation) - Apply safety distance
80
- if (expand > 0) {
81
- mask = this.circularMorphology(mask, paddedWidth, paddedHeight, expand, "dilate");
82
- }
83
-
84
- // 5. Trace contours from the unified mask
85
- const allContourPoints = this.traceAllContours(mask, paddedWidth, paddedHeight);
86
-
87
- if (allContourPoints.length === 0) {
88
- // Fallback: Return a rectangular outline matching dimensions
89
- const w = options.scaleToWidth ?? width;
90
- const h = options.scaleToHeight ?? height;
91
- return `M 0 0 L ${w} 0 L ${w} ${h} L 0 ${h} Z`;
92
- }
93
-
94
- // 6. Select the largest contour to ensure a single, consistent overall shape
95
- const primaryContour = allContourPoints.sort(
96
- (a, b) => b.length - a.length,
97
- )[0];
98
-
99
- // 7. Restore coordinates (remove padding)
100
- const unpaddedPoints = primaryContour.map(p => ({
101
- x: p.x - padding,
102
- y: p.y - padding
103
- }));
104
-
105
- // 8. Find bounds for the selected contour
106
- let minX = Infinity,
107
- minY = Infinity,
108
- maxX = -Infinity,
109
- maxY = -Infinity;
110
-
111
- for (const p of unpaddedPoints) {
112
- if (p.x < minX) minX = p.x;
113
- if (p.y < minY) minY = p.y;
114
- if (p.x > maxX) maxX = p.x;
115
- if (p.y > maxY) maxY = p.y;
116
- }
117
-
118
- const globalBounds = {
119
- minX,
120
- minY,
121
- width: maxX - minX,
122
- height: maxY - minY,
123
- };
124
-
125
- // 9. Post-processing (Scale)
126
- let finalPoints = unpaddedPoints;
127
- if (options.scaleToWidth && options.scaleToHeight) {
128
- finalPoints = this.scalePoints(
129
- unpaddedPoints,
130
- options.scaleToWidth,
131
- options.scaleToHeight,
132
- globalBounds,
133
- );
134
- }
135
-
136
- // 10. Simplify and Generate SVG
137
- const useSmoothing = options.smoothing !== false; // Default true
138
-
139
- if (useSmoothing) {
140
- return this.pointsToSVGPaper(finalPoints, options.simplifyTolerance ?? 2.5);
141
- } else {
142
- const simplifiedPoints = this.douglasPeucker(
143
- finalPoints,
144
- options.simplifyTolerance ?? 2.0,
145
- );
146
- return this.pointsToSVG(simplifiedPoints);
147
- }
148
- }
149
-
150
- private static createMask(
151
- imageData: ImageData,
152
- threshold: number,
153
- padding: number,
154
- paddedWidth: number,
155
- paddedHeight: number,
156
- ): Uint8Array {
157
- const { width, height, data } = imageData;
158
- const mask = new Uint8Array(paddedWidth * paddedHeight);
159
-
160
- // 1. Detect if the image has transparency (any pixel with alpha < 255)
161
- let hasTransparency = false;
162
- for (let i = 3; i < data.length; i += 4) {
163
- if (data[i] < 255) {
164
- hasTransparency = true;
165
- break;
166
- }
167
- }
168
-
169
- // 2. Binarize based on alpha or luminance
170
- for (let y = 0; y < height; y++) {
171
- for (let x = 0; x < width; x++) {
172
- const srcIdx = (y * width + x) * 4;
173
- const r = data[srcIdx];
174
- const g = data[srcIdx + 1];
175
- const b = data[srcIdx + 2];
176
- const a = data[srcIdx + 3];
177
-
178
- const destIdx = (y + padding) * paddedWidth + (x + padding);
179
-
180
- if (hasTransparency) {
181
- if (a > threshold) {
182
- mask[destIdx] = 1;
183
- }
184
- } else {
185
- if (!(r > 240 && g > 240 && b > 240)) {
186
- mask[destIdx] = 1;
187
- }
188
- }
189
- }
190
- }
191
- return mask;
192
- }
193
-
194
- /**
195
- * Fast circular morphology using a distance-transform inspired separable approach.
196
- * O(N * R) complexity, where R is the radius.
197
- */
198
- private static circularMorphology(
199
- mask: Uint8Array,
200
- width: number,
201
- height: number,
202
- radius: number,
203
- op: "dilate" | "erode" | "closing" | "opening",
204
- ): Uint8Array {
205
- const dilate = (m: Uint8Array, r: number) => {
206
- const horizontalDist = new Int32Array(width * height);
207
- // Horizontal pass: dist to nearest solid pixel in row
208
- for (let y = 0; y < height; y++) {
209
- let lastSolid = -r * 2;
210
- for (let x = 0; x < width; x++) {
211
- if (m[y * width + x]) lastSolid = x;
212
- horizontalDist[y * width + x] = x - lastSolid;
213
- }
214
- lastSolid = width + r * 2;
215
- for (let x = width - 1; x >= 0; x--) {
216
- if (m[y * width + x]) lastSolid = x;
217
- horizontalDist[y * width + x] = Math.min(
218
- horizontalDist[y * width + x],
219
- lastSolid - x,
220
- );
221
- }
222
- }
223
-
224
- const result = new Uint8Array(width * height);
225
- const r2 = r * r;
226
- // Vertical pass: check Euclidean distance using precomputed horizontal distances
227
- for (let x = 0; x < width; x++) {
228
- for (let y = 0; y < height; y++) {
229
- let found = false;
230
- const minY = Math.max(0, y - r);
231
- const maxY = Math.min(height - 1, y + r);
232
- for (let dy = minY; dy <= maxY; dy++) {
233
- const dY = dy - y;
234
- const hDist = horizontalDist[dy * width + x];
235
- if (hDist * hDist + dY * dY <= r2) {
236
- found = true;
237
- break;
238
- }
239
- }
240
- if (found) result[y * width + x] = 1;
241
- }
242
- }
243
- return result;
244
- };
245
-
246
- const erode = (m: Uint8Array, r: number) => {
247
- // Erosion is dilation of the inverted mask
248
- const inverted = new Uint8Array(m.length);
249
- for (let i = 0; i < m.length; i++) inverted[i] = m[i] ? 0 : 1;
250
- const dilatedInverted = dilate(inverted, r);
251
- const result = new Uint8Array(m.length);
252
- for (let i = 0; i < m.length; i++) result[i] = dilatedInverted[i] ? 0 : 1;
253
- return result;
254
- };
255
-
256
- switch (op) {
257
- case "dilate":
258
- return dilate(mask, radius);
259
- case "erode":
260
- return erode(mask, radius);
261
- case "closing":
262
- return erode(dilate(mask, radius), radius);
263
- case "opening":
264
- return dilate(erode(mask, radius), radius);
265
- default:
266
- return mask;
267
- }
268
- }
269
-
270
- /**
271
- * Fills internal holes in the binary mask using flood fill from edges.
272
- */
273
- private static fillHoles(
274
- mask: Uint8Array,
275
- width: number,
276
- height: number,
277
- ): Uint8Array {
278
- const background = new Uint8Array(width * height);
279
- const queue: [number, number][] = [];
280
-
281
- // Add all edge pixels that are 0 to the queue
282
- for (let x = 0; x < width; x++) {
283
- if (mask[x] === 0) {
284
- background[x] = 1;
285
- queue.push([x, 0]);
286
- }
287
- const lastRow = (height - 1) * width + x;
288
- if (mask[lastRow] === 0) {
289
- background[lastRow] = 1;
290
- queue.push([x, height - 1]);
291
- }
292
- }
293
- for (let y = 1; y < height - 1; y++) {
294
- if (mask[y * width] === 0) {
295
- background[y * width] = 1;
296
- queue.push([0, y]);
297
- }
298
- if (mask[y * width + width - 1] === 0) {
299
- background[y * width + width - 1] = 1;
300
- queue.push([width - 1, y]);
301
- }
302
- }
303
-
304
- // Flood fill from the edges to find all background pixels
305
- const dirs = [
306
- [0, 1],
307
- [0, -1],
308
- [1, 0],
309
- [-1, 0],
310
- ];
311
- let head = 0;
312
- while (head < queue.length) {
313
- const [cx, cy] = queue[head++];
314
- for (const [dx, dy] of dirs) {
315
- const nx = cx + dx;
316
- const ny = cy + dy;
317
- if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
318
- const nidx = ny * width + nx;
319
- if (mask[nidx] === 0 && background[nidx] === 0) {
320
- background[nidx] = 1;
321
- queue.push([nx, ny]);
322
- }
323
- }
324
- }
325
- }
326
-
327
- // Any pixel that is NOT reachable from the background is part of the "filled" mask
328
- const filledMask = new Uint8Array(width * height);
329
- for (let i = 0; i < width * height; i++) {
330
- filledMask[i] = background[i] === 0 ? 1 : 0;
331
- }
332
-
333
- return filledMask;
334
- }
335
-
336
- /**
337
- * Traces all contours in the mask with optimized start-point detection
338
- */
339
- private static traceAllContours(
340
- mask: Uint8Array,
341
- width: number,
342
- height: number,
343
- ): Point[][] {
344
- const visited = new Uint8Array(width * height);
345
- const allContours: Point[][] = [];
346
-
347
- for (let y = 0; y < height; y++) {
348
- for (let x = 0; x < width; x++) {
349
- const idx = y * width + x;
350
- if (mask[idx] && !visited[idx]) {
351
- // Only start a new trace if it's a potential outer boundary (left edge)
352
- const isLeftEdge = x === 0 || mask[idx - 1] === 0;
353
- if (isLeftEdge) {
354
- const contour = this.marchingSquares(
355
- mask,
356
- visited,
357
- x,
358
- y,
359
- width,
360
- height,
361
- );
362
- if (contour.length > 2) {
363
- allContours.push(contour);
364
- }
365
- }
366
- }
367
- }
368
- }
369
- return allContours;
370
- }
371
-
372
- private static loadImage(url: string): Promise<HTMLImageElement> {
373
- return new Promise((resolve, reject) => {
374
- const img = new Image();
375
- img.crossOrigin = "Anonymous";
376
- img.onload = () => resolve(img);
377
- img.onerror = (e) => reject(e);
378
- img.src = url;
379
- });
380
- }
381
-
382
- /**
383
- * Moore-Neighbor Tracing Algorithm
384
- * More robust for irregular shapes than simple Marching Squares walker.
385
- */
386
- private static marchingSquares(
387
- mask: Uint8Array,
388
- visited: Uint8Array,
389
- startX: number,
390
- startY: number,
391
- width: number,
392
- height: number,
393
- ): Point[] {
394
- const isSolid = (x: number, y: number): boolean => {
395
- if (x < 0 || x >= width || y < 0 || y >= height) return false;
396
- return mask[y * width + x] === 1;
397
- };
398
-
399
- const points: Point[] = [];
400
-
401
- // Moore-Neighbor Tracing
402
- // We enter from the Left (since we scan Left->Right), so "backtrack" is Left.
403
- // B = (startX - 1, startY)
404
- // P = (startX, startY)
405
-
406
- let cx = startX;
407
- let cy = startY;
408
-
409
- // Start backtrack direction: Left (since we found it scanning from left)
410
- // Directions: 0=Up, 1=UpRight, 2=Right, 3=DownRight, 4=Down, 5=DownLeft, 6=Left, 7=UpLeft
411
- // Offsets for 8 neighbors starting from Up (0,-1) clockwise
412
- const neighbors = [
413
- { x: 0, y: -1 },
414
- { x: 1, y: -1 },
415
- { x: 1, y: 0 },
416
- { x: 1, y: 1 },
417
- { x: 0, y: 1 },
418
- { x: -1, y: 1 },
419
- { x: -1, y: 0 },
420
- { x: -1, y: -1 },
421
- ];
422
-
423
- // Backtrack is Left -> Index 6.
424
- let backtrack = 6;
425
-
426
- const maxSteps = width * height * 3;
427
- let steps = 0;
428
-
429
- do {
430
- points.push({ x: cx, y: cy });
431
- visited[cy * width + cx] = 1; // Mark as visited to avoid re-starting here
432
-
433
- // Search for next solid neighbor in clockwise order, starting from backtrack
434
- let found = false;
435
-
436
- for (let i = 0; i < 8; i++) {
437
- const idx = (backtrack + 1 + i) % 8;
438
- const nx = cx + neighbors[idx].x;
439
- const ny = cy + neighbors[idx].y;
440
-
441
- if (isSolid(nx, ny)) {
442
- cx = nx;
443
- cy = ny;
444
- backtrack = (idx + 4 + 1) % 8;
445
- found = true;
446
- break;
447
- }
448
- }
449
-
450
- if (!found) break;
451
-
452
- steps++;
453
- } while ((cx !== startX || cy !== startY) && steps < maxSteps);
454
-
455
- return points;
456
- }
457
-
458
- /**
459
- * Douglas-Peucker Line Simplification
460
- */
461
- private static douglasPeucker(points: Point[], tolerance: number): Point[] {
462
- if (points.length <= 2) return points;
463
-
464
- const sqTolerance = tolerance * tolerance;
465
- let maxSqDist = 0;
466
- let index = 0;
467
-
468
- const first = points[0];
469
- const last = points[points.length - 1];
470
-
471
- for (let i = 1; i < points.length - 1; i++) {
472
- const sqDist = this.getSqSegDist(points[i], first, last);
473
- if (sqDist > maxSqDist) {
474
- index = i;
475
- maxSqDist = sqDist;
476
- }
477
- }
478
-
479
- if (maxSqDist > sqTolerance) {
480
- // Check if closed loop?
481
- // If closed loop, we shouldn't simplify start/end connection too much?
482
- // Douglas-Peucker works on segments.
483
- const left = this.douglasPeucker(points.slice(0, index + 1), tolerance);
484
- const right = this.douglasPeucker(points.slice(index), tolerance);
485
- return left.slice(0, left.length - 1).concat(right);
486
- } else {
487
- return [first, last];
488
- }
489
- }
490
-
491
- private static getSqSegDist(p: Point, p1: Point, p2: Point): number {
492
- let x = p1.x;
493
- let y = p1.y;
494
- let dx = p2.x - x;
495
- let dy = p2.y - y;
496
-
497
- if (dx !== 0 || dy !== 0) {
498
- const t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);
499
- if (t > 1) {
500
- x = p2.x;
501
- y = p2.y;
502
- } else if (t > 0) {
503
- x += dx * t;
504
- y += dy * t;
505
- }
506
- }
507
-
508
- dx = p.x - x;
509
- dy = p.y - y;
510
-
511
- return dx * dx + dy * dy;
512
- }
513
-
514
- private static scalePoints(
515
- points: Point[],
516
- targetWidth: number,
517
- targetHeight: number,
518
- bounds: { minX: number; minY: number; width: number; height: number },
519
- ): Point[] {
520
- if (points.length === 0) return points;
521
-
522
- if (bounds.width === 0 || bounds.height === 0) return points;
523
-
524
- const scaleX = targetWidth / bounds.width;
525
- const scaleY = targetHeight / bounds.height;
526
-
527
- return points.map((p) => ({
528
- x: (p.x - bounds.minX) * scaleX,
529
- y: (p.y - bounds.minY) * scaleY,
530
- }));
531
- }
532
-
533
- private static pointsToSVG(points: Point[]): string {
534
- if (points.length === 0) return "";
535
- const head = points[0];
536
- const tail = points.slice(1);
537
-
538
- return (
539
- `M ${head.x} ${head.y} ` +
540
- tail.map((p) => `L ${p.x} ${p.y}`).join(" ") +
541
- " Z"
542
- );
543
- }
544
-
545
- private static ensurePaper() {
546
- if (!paper.project) {
547
- paper.setup(new paper.Size(100, 100));
548
- }
549
- }
550
-
551
- private static pointsToSVGPaper(points: Point[], tolerance: number): string {
552
- if (points.length < 3) return this.pointsToSVG(points);
553
-
554
- this.ensurePaper();
555
-
556
- // Create Path
557
- const path = new paper.Path({
558
- segments: points.map(p => [p.x, p.y]),
559
- closed: true
560
- });
561
-
562
- // Simplify
563
- path.simplify(tolerance);
564
-
565
- const data = path.pathData;
566
- path.remove();
567
-
568
- return data;
569
- }
570
- }
1
+ /**
2
+ * Image Tracer Utility
3
+ * Converts raster images (URL/Base64) to SVG Path Data using Marching Squares algorithm.
4
+ */
5
+
6
+ import paper from "paper";
7
+
8
+ interface Point {
9
+ x: number;
10
+ y: number;
11
+ }
12
+
13
+ export class ImageTracer {
14
+ /**
15
+ * Main entry point: Traces an image URL to an SVG path string.
16
+ * @param imageUrl The URL or Base64 string of the image.
17
+ * @param options Configuration options.
18
+ */
19
+ public static async trace(
20
+ imageUrl: string,
21
+ options: {
22
+ threshold?: number; // 0-255, default 10
23
+ simplifyTolerance?: number; // default 2.5
24
+ scale?: number; // Scale factor for the processing canvas, default 1.0
25
+ scaleToWidth?: number;
26
+ scaleToHeight?: number;
27
+ morphologyRadius?: number; // Default 10.
28
+ expand?: number; // Expansion radius in pixels. Default 0.
29
+ smoothing?: boolean; // Use Paper.js smoothing (curve fitting). Default true.
30
+ } = {},
31
+ ): Promise<string> {
32
+ const img = await this.loadImage(imageUrl);
33
+ const width = img.width;
34
+ const height = img.height;
35
+
36
+ // 1. Draw to canvas and get pixel data
37
+ const canvas = document.createElement("canvas");
38
+ canvas.width = width;
39
+ canvas.height = height;
40
+ const ctx = canvas.getContext("2d");
41
+ if (!ctx) throw new Error("Could not get 2D context");
42
+
43
+ ctx.drawImage(img, 0, 0);
44
+ const imageData = ctx.getImageData(0, 0, width, height);
45
+
46
+ // 2. Morphology processing
47
+ const threshold = options.threshold ?? 10;
48
+ // Adaptive radius: 3% of the image's largest dimension, at least 5px
49
+ const adaptiveRadius = Math.max(
50
+ 5,
51
+ Math.floor(Math.max(width, height) * 0.02),
52
+ );
53
+ const radius = options.morphologyRadius ?? adaptiveRadius;
54
+ const expand = options.expand ?? 0;
55
+
56
+ // Add padding to the processing canvas to avoid edge clipping during dilation
57
+ // Padding should be at least the radius + expansion size
58
+ const padding = radius + expand + 2;
59
+ const paddedWidth = width + padding * 2;
60
+ const paddedHeight = height + padding * 2;
61
+
62
+ let mask = this.createMask(imageData, threshold, padding, paddedWidth, paddedHeight);
63
+
64
+ if (radius > 0) {
65
+ // 1. Primary Closing (Large Radius, Circular) to merge distant parts
66
+ mask = this.circularMorphology(mask, paddedWidth, paddedHeight, radius, "closing");
67
+
68
+ // 2. Fill internal holes to ensure we only get the overall outer contour
69
+ mask = this.fillHoles(mask, paddedWidth, paddedHeight);
70
+
71
+ // 3. Secondary Smoothing (Small Radius, Circular) to round off sharp corners
72
+ const smoothRadius = Math.max(2, Math.floor(radius * 0.3));
73
+ mask = this.circularMorphology(mask, paddedWidth, paddedHeight, smoothRadius, "closing");
74
+ } else {
75
+ // Even if no smoothing radius, we usually want to fill holes for a dieline
76
+ mask = this.fillHoles(mask, paddedWidth, paddedHeight);
77
+ }
78
+
79
+ // 4. Expand (Dilation) - Apply safety distance
80
+ if (expand > 0) {
81
+ mask = this.circularMorphology(mask, paddedWidth, paddedHeight, expand, "dilate");
82
+ }
83
+
84
+ // 5. Trace contours from the unified mask
85
+ const allContourPoints = this.traceAllContours(mask, paddedWidth, paddedHeight);
86
+
87
+ if (allContourPoints.length === 0) {
88
+ // Fallback: Return a rectangular outline matching dimensions
89
+ const w = options.scaleToWidth ?? width;
90
+ const h = options.scaleToHeight ?? height;
91
+ return `M 0 0 L ${w} 0 L ${w} ${h} L 0 ${h} Z`;
92
+ }
93
+
94
+ // 6. Select the largest contour to ensure a single, consistent overall shape
95
+ const primaryContour = allContourPoints.sort(
96
+ (a, b) => b.length - a.length,
97
+ )[0];
98
+
99
+ // 7. Restore coordinates (remove padding)
100
+ const unpaddedPoints = primaryContour.map(p => ({
101
+ x: p.x - padding,
102
+ y: p.y - padding
103
+ }));
104
+
105
+ // 8. Find bounds for the selected contour
106
+ let minX = Infinity,
107
+ minY = Infinity,
108
+ maxX = -Infinity,
109
+ maxY = -Infinity;
110
+
111
+ for (const p of unpaddedPoints) {
112
+ if (p.x < minX) minX = p.x;
113
+ if (p.y < minY) minY = p.y;
114
+ if (p.x > maxX) maxX = p.x;
115
+ if (p.y > maxY) maxY = p.y;
116
+ }
117
+
118
+ const globalBounds = {
119
+ minX,
120
+ minY,
121
+ width: maxX - minX,
122
+ height: maxY - minY,
123
+ };
124
+
125
+ // 9. Post-processing (Scale)
126
+ let finalPoints = unpaddedPoints;
127
+ if (options.scaleToWidth && options.scaleToHeight) {
128
+ finalPoints = this.scalePoints(
129
+ unpaddedPoints,
130
+ options.scaleToWidth,
131
+ options.scaleToHeight,
132
+ globalBounds,
133
+ );
134
+ }
135
+
136
+ // 10. Simplify and Generate SVG
137
+ const useSmoothing = options.smoothing !== false; // Default true
138
+
139
+ if (useSmoothing) {
140
+ return this.pointsToSVGPaper(finalPoints, options.simplifyTolerance ?? 2.5);
141
+ } else {
142
+ const simplifiedPoints = this.douglasPeucker(
143
+ finalPoints,
144
+ options.simplifyTolerance ?? 2.0,
145
+ );
146
+ return this.pointsToSVG(simplifiedPoints);
147
+ }
148
+ }
149
+
150
+ private static createMask(
151
+ imageData: ImageData,
152
+ threshold: number,
153
+ padding: number,
154
+ paddedWidth: number,
155
+ paddedHeight: number,
156
+ ): Uint8Array {
157
+ const { width, height, data } = imageData;
158
+ const mask = new Uint8Array(paddedWidth * paddedHeight);
159
+
160
+ // 1. Detect if the image has transparency (any pixel with alpha < 255)
161
+ let hasTransparency = false;
162
+ for (let i = 3; i < data.length; i += 4) {
163
+ if (data[i] < 255) {
164
+ hasTransparency = true;
165
+ break;
166
+ }
167
+ }
168
+
169
+ // 2. Binarize based on alpha or luminance
170
+ for (let y = 0; y < height; y++) {
171
+ for (let x = 0; x < width; x++) {
172
+ const srcIdx = (y * width + x) * 4;
173
+ const r = data[srcIdx];
174
+ const g = data[srcIdx + 1];
175
+ const b = data[srcIdx + 2];
176
+ const a = data[srcIdx + 3];
177
+
178
+ const destIdx = (y + padding) * paddedWidth + (x + padding);
179
+
180
+ if (hasTransparency) {
181
+ if (a > threshold) {
182
+ mask[destIdx] = 1;
183
+ }
184
+ } else {
185
+ if (!(r > 240 && g > 240 && b > 240)) {
186
+ mask[destIdx] = 1;
187
+ }
188
+ }
189
+ }
190
+ }
191
+ return mask;
192
+ }
193
+
194
+ /**
195
+ * Fast circular morphology using a distance-transform inspired separable approach.
196
+ * O(N * R) complexity, where R is the radius.
197
+ */
198
+ private static circularMorphology(
199
+ mask: Uint8Array,
200
+ width: number,
201
+ height: number,
202
+ radius: number,
203
+ op: "dilate" | "erode" | "closing" | "opening",
204
+ ): Uint8Array {
205
+ const dilate = (m: Uint8Array, r: number) => {
206
+ const horizontalDist = new Int32Array(width * height);
207
+ // Horizontal pass: dist to nearest solid pixel in row
208
+ for (let y = 0; y < height; y++) {
209
+ let lastSolid = -r * 2;
210
+ for (let x = 0; x < width; x++) {
211
+ if (m[y * width + x]) lastSolid = x;
212
+ horizontalDist[y * width + x] = x - lastSolid;
213
+ }
214
+ lastSolid = width + r * 2;
215
+ for (let x = width - 1; x >= 0; x--) {
216
+ if (m[y * width + x]) lastSolid = x;
217
+ horizontalDist[y * width + x] = Math.min(
218
+ horizontalDist[y * width + x],
219
+ lastSolid - x,
220
+ );
221
+ }
222
+ }
223
+
224
+ const result = new Uint8Array(width * height);
225
+ const r2 = r * r;
226
+ // Vertical pass: check Euclidean distance using precomputed horizontal distances
227
+ for (let x = 0; x < width; x++) {
228
+ for (let y = 0; y < height; y++) {
229
+ let found = false;
230
+ const minY = Math.max(0, y - r);
231
+ const maxY = Math.min(height - 1, y + r);
232
+ for (let dy = minY; dy <= maxY; dy++) {
233
+ const dY = dy - y;
234
+ const hDist = horizontalDist[dy * width + x];
235
+ if (hDist * hDist + dY * dY <= r2) {
236
+ found = true;
237
+ break;
238
+ }
239
+ }
240
+ if (found) result[y * width + x] = 1;
241
+ }
242
+ }
243
+ return result;
244
+ };
245
+
246
+ const erode = (m: Uint8Array, r: number) => {
247
+ // Erosion is dilation of the inverted mask
248
+ const inverted = new Uint8Array(m.length);
249
+ for (let i = 0; i < m.length; i++) inverted[i] = m[i] ? 0 : 1;
250
+ const dilatedInverted = dilate(inverted, r);
251
+ const result = new Uint8Array(m.length);
252
+ for (let i = 0; i < m.length; i++) result[i] = dilatedInverted[i] ? 0 : 1;
253
+ return result;
254
+ };
255
+
256
+ switch (op) {
257
+ case "dilate":
258
+ return dilate(mask, radius);
259
+ case "erode":
260
+ return erode(mask, radius);
261
+ case "closing":
262
+ return erode(dilate(mask, radius), radius);
263
+ case "opening":
264
+ return dilate(erode(mask, radius), radius);
265
+ default:
266
+ return mask;
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Fills internal holes in the binary mask using flood fill from edges.
272
+ */
273
+ private static fillHoles(
274
+ mask: Uint8Array,
275
+ width: number,
276
+ height: number,
277
+ ): Uint8Array {
278
+ const background = new Uint8Array(width * height);
279
+ const queue: [number, number][] = [];
280
+
281
+ // Add all edge pixels that are 0 to the queue
282
+ for (let x = 0; x < width; x++) {
283
+ if (mask[x] === 0) {
284
+ background[x] = 1;
285
+ queue.push([x, 0]);
286
+ }
287
+ const lastRow = (height - 1) * width + x;
288
+ if (mask[lastRow] === 0) {
289
+ background[lastRow] = 1;
290
+ queue.push([x, height - 1]);
291
+ }
292
+ }
293
+ for (let y = 1; y < height - 1; y++) {
294
+ if (mask[y * width] === 0) {
295
+ background[y * width] = 1;
296
+ queue.push([0, y]);
297
+ }
298
+ if (mask[y * width + width - 1] === 0) {
299
+ background[y * width + width - 1] = 1;
300
+ queue.push([width - 1, y]);
301
+ }
302
+ }
303
+
304
+ // Flood fill from the edges to find all background pixels
305
+ const dirs = [
306
+ [0, 1],
307
+ [0, -1],
308
+ [1, 0],
309
+ [-1, 0],
310
+ ];
311
+ let head = 0;
312
+ while (head < queue.length) {
313
+ const [cx, cy] = queue[head++];
314
+ for (const [dx, dy] of dirs) {
315
+ const nx = cx + dx;
316
+ const ny = cy + dy;
317
+ if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
318
+ const nidx = ny * width + nx;
319
+ if (mask[nidx] === 0 && background[nidx] === 0) {
320
+ background[nidx] = 1;
321
+ queue.push([nx, ny]);
322
+ }
323
+ }
324
+ }
325
+ }
326
+
327
+ // Any pixel that is NOT reachable from the background is part of the "filled" mask
328
+ const filledMask = new Uint8Array(width * height);
329
+ for (let i = 0; i < width * height; i++) {
330
+ filledMask[i] = background[i] === 0 ? 1 : 0;
331
+ }
332
+
333
+ return filledMask;
334
+ }
335
+
336
+ /**
337
+ * Traces all contours in the mask with optimized start-point detection
338
+ */
339
+ private static traceAllContours(
340
+ mask: Uint8Array,
341
+ width: number,
342
+ height: number,
343
+ ): Point[][] {
344
+ const visited = new Uint8Array(width * height);
345
+ const allContours: Point[][] = [];
346
+
347
+ for (let y = 0; y < height; y++) {
348
+ for (let x = 0; x < width; x++) {
349
+ const idx = y * width + x;
350
+ if (mask[idx] && !visited[idx]) {
351
+ // Only start a new trace if it's a potential outer boundary (left edge)
352
+ const isLeftEdge = x === 0 || mask[idx - 1] === 0;
353
+ if (isLeftEdge) {
354
+ const contour = this.marchingSquares(
355
+ mask,
356
+ visited,
357
+ x,
358
+ y,
359
+ width,
360
+ height,
361
+ );
362
+ if (contour.length > 2) {
363
+ allContours.push(contour);
364
+ }
365
+ }
366
+ }
367
+ }
368
+ }
369
+ return allContours;
370
+ }
371
+
372
+ private static loadImage(url: string): Promise<HTMLImageElement> {
373
+ return new Promise((resolve, reject) => {
374
+ const img = new Image();
375
+ img.crossOrigin = "Anonymous";
376
+ img.onload = () => resolve(img);
377
+ img.onerror = (e) => reject(e);
378
+ img.src = url;
379
+ });
380
+ }
381
+
382
+ /**
383
+ * Moore-Neighbor Tracing Algorithm
384
+ * More robust for irregular shapes than simple Marching Squares walker.
385
+ */
386
+ private static marchingSquares(
387
+ mask: Uint8Array,
388
+ visited: Uint8Array,
389
+ startX: number,
390
+ startY: number,
391
+ width: number,
392
+ height: number,
393
+ ): Point[] {
394
+ const isSolid = (x: number, y: number): boolean => {
395
+ if (x < 0 || x >= width || y < 0 || y >= height) return false;
396
+ return mask[y * width + x] === 1;
397
+ };
398
+
399
+ const points: Point[] = [];
400
+
401
+ // Moore-Neighbor Tracing
402
+ // We enter from the Left (since we scan Left->Right), so "backtrack" is Left.
403
+ // B = (startX - 1, startY)
404
+ // P = (startX, startY)
405
+
406
+ let cx = startX;
407
+ let cy = startY;
408
+
409
+ // Start backtrack direction: Left (since we found it scanning from left)
410
+ // Directions: 0=Up, 1=UpRight, 2=Right, 3=DownRight, 4=Down, 5=DownLeft, 6=Left, 7=UpLeft
411
+ // Offsets for 8 neighbors starting from Up (0,-1) clockwise
412
+ const neighbors = [
413
+ { x: 0, y: -1 },
414
+ { x: 1, y: -1 },
415
+ { x: 1, y: 0 },
416
+ { x: 1, y: 1 },
417
+ { x: 0, y: 1 },
418
+ { x: -1, y: 1 },
419
+ { x: -1, y: 0 },
420
+ { x: -1, y: -1 },
421
+ ];
422
+
423
+ // Backtrack is Left -> Index 6.
424
+ let backtrack = 6;
425
+
426
+ const maxSteps = width * height * 3;
427
+ let steps = 0;
428
+
429
+ do {
430
+ points.push({ x: cx, y: cy });
431
+ visited[cy * width + cx] = 1; // Mark as visited to avoid re-starting here
432
+
433
+ // Search for next solid neighbor in clockwise order, starting from backtrack
434
+ let found = false;
435
+
436
+ for (let i = 0; i < 8; i++) {
437
+ const idx = (backtrack + 1 + i) % 8;
438
+ const nx = cx + neighbors[idx].x;
439
+ const ny = cy + neighbors[idx].y;
440
+
441
+ if (isSolid(nx, ny)) {
442
+ cx = nx;
443
+ cy = ny;
444
+ backtrack = (idx + 4 + 1) % 8;
445
+ found = true;
446
+ break;
447
+ }
448
+ }
449
+
450
+ if (!found) break;
451
+
452
+ steps++;
453
+ } while ((cx !== startX || cy !== startY) && steps < maxSteps);
454
+
455
+ return points;
456
+ }
457
+
458
+ /**
459
+ * Douglas-Peucker Line Simplification
460
+ */
461
+ private static douglasPeucker(points: Point[], tolerance: number): Point[] {
462
+ if (points.length <= 2) return points;
463
+
464
+ const sqTolerance = tolerance * tolerance;
465
+ let maxSqDist = 0;
466
+ let index = 0;
467
+
468
+ const first = points[0];
469
+ const last = points[points.length - 1];
470
+
471
+ for (let i = 1; i < points.length - 1; i++) {
472
+ const sqDist = this.getSqSegDist(points[i], first, last);
473
+ if (sqDist > maxSqDist) {
474
+ index = i;
475
+ maxSqDist = sqDist;
476
+ }
477
+ }
478
+
479
+ if (maxSqDist > sqTolerance) {
480
+ // Check if closed loop?
481
+ // If closed loop, we shouldn't simplify start/end connection too much?
482
+ // Douglas-Peucker works on segments.
483
+ const left = this.douglasPeucker(points.slice(0, index + 1), tolerance);
484
+ const right = this.douglasPeucker(points.slice(index), tolerance);
485
+ return left.slice(0, left.length - 1).concat(right);
486
+ } else {
487
+ return [first, last];
488
+ }
489
+ }
490
+
491
+ private static getSqSegDist(p: Point, p1: Point, p2: Point): number {
492
+ let x = p1.x;
493
+ let y = p1.y;
494
+ let dx = p2.x - x;
495
+ let dy = p2.y - y;
496
+
497
+ if (dx !== 0 || dy !== 0) {
498
+ const t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);
499
+ if (t > 1) {
500
+ x = p2.x;
501
+ y = p2.y;
502
+ } else if (t > 0) {
503
+ x += dx * t;
504
+ y += dy * t;
505
+ }
506
+ }
507
+
508
+ dx = p.x - x;
509
+ dy = p.y - y;
510
+
511
+ return dx * dx + dy * dy;
512
+ }
513
+
514
+ private static scalePoints(
515
+ points: Point[],
516
+ targetWidth: number,
517
+ targetHeight: number,
518
+ bounds: { minX: number; minY: number; width: number; height: number },
519
+ ): Point[] {
520
+ if (points.length === 0) return points;
521
+
522
+ if (bounds.width === 0 || bounds.height === 0) return points;
523
+
524
+ const scaleX = targetWidth / bounds.width;
525
+ const scaleY = targetHeight / bounds.height;
526
+
527
+ return points.map((p) => ({
528
+ x: (p.x - bounds.minX) * scaleX,
529
+ y: (p.y - bounds.minY) * scaleY,
530
+ }));
531
+ }
532
+
533
+ private static pointsToSVG(points: Point[]): string {
534
+ if (points.length === 0) return "";
535
+ const head = points[0];
536
+ const tail = points.slice(1);
537
+
538
+ return (
539
+ `M ${head.x} ${head.y} ` +
540
+ tail.map((p) => `L ${p.x} ${p.y}`).join(" ") +
541
+ " Z"
542
+ );
543
+ }
544
+
545
+ private static ensurePaper() {
546
+ if (!paper.project) {
547
+ paper.setup(new paper.Size(100, 100));
548
+ }
549
+ }
550
+
551
+ private static pointsToSVGPaper(points: Point[], tolerance: number): string {
552
+ if (points.length < 3) return this.pointsToSVG(points);
553
+
554
+ this.ensurePaper();
555
+
556
+ // Create Path
557
+ const path = new paper.Path({
558
+ segments: points.map(p => [p.x, p.y]),
559
+ closed: true
560
+ });
561
+
562
+ // Simplify
563
+ path.simplify(tolerance);
564
+
565
+ const data = path.pathData;
566
+ path.remove();
567
+
568
+ return data;
569
+ }
570
+ }