@pooder/kit 5.3.0 → 5.3.1

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 (60) hide show
  1. package/.test-dist/src/CanvasService.js +249 -249
  2. package/.test-dist/src/ViewportSystem.js +75 -75
  3. package/.test-dist/src/background.js +203 -203
  4. package/.test-dist/src/bridgeSelection.js +20 -20
  5. package/.test-dist/src/constraints.js +237 -237
  6. package/.test-dist/src/dieline.js +818 -818
  7. package/.test-dist/src/edgeScale.js +12 -12
  8. package/.test-dist/src/feature.js +826 -826
  9. package/.test-dist/src/featureComplete.js +32 -32
  10. package/.test-dist/src/film.js +167 -167
  11. package/.test-dist/src/geometry.js +506 -506
  12. package/.test-dist/src/image.js +1250 -1250
  13. package/.test-dist/src/maskOps.js +270 -270
  14. package/.test-dist/src/mirror.js +104 -104
  15. package/.test-dist/src/renderSpec.js +2 -2
  16. package/.test-dist/src/ruler.js +343 -343
  17. package/.test-dist/src/sceneLayout.js +99 -99
  18. package/.test-dist/src/sceneLayoutModel.js +196 -196
  19. package/.test-dist/src/sceneView.js +40 -40
  20. package/.test-dist/src/sceneVisibility.js +42 -42
  21. package/.test-dist/src/size.js +332 -332
  22. package/.test-dist/src/tracer.js +544 -544
  23. package/.test-dist/src/white-ink.js +829 -829
  24. package/.test-dist/src/wrappedOffsets.js +33 -33
  25. package/CHANGELOG.md +6 -0
  26. package/dist/index.d.mts +6 -0
  27. package/dist/index.d.ts +6 -0
  28. package/dist/index.js +108 -20
  29. package/dist/index.mjs +108 -20
  30. package/package.json +1 -1
  31. package/src/coordinate.ts +106 -106
  32. package/src/extensions/background.ts +230 -230
  33. package/src/extensions/bridgeSelection.ts +17 -17
  34. package/src/extensions/constraints.ts +322 -322
  35. package/src/extensions/dieline.ts +46 -0
  36. package/src/extensions/edgeScale.ts +19 -19
  37. package/src/extensions/feature.ts +1021 -1021
  38. package/src/extensions/featureComplete.ts +46 -46
  39. package/src/extensions/film.ts +194 -194
  40. package/src/extensions/geometry.ts +752 -719
  41. package/src/extensions/image.ts +1926 -1924
  42. package/src/extensions/index.ts +11 -11
  43. package/src/extensions/maskOps.ts +283 -283
  44. package/src/extensions/mirror.ts +128 -128
  45. package/src/extensions/ruler.ts +451 -451
  46. package/src/extensions/sceneLayout.ts +140 -140
  47. package/src/extensions/sceneLayoutModel.ts +352 -342
  48. package/src/extensions/sceneVisibility.ts +71 -71
  49. package/src/extensions/size.ts +389 -389
  50. package/src/extensions/tracer.ts +58 -19
  51. package/src/extensions/white-ink.ts +1400 -1400
  52. package/src/extensions/wrappedOffsets.ts +33 -33
  53. package/src/index.ts +2 -2
  54. package/src/services/CanvasService.ts +300 -300
  55. package/src/services/ViewportSystem.ts +95 -95
  56. package/src/services/index.ts +3 -3
  57. package/src/services/renderSpec.ts +18 -18
  58. package/src/units.ts +27 -27
  59. package/tests/run.ts +118 -118
  60. package/tsconfig.test.json +15 -15
@@ -1,719 +1,752 @@
1
- import paper from "paper";
2
- import { pickExitIndex, scoreOutsideAbove } from "./bridgeSelection";
3
- import { sampleWrappedOffsets, wrappedDistance } from "./wrappedOffsets";
4
-
5
- export type FeatureOperation = "add" | "subtract";
6
- export type FeatureShape = "rect" | "circle";
7
-
8
- export interface DielineFeature {
9
- id: string;
10
- groupId?: string;
11
- operation: FeatureOperation;
12
- shape: FeatureShape;
13
- x: number;
14
- y: number;
15
- width?: number;
16
- height?: number;
17
- radius?: number;
18
- rotation?: number;
19
- // Rendering behavior: 'edge' (modifies perimeter) or 'surface' (hole/island)
20
- renderBehavior?: "edge" | "surface";
21
- color?: string;
22
- strokeDash?: number[];
23
- skipCut?: boolean;
24
- bridge?: {
25
- type: "vertical";
26
- };
27
- }
28
-
29
- export interface GeometryOptions {
30
- shape: "rect" | "circle" | "ellipse" | "custom";
31
- width: number;
32
- height: number;
33
- radius: number;
34
- x: number;
35
- y: number;
36
- features: Array<DielineFeature>;
37
- pathData?: string;
38
- canvasWidth?: number;
39
- canvasHeight?: number;
40
- }
41
-
42
- export interface MaskGeometryOptions extends GeometryOptions {
43
- canvasWidth: number;
44
- canvasHeight: number;
45
- }
46
-
47
- /**
48
- * Resolves the absolute position of a feature based on normalized coordinates.
49
- */
50
- export function resolveFeaturePosition(
51
- feature: DielineFeature,
52
- geometry: { x: number; y: number; width: number; height: number },
53
- ): { x: number; y: number } {
54
- const { x, y, width, height } = geometry;
55
- // geometry.x/y is the Center.
56
- const left = x - width / 2;
57
- const top = y - height / 2;
58
-
59
- return {
60
- x: left + feature.x * width,
61
- y: top + feature.y * height,
62
- };
63
- }
64
-
65
- /**
66
- * Initializes paper.js project if not already initialized.
67
- */
68
- function ensurePaper(width: number, height: number) {
69
- if (!paper.project) {
70
- paper.setup(new paper.Size(width, height));
71
- } else {
72
- paper.view.viewSize = new paper.Size(width, height);
73
- }
74
- }
75
-
76
- const isBridgeDebugEnabled = () =>
77
- Boolean((globalThis as any).__POODER_BRIDGE_DEBUG__);
78
-
79
- function normalizePathItem(shape: paper.PathItem): paper.PathItem {
80
- let result: any = shape;
81
- if (typeof result.resolveCrossings === "function") result = result.resolveCrossings();
82
- if (typeof result.reduce === "function") result = result.reduce({});
83
- if (typeof result.reorient === "function") result = result.reorient(true, true);
84
- if (typeof result.reduce === "function") result = result.reduce({});
85
- return result as paper.PathItem;
86
- }
87
-
88
- function getBridgeDelta(itemBounds: paper.Rectangle, overlap: number) {
89
- return Math.max(overlap, Math.min(5, Math.max(1, itemBounds.height * 0.02)));
90
- }
91
-
92
- function getExitHit(args: {
93
- mainShape: paper.Path;
94
- x: number;
95
- bridgeBottom: number;
96
- toY: number;
97
- eps: number;
98
- delta: number;
99
- overlap: number;
100
- op: FeatureOperation;
101
- }) {
102
- const { mainShape, x, bridgeBottom, toY, eps, delta, overlap, op } = args;
103
-
104
- const ray = new paper.Path.Line({
105
- from: [x, bridgeBottom],
106
- to: [x, toY],
107
- insert: false,
108
- });
109
-
110
- const intersections = mainShape.getIntersections(ray) || [];
111
- ray.remove();
112
-
113
- const validHits = intersections.filter((i) => i.point.y < bridgeBottom - eps);
114
- if (validHits.length === 0) return null;
115
-
116
- validHits.sort((a, b) => b.point.y - a.point.y);
117
- const flags = validHits.map((h) => {
118
- const above = h.point.add(new paper.Point(0, -delta));
119
- const below = h.point.add(new paper.Point(0, delta));
120
- return {
121
- insideAbove: mainShape.contains(above),
122
- insideBelow: mainShape.contains(below),
123
- };
124
- });
125
-
126
- const idx = pickExitIndex(flags);
127
- if (idx < 0) return null;
128
-
129
- if (isBridgeDebugEnabled()) {
130
- console.debug("Geometry: Bridge ray", {
131
- x,
132
- validHits: validHits.length,
133
- idx,
134
- delta,
135
- overlap,
136
- op,
137
- });
138
- }
139
-
140
- const hit = validHits[idx];
141
- return { point: hit.point, location: hit };
142
- }
143
-
144
- function selectOuterChain(args: {
145
- mainShape: paper.Path;
146
- pointsA: paper.Point[];
147
- pointsB: paper.Point[];
148
- delta: number;
149
- overlap: number;
150
- op: FeatureOperation;
151
- }) {
152
- const { mainShape, pointsA, pointsB, delta, overlap, op } = args;
153
-
154
- const scoreA = scoreOutsideAbove(
155
- pointsA.map((p) => ({
156
- outsideAbove: !mainShape.contains(p.add(new paper.Point(0, -delta))),
157
- })),
158
- );
159
- const scoreB = scoreOutsideAbove(
160
- pointsB.map((p) => ({
161
- outsideAbove: !mainShape.contains(p.add(new paper.Point(0, -delta))),
162
- })),
163
- );
164
-
165
- const ratioA = scoreA / pointsA.length;
166
- const ratioB = scoreB / pointsB.length;
167
-
168
- if (isBridgeDebugEnabled()) {
169
- console.debug("Geometry: Bridge chain", {
170
- scoreA,
171
- scoreB,
172
- lenA: pointsA.length,
173
- lenB: pointsB.length,
174
- ratioA,
175
- ratioB,
176
- delta,
177
- overlap,
178
- op,
179
- });
180
- }
181
-
182
- const ratioEps = 1e-6;
183
- if (Math.abs(ratioA - ratioB) > ratioEps) {
184
- return ratioA > ratioB ? pointsA : pointsB;
185
- }
186
- if (scoreA !== scoreB) return scoreA > scoreB ? pointsA : pointsB;
187
- return pointsA.length <= pointsB.length ? pointsA : pointsB;
188
- }
189
-
190
- /**
191
- * Creates the base dieline shape (Rect/Circle/Ellipse/Custom)
192
- */
193
- function createBaseShape(options: GeometryOptions): paper.PathItem {
194
- const { shape, width, height, radius, x, y, pathData } = options;
195
- const center = new paper.Point(x, y);
196
-
197
- if (shape === "rect") {
198
- return new paper.Path.Rectangle({
199
- point: [x - width / 2, y - height / 2],
200
- size: [Math.max(0, width), Math.max(0, height)],
201
- radius: Math.max(0, radius),
202
- });
203
- } else if (shape === "circle") {
204
- const r = Math.min(width, height) / 2;
205
- return new paper.Path.Circle({
206
- center: center,
207
- radius: Math.max(0, r),
208
- });
209
- } else if (shape === "ellipse") {
210
- return new paper.Path.Ellipse({
211
- center: center,
212
- radius: [Math.max(0, width / 2), Math.max(0, height / 2)],
213
- });
214
- } else if (shape === "custom" && pathData) {
215
- const hasMultipleSubPaths = ((pathData.match(/[Mm]/g) || []).length ?? 0) > 1;
216
- const path: paper.PathItem = hasMultipleSubPaths
217
- ? new paper.CompoundPath(pathData)
218
- : (() => {
219
- const single = new paper.Path();
220
- single.pathData = pathData;
221
- return single;
222
- })();
223
- // Align center
224
- path.position = center;
225
- if (
226
- width > 0 &&
227
- height > 0 &&
228
- path.bounds.width > 0 &&
229
- path.bounds.height > 0
230
- ) {
231
- path.scale(width / path.bounds.width, height / path.bounds.height);
232
- }
233
- return path;
234
- } else {
235
- return new paper.Path.Rectangle({
236
- point: [x - width / 2, y - height / 2],
237
- size: [Math.max(0, width), Math.max(0, height)],
238
- });
239
- }
240
- }
241
-
242
- function resolveBridgeBasePath(
243
- shape: paper.PathItem,
244
- anchor: paper.Point,
245
- ): paper.Path | null {
246
- if (shape instanceof paper.Path) {
247
- return shape;
248
- }
249
-
250
- if (shape instanceof paper.CompoundPath) {
251
- const children = (shape.children || []).filter(
252
- (child): child is paper.Path => child instanceof paper.Path,
253
- );
254
- if (!children.length) return null;
255
- let best = children[0];
256
- let bestDistance = Infinity;
257
- for (const child of children) {
258
- const location = child.getNearestLocation(anchor);
259
- const point = location?.point;
260
- if (!point) continue;
261
- const distance = point.getDistance(anchor);
262
- if (distance < bestDistance) {
263
- bestDistance = distance;
264
- best = child;
265
- }
266
- }
267
- return best;
268
- }
269
-
270
- return null;
271
- }
272
-
273
- /**
274
- * Creates a Paper.js Item for a single feature.
275
- */
276
- function createFeatureItem(
277
- feature: DielineFeature,
278
- center: paper.Point,
279
- ): paper.PathItem {
280
- let item: paper.PathItem;
281
-
282
- if (feature.shape === "rect") {
283
- const w = feature.width || 10;
284
- const h = feature.height || 10;
285
- const r = feature.radius || 0;
286
- item = new paper.Path.Rectangle({
287
- point: [center.x - w / 2, center.y - h / 2],
288
- size: [w, h],
289
- radius: r,
290
- });
291
- } else {
292
- // Circle
293
- const r = feature.radius || 5;
294
- item = new paper.Path.Circle({
295
- center: center,
296
- radius: r,
297
- });
298
- }
299
-
300
- if (feature.rotation) {
301
- item.rotate(feature.rotation, center);
302
- }
303
-
304
- return item;
305
- }
306
-
307
- /**
308
- * Internal helper to generate the Perimeter Shape (Base + Edge Features).
309
- */
310
- function getPerimeterShape(options: GeometryOptions): paper.PathItem {
311
- // 1. Create Base Shape
312
- let mainShape = createBaseShape(options);
313
-
314
- const { features } = options;
315
-
316
- if (features && features.length > 0) {
317
- // Filter for Edge Features (Default is Edge, unless explicit 'surface')
318
- const edgeFeatures = features.filter(
319
- (f) => !f.renderBehavior || f.renderBehavior === "edge",
320
- );
321
-
322
- const adds: paper.PathItem[] = [];
323
- const subtracts: paper.PathItem[] = [];
324
-
325
- edgeFeatures.forEach((f) => {
326
- const pos = resolveFeaturePosition(f, options);
327
- const center = new paper.Point(pos.x, pos.y);
328
- const item = createFeatureItem(f, center);
329
-
330
- // Handle Bridge logic: Create a connection shape to the main body
331
- if (f.bridge && f.bridge.type === "vertical") {
332
- const itemBounds = item.bounds;
333
- const mainBounds = mainShape.bounds;
334
- const bridgeTop = mainBounds.top;
335
- const bridgeBottom = itemBounds.top;
336
-
337
- if (bridgeBottom > bridgeTop) {
338
- const overlap = 2;
339
- const rayPadding = 10;
340
- const eps = 0.1;
341
- const delta = getBridgeDelta(itemBounds, overlap);
342
-
343
- const toY = bridgeTop - rayPadding;
344
- const inset = Math.min(1, Math.max(0, itemBounds.width * 0.01));
345
- const xLeft = itemBounds.left + inset;
346
- const xRight = itemBounds.right - inset;
347
- const bridgeBasePath = resolveBridgeBasePath(mainShape, center);
348
- const canBridge = !!bridgeBasePath && xRight - xLeft > eps;
349
-
350
- if (canBridge && bridgeBasePath) {
351
- const leftHit = getExitHit({
352
- mainShape: bridgeBasePath,
353
- x: xLeft,
354
- bridgeBottom,
355
- toY,
356
- eps,
357
- delta,
358
- overlap,
359
- op: f.operation,
360
- });
361
- const rightHit = getExitHit({
362
- mainShape: bridgeBasePath,
363
- x: xRight,
364
- bridgeBottom,
365
- toY,
366
- eps,
367
- delta,
368
- overlap,
369
- op: f.operation,
370
- });
371
-
372
- if (leftHit && rightHit) {
373
- const pathLength = bridgeBasePath.length;
374
- const leftOffset = leftHit.location.offset;
375
- const rightOffset = rightHit.location.offset;
376
-
377
- const distanceA = wrappedDistance(pathLength, leftOffset, rightOffset);
378
- const distanceB = wrappedDistance(pathLength, rightOffset, leftOffset);
379
- const countFor = (d: number) =>
380
- Math.max(8, Math.min(80, Math.ceil(d / 6)));
381
-
382
- const offsetsA = sampleWrappedOffsets(
383
- pathLength,
384
- leftOffset,
385
- rightOffset,
386
- countFor(distanceA),
387
- );
388
-
389
- const offsetsB = sampleWrappedOffsets(
390
- pathLength,
391
- rightOffset,
392
- leftOffset,
393
- countFor(distanceB),
394
- );
395
-
396
- const pointsA = offsetsA
397
- .map((o) => bridgeBasePath.getPointAt(o))
398
- .filter((p): p is paper.Point => Boolean(p));
399
- const pointsB = offsetsB
400
- .map((o) => bridgeBasePath.getPointAt(o))
401
- .filter((p): p is paper.Point => Boolean(p));
402
-
403
- if (pointsA.length >= 2 && pointsB.length >= 2) {
404
- let topBase = selectOuterChain({
405
- mainShape: bridgeBasePath,
406
- pointsA,
407
- pointsB,
408
- delta,
409
- overlap,
410
- op: f.operation,
411
- });
412
-
413
- const dist2 = (a: paper.Point, b: paper.Point) => {
414
- const dx = a.x - b.x;
415
- const dy = a.y - b.y;
416
- return dx * dx + dy * dy;
417
- };
418
-
419
- if (
420
- dist2(topBase[0], leftHit.point) >
421
- dist2(topBase[0], rightHit.point)
422
- ) {
423
- topBase = topBase.slice().reverse();
424
- }
425
-
426
- topBase = topBase.slice();
427
- topBase[0] = leftHit.point;
428
- topBase[topBase.length - 1] = rightHit.point;
429
-
430
- const capShiftY =
431
- f.operation === "subtract"
432
- ? -Math.max(overlap * 2, delta)
433
- : overlap;
434
- const topPoints = topBase.map((p) =>
435
- p.add(new paper.Point(0, capShiftY)),
436
- );
437
-
438
- const bridgeBottomY = bridgeBottom + overlap * 2;
439
- const bridgePoly = new paper.Path({ insert: false });
440
- for (const p of topPoints) bridgePoly.add(p);
441
- bridgePoly.add(new paper.Point(xRight, bridgeBottomY));
442
- bridgePoly.add(new paper.Point(xLeft, bridgeBottomY));
443
- bridgePoly.closed = true;
444
-
445
- const unitedItem = item.unite(bridgePoly);
446
- item.remove();
447
- bridgePoly.remove();
448
-
449
- if (f.operation === "add") {
450
- adds.push(unitedItem);
451
- } else {
452
- subtracts.push(unitedItem);
453
- }
454
- return;
455
- }
456
- }
457
- }
458
-
459
- if (f.operation === "add") {
460
- adds.push(item);
461
- } else {
462
- subtracts.push(item);
463
- }
464
- } else {
465
- if (f.operation === "add") {
466
- adds.push(item);
467
- } else {
468
- subtracts.push(item);
469
- }
470
- }
471
- } else {
472
- if (f.operation === "add") {
473
- adds.push(item);
474
- } else {
475
- subtracts.push(item);
476
- }
477
- }
478
- });
479
-
480
- // 2. Process Additions (Union)
481
- if (adds.length > 0) {
482
- for (const item of adds) {
483
- try {
484
- const temp = mainShape.unite(item);
485
- mainShape.remove();
486
- item.remove();
487
- mainShape = normalizePathItem(temp);
488
- } catch (e) {
489
- console.error("Geometry: Failed to unite feature", e);
490
- item.remove();
491
- }
492
- }
493
- }
494
-
495
- // 3. Process Subtractions (Difference)
496
- if (subtracts.length > 0) {
497
- for (const item of subtracts) {
498
- try {
499
- const temp = mainShape.subtract(item);
500
- mainShape.remove();
501
- item.remove();
502
- mainShape = normalizePathItem(temp);
503
- } catch (e) {
504
- console.error("Geometry: Failed to subtract feature", e);
505
- item.remove();
506
- }
507
- }
508
- }
509
- }
510
-
511
- return mainShape;
512
- }
513
-
514
- /**
515
- * Applies Internal/Surface features to a shape.
516
- */
517
- function applySurfaceFeatures(
518
- shape: paper.PathItem,
519
- features: DielineFeature[],
520
- options: GeometryOptions,
521
- ): paper.PathItem {
522
- const surfaceFeatures = features.filter(
523
- (f) => f.renderBehavior === "surface",
524
- );
525
-
526
- if (surfaceFeatures.length === 0) return shape;
527
-
528
- let result = shape;
529
-
530
- // Internal features are usually subtractive (holes)
531
- // But we support 'add' too (islands? maybe just unite)
532
-
533
- for (const f of surfaceFeatures) {
534
- const pos = resolveFeaturePosition(f, options);
535
- const center = new paper.Point(pos.x, pos.y);
536
- const item = createFeatureItem(f, center);
537
-
538
- try {
539
- if (f.operation === "add") {
540
- const temp = result.unite(item);
541
- result.remove();
542
- item.remove();
543
- result = normalizePathItem(temp);
544
- } else {
545
- const temp = result.subtract(item);
546
- result.remove();
547
- item.remove();
548
- result = normalizePathItem(temp);
549
- }
550
- } catch (e) {
551
- console.error("Geometry: Failed to apply surface feature", e);
552
- item.remove();
553
- }
554
- }
555
-
556
- return result;
557
- }
558
-
559
- /**
560
- * Generates the path data for the Dieline (Product Shape).
561
- */
562
- export function generateDielinePath(options: GeometryOptions): string {
563
- const paperWidth = options.canvasWidth || options.width * 2 || 2000;
564
- const paperHeight = options.canvasHeight || options.height * 2 || 2000;
565
- ensurePaper(paperWidth, paperHeight);
566
- paper.project.activeLayer.removeChildren();
567
-
568
- const perimeter = getPerimeterShape(options);
569
- const finalShape = applySurfaceFeatures(perimeter, options.features, options);
570
-
571
- const pathData = finalShape.pathData;
572
- finalShape.remove();
573
-
574
- return pathData;
575
- }
576
-
577
- /**
578
- * Generates the path data for the Mask (Background Overlay).
579
- * Logic: Canvas SUBTRACT ProductShape
580
- */
581
- export function generateMaskPath(options: MaskGeometryOptions): string {
582
- ensurePaper(options.canvasWidth, options.canvasHeight);
583
- paper.project.activeLayer.removeChildren();
584
-
585
- const { canvasWidth, canvasHeight } = options;
586
-
587
- const maskRect = new paper.Path.Rectangle({
588
- point: [0, 0],
589
- size: [canvasWidth, canvasHeight],
590
- });
591
-
592
- const perimeter = getPerimeterShape(options);
593
- const mainShape = applySurfaceFeatures(perimeter, options.features, options);
594
-
595
- const finalMask = maskRect.subtract(mainShape);
596
-
597
- maskRect.remove();
598
- mainShape.remove();
599
-
600
- const pathData = finalMask.pathData;
601
- finalMask.remove();
602
-
603
- return pathData;
604
- }
605
-
606
- /**
607
- * Generates the path data for the Bleed Zone.
608
- */
609
- export function generateBleedZonePath(
610
- originalOptions: GeometryOptions,
611
- offsetOptions: GeometryOptions,
612
- offset: number,
613
- ): string {
614
- const paperWidth =
615
- originalOptions.canvasWidth || originalOptions.width * 2 || 2000;
616
- const paperHeight =
617
- originalOptions.canvasHeight || originalOptions.height * 2 || 2000;
618
- ensurePaper(paperWidth, paperHeight);
619
- paper.project.activeLayer.removeChildren();
620
-
621
- // 1. Generate Original Shape
622
- const pOriginal = getPerimeterShape(originalOptions);
623
- const shapeOriginal = applySurfaceFeatures(
624
- pOriginal,
625
- originalOptions.features,
626
- originalOptions,
627
- );
628
-
629
- // 2. Generate Offset Shape
630
- const pOffset = getPerimeterShape(offsetOptions);
631
- const shapeOffset = applySurfaceFeatures(
632
- pOffset,
633
- offsetOptions.features,
634
- offsetOptions,
635
- );
636
-
637
- // 3. Calculate Difference
638
- let bleedZone: paper.PathItem;
639
- if (offset > 0) {
640
- bleedZone = shapeOffset.subtract(shapeOriginal);
641
- } else {
642
- bleedZone = shapeOriginal.subtract(shapeOffset);
643
- }
644
-
645
- const pathData = bleedZone.pathData;
646
-
647
- shapeOriginal.remove();
648
- shapeOffset.remove();
649
- bleedZone.remove();
650
-
651
- return pathData;
652
- }
653
-
654
- /**
655
- * Finds the lowest point (Max Y) on the Dieline geometry (Base Shape ONLY).
656
- */
657
- export function getLowestPointOnDieline(
658
- options: GeometryOptions,
659
- ): { x: number; y: number } {
660
- ensurePaper(options.width * 2, options.height * 2);
661
- paper.project.activeLayer.removeChildren();
662
-
663
- const shape = createBaseShape(options);
664
- const bounds = shape.bounds;
665
-
666
- const result = {
667
- x: bounds.center.x,
668
- y: bounds.bottom,
669
- };
670
- shape.remove();
671
-
672
- return result;
673
- }
674
-
675
- /**
676
- * Finds the nearest point on the Dieline geometry (Base Shape ONLY) for a given target point.
677
- * Used for constraining feature movement.
678
- */
679
- export function getNearestPointOnDieline(
680
- point: { x: number; y: number },
681
- options: GeometryOptions,
682
- ): { x: number; y: number; normal?: { x: number; y: number } } {
683
- ensurePaper(options.width * 2, options.height * 2);
684
- paper.project.activeLayer.removeChildren();
685
-
686
- // We constrain to the BASE shape, not including other features,
687
- // because usually you want to snap to the main edge.
688
- const shape = createBaseShape(options);
689
-
690
- const p = new paper.Point(point.x, point.y);
691
- const location = shape.getNearestLocation(p);
692
-
693
- const result = {
694
- x: location.point.x,
695
- y: location.point.y,
696
- normal: location.normal ? { x: location.normal.x, y: location.normal.y } : undefined
697
- };
698
- shape.remove();
699
-
700
- return result;
701
- }
702
-
703
- export function getPathBounds(pathData: string): {
704
- x: number;
705
- y: number;
706
- width: number;
707
- height: number;
708
- } {
709
- const path = new paper.Path();
710
- path.pathData = pathData;
711
- const bounds = path.bounds;
712
- path.remove();
713
- return {
714
- x: bounds.x,
715
- y: bounds.y,
716
- width: bounds.width,
717
- height: bounds.height,
718
- };
719
- }
1
+ import paper from "paper";
2
+ import { pickExitIndex, scoreOutsideAbove } from "./bridgeSelection";
3
+ import { sampleWrappedOffsets, wrappedDistance } from "./wrappedOffsets";
4
+
5
+ export type FeatureOperation = "add" | "subtract";
6
+ export type FeatureShape = "rect" | "circle";
7
+
8
+ export interface DielineFeature {
9
+ id: string;
10
+ groupId?: string;
11
+ operation: FeatureOperation;
12
+ shape: FeatureShape;
13
+ x: number;
14
+ y: number;
15
+ width?: number;
16
+ height?: number;
17
+ radius?: number;
18
+ rotation?: number;
19
+ // Rendering behavior: 'edge' (modifies perimeter) or 'surface' (hole/island)
20
+ renderBehavior?: "edge" | "surface";
21
+ color?: string;
22
+ strokeDash?: number[];
23
+ skipCut?: boolean;
24
+ bridge?: {
25
+ type: "vertical";
26
+ };
27
+ }
28
+
29
+ export interface GeometryOptions {
30
+ shape: "rect" | "circle" | "ellipse" | "custom";
31
+ width: number;
32
+ height: number;
33
+ radius: number;
34
+ x: number;
35
+ y: number;
36
+ features: Array<DielineFeature>;
37
+ pathData?: string;
38
+ customSourceWidthPx?: number;
39
+ customSourceHeightPx?: number;
40
+ canvasWidth?: number;
41
+ canvasHeight?: number;
42
+ }
43
+
44
+ export interface MaskGeometryOptions extends GeometryOptions {
45
+ canvasWidth: number;
46
+ canvasHeight: number;
47
+ }
48
+
49
+ /**
50
+ * Resolves the absolute position of a feature based on normalized coordinates.
51
+ */
52
+ export function resolveFeaturePosition(
53
+ feature: DielineFeature,
54
+ geometry: { x: number; y: number; width: number; height: number },
55
+ ): { x: number; y: number } {
56
+ const { x, y, width, height } = geometry;
57
+ // geometry.x/y is the Center.
58
+ const left = x - width / 2;
59
+ const top = y - height / 2;
60
+
61
+ return {
62
+ x: left + feature.x * width,
63
+ y: top + feature.y * height,
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Initializes paper.js project if not already initialized.
69
+ */
70
+ function ensurePaper(width: number, height: number) {
71
+ if (!paper.project) {
72
+ paper.setup(new paper.Size(width, height));
73
+ } else {
74
+ paper.view.viewSize = new paper.Size(width, height);
75
+ }
76
+ }
77
+
78
+ const isBridgeDebugEnabled = () =>
79
+ Boolean((globalThis as any).__POODER_BRIDGE_DEBUG__);
80
+
81
+ function normalizePathItem(shape: paper.PathItem): paper.PathItem {
82
+ let result: any = shape;
83
+ if (typeof result.resolveCrossings === "function") result = result.resolveCrossings();
84
+ if (typeof result.reduce === "function") result = result.reduce({});
85
+ if (typeof result.reorient === "function") result = result.reorient(true, true);
86
+ if (typeof result.reduce === "function") result = result.reduce({});
87
+ return result as paper.PathItem;
88
+ }
89
+
90
+ function getBridgeDelta(itemBounds: paper.Rectangle, overlap: number) {
91
+ return Math.max(overlap, Math.min(5, Math.max(1, itemBounds.height * 0.02)));
92
+ }
93
+
94
+ function getExitHit(args: {
95
+ mainShape: paper.Path;
96
+ x: number;
97
+ bridgeBottom: number;
98
+ toY: number;
99
+ eps: number;
100
+ delta: number;
101
+ overlap: number;
102
+ op: FeatureOperation;
103
+ }) {
104
+ const { mainShape, x, bridgeBottom, toY, eps, delta, overlap, op } = args;
105
+
106
+ const ray = new paper.Path.Line({
107
+ from: [x, bridgeBottom],
108
+ to: [x, toY],
109
+ insert: false,
110
+ });
111
+
112
+ const intersections = mainShape.getIntersections(ray) || [];
113
+ ray.remove();
114
+
115
+ const validHits = intersections.filter((i) => i.point.y < bridgeBottom - eps);
116
+ if (validHits.length === 0) return null;
117
+
118
+ validHits.sort((a, b) => b.point.y - a.point.y);
119
+ const flags = validHits.map((h) => {
120
+ const above = h.point.add(new paper.Point(0, -delta));
121
+ const below = h.point.add(new paper.Point(0, delta));
122
+ return {
123
+ insideAbove: mainShape.contains(above),
124
+ insideBelow: mainShape.contains(below),
125
+ };
126
+ });
127
+
128
+ const idx = pickExitIndex(flags);
129
+ if (idx < 0) return null;
130
+
131
+ if (isBridgeDebugEnabled()) {
132
+ console.debug("Geometry: Bridge ray", {
133
+ x,
134
+ validHits: validHits.length,
135
+ idx,
136
+ delta,
137
+ overlap,
138
+ op,
139
+ });
140
+ }
141
+
142
+ const hit = validHits[idx];
143
+ return { point: hit.point, location: hit };
144
+ }
145
+
146
+ function selectOuterChain(args: {
147
+ mainShape: paper.Path;
148
+ pointsA: paper.Point[];
149
+ pointsB: paper.Point[];
150
+ delta: number;
151
+ overlap: number;
152
+ op: FeatureOperation;
153
+ }) {
154
+ const { mainShape, pointsA, pointsB, delta, overlap, op } = args;
155
+
156
+ const scoreA = scoreOutsideAbove(
157
+ pointsA.map((p) => ({
158
+ outsideAbove: !mainShape.contains(p.add(new paper.Point(0, -delta))),
159
+ })),
160
+ );
161
+ const scoreB = scoreOutsideAbove(
162
+ pointsB.map((p) => ({
163
+ outsideAbove: !mainShape.contains(p.add(new paper.Point(0, -delta))),
164
+ })),
165
+ );
166
+
167
+ const ratioA = scoreA / pointsA.length;
168
+ const ratioB = scoreB / pointsB.length;
169
+
170
+ if (isBridgeDebugEnabled()) {
171
+ console.debug("Geometry: Bridge chain", {
172
+ scoreA,
173
+ scoreB,
174
+ lenA: pointsA.length,
175
+ lenB: pointsB.length,
176
+ ratioA,
177
+ ratioB,
178
+ delta,
179
+ overlap,
180
+ op,
181
+ });
182
+ }
183
+
184
+ const ratioEps = 1e-6;
185
+ if (Math.abs(ratioA - ratioB) > ratioEps) {
186
+ return ratioA > ratioB ? pointsA : pointsB;
187
+ }
188
+ if (scoreA !== scoreB) return scoreA > scoreB ? pointsA : pointsB;
189
+ return pointsA.length <= pointsB.length ? pointsA : pointsB;
190
+ }
191
+
192
+ /**
193
+ * Creates the base dieline shape (Rect/Circle/Ellipse/Custom)
194
+ */
195
+ function createBaseShape(options: GeometryOptions): paper.PathItem {
196
+ const {
197
+ shape,
198
+ width,
199
+ height,
200
+ radius,
201
+ x,
202
+ y,
203
+ pathData,
204
+ customSourceWidthPx,
205
+ customSourceHeightPx,
206
+ } = options;
207
+ const center = new paper.Point(x, y);
208
+
209
+ if (shape === "rect") {
210
+ return new paper.Path.Rectangle({
211
+ point: [x - width / 2, y - height / 2],
212
+ size: [Math.max(0, width), Math.max(0, height)],
213
+ radius: Math.max(0, radius),
214
+ });
215
+ } else if (shape === "circle") {
216
+ const r = Math.min(width, height) / 2;
217
+ return new paper.Path.Circle({
218
+ center: center,
219
+ radius: Math.max(0, r),
220
+ });
221
+ } else if (shape === "ellipse") {
222
+ return new paper.Path.Ellipse({
223
+ center: center,
224
+ radius: [Math.max(0, width / 2), Math.max(0, height / 2)],
225
+ });
226
+ } else if (shape === "custom" && pathData) {
227
+ const hasMultipleSubPaths = ((pathData.match(/[Mm]/g) || []).length ?? 0) > 1;
228
+ const path: paper.PathItem = hasMultipleSubPaths
229
+ ? new paper.CompoundPath(pathData)
230
+ : (() => {
231
+ const single = new paper.Path();
232
+ single.pathData = pathData;
233
+ return single;
234
+ })();
235
+ const sourceWidth = Number(customSourceWidthPx ?? 0);
236
+ const sourceHeight = Number(customSourceHeightPx ?? 0);
237
+ if (
238
+ Number.isFinite(sourceWidth) &&
239
+ Number.isFinite(sourceHeight) &&
240
+ sourceWidth > 0 &&
241
+ sourceHeight > 0 &&
242
+ width > 0 &&
243
+ height > 0
244
+ ) {
245
+ // Preserve original detect-space offset/expand by mapping source image
246
+ // coordinates directly into the target dieline frame.
247
+ const targetLeft = x - width / 2;
248
+ const targetTop = y - height / 2;
249
+ path.scale(width / sourceWidth, height / sourceHeight, new paper.Point(0, 0));
250
+ path.translate(new paper.Point(targetLeft, targetTop));
251
+ return path;
252
+ }
253
+
254
+ if (
255
+ width > 0 &&
256
+ height > 0 &&
257
+ path.bounds.width > 0 &&
258
+ path.bounds.height > 0
259
+ ) {
260
+ // Fallback for malformed custom-path metadata.
261
+ path.position = center;
262
+ path.scale(width / path.bounds.width, height / path.bounds.height);
263
+ return path;
264
+ }
265
+ path.position = center;
266
+ return path;
267
+ } else {
268
+ return new paper.Path.Rectangle({
269
+ point: [x - width / 2, y - height / 2],
270
+ size: [Math.max(0, width), Math.max(0, height)],
271
+ });
272
+ }
273
+ }
274
+
275
+ function resolveBridgeBasePath(
276
+ shape: paper.PathItem,
277
+ anchor: paper.Point,
278
+ ): paper.Path | null {
279
+ if (shape instanceof paper.Path) {
280
+ return shape;
281
+ }
282
+
283
+ if (shape instanceof paper.CompoundPath) {
284
+ const children = (shape.children || []).filter(
285
+ (child): child is paper.Path => child instanceof paper.Path,
286
+ );
287
+ if (!children.length) return null;
288
+ let best = children[0];
289
+ let bestDistance = Infinity;
290
+ for (const child of children) {
291
+ const location = child.getNearestLocation(anchor);
292
+ const point = location?.point;
293
+ if (!point) continue;
294
+ const distance = point.getDistance(anchor);
295
+ if (distance < bestDistance) {
296
+ bestDistance = distance;
297
+ best = child;
298
+ }
299
+ }
300
+ return best;
301
+ }
302
+
303
+ return null;
304
+ }
305
+
306
+ /**
307
+ * Creates a Paper.js Item for a single feature.
308
+ */
309
+ function createFeatureItem(
310
+ feature: DielineFeature,
311
+ center: paper.Point,
312
+ ): paper.PathItem {
313
+ let item: paper.PathItem;
314
+
315
+ if (feature.shape === "rect") {
316
+ const w = feature.width || 10;
317
+ const h = feature.height || 10;
318
+ const r = feature.radius || 0;
319
+ item = new paper.Path.Rectangle({
320
+ point: [center.x - w / 2, center.y - h / 2],
321
+ size: [w, h],
322
+ radius: r,
323
+ });
324
+ } else {
325
+ // Circle
326
+ const r = feature.radius || 5;
327
+ item = new paper.Path.Circle({
328
+ center: center,
329
+ radius: r,
330
+ });
331
+ }
332
+
333
+ if (feature.rotation) {
334
+ item.rotate(feature.rotation, center);
335
+ }
336
+
337
+ return item;
338
+ }
339
+
340
+ /**
341
+ * Internal helper to generate the Perimeter Shape (Base + Edge Features).
342
+ */
343
+ function getPerimeterShape(options: GeometryOptions): paper.PathItem {
344
+ // 1. Create Base Shape
345
+ let mainShape = createBaseShape(options);
346
+
347
+ const { features } = options;
348
+
349
+ if (features && features.length > 0) {
350
+ // Filter for Edge Features (Default is Edge, unless explicit 'surface')
351
+ const edgeFeatures = features.filter(
352
+ (f) => !f.renderBehavior || f.renderBehavior === "edge",
353
+ );
354
+
355
+ const adds: paper.PathItem[] = [];
356
+ const subtracts: paper.PathItem[] = [];
357
+
358
+ edgeFeatures.forEach((f) => {
359
+ const pos = resolveFeaturePosition(f, options);
360
+ const center = new paper.Point(pos.x, pos.y);
361
+ const item = createFeatureItem(f, center);
362
+
363
+ // Handle Bridge logic: Create a connection shape to the main body
364
+ if (f.bridge && f.bridge.type === "vertical") {
365
+ const itemBounds = item.bounds;
366
+ const mainBounds = mainShape.bounds;
367
+ const bridgeTop = mainBounds.top;
368
+ const bridgeBottom = itemBounds.top;
369
+
370
+ if (bridgeBottom > bridgeTop) {
371
+ const overlap = 2;
372
+ const rayPadding = 10;
373
+ const eps = 0.1;
374
+ const delta = getBridgeDelta(itemBounds, overlap);
375
+
376
+ const toY = bridgeTop - rayPadding;
377
+ const inset = Math.min(1, Math.max(0, itemBounds.width * 0.01));
378
+ const xLeft = itemBounds.left + inset;
379
+ const xRight = itemBounds.right - inset;
380
+ const bridgeBasePath = resolveBridgeBasePath(mainShape, center);
381
+ const canBridge = !!bridgeBasePath && xRight - xLeft > eps;
382
+
383
+ if (canBridge && bridgeBasePath) {
384
+ const leftHit = getExitHit({
385
+ mainShape: bridgeBasePath,
386
+ x: xLeft,
387
+ bridgeBottom,
388
+ toY,
389
+ eps,
390
+ delta,
391
+ overlap,
392
+ op: f.operation,
393
+ });
394
+ const rightHit = getExitHit({
395
+ mainShape: bridgeBasePath,
396
+ x: xRight,
397
+ bridgeBottom,
398
+ toY,
399
+ eps,
400
+ delta,
401
+ overlap,
402
+ op: f.operation,
403
+ });
404
+
405
+ if (leftHit && rightHit) {
406
+ const pathLength = bridgeBasePath.length;
407
+ const leftOffset = leftHit.location.offset;
408
+ const rightOffset = rightHit.location.offset;
409
+
410
+ const distanceA = wrappedDistance(pathLength, leftOffset, rightOffset);
411
+ const distanceB = wrappedDistance(pathLength, rightOffset, leftOffset);
412
+ const countFor = (d: number) =>
413
+ Math.max(8, Math.min(80, Math.ceil(d / 6)));
414
+
415
+ const offsetsA = sampleWrappedOffsets(
416
+ pathLength,
417
+ leftOffset,
418
+ rightOffset,
419
+ countFor(distanceA),
420
+ );
421
+
422
+ const offsetsB = sampleWrappedOffsets(
423
+ pathLength,
424
+ rightOffset,
425
+ leftOffset,
426
+ countFor(distanceB),
427
+ );
428
+
429
+ const pointsA = offsetsA
430
+ .map((o) => bridgeBasePath.getPointAt(o))
431
+ .filter((p): p is paper.Point => Boolean(p));
432
+ const pointsB = offsetsB
433
+ .map((o) => bridgeBasePath.getPointAt(o))
434
+ .filter((p): p is paper.Point => Boolean(p));
435
+
436
+ if (pointsA.length >= 2 && pointsB.length >= 2) {
437
+ let topBase = selectOuterChain({
438
+ mainShape: bridgeBasePath,
439
+ pointsA,
440
+ pointsB,
441
+ delta,
442
+ overlap,
443
+ op: f.operation,
444
+ });
445
+
446
+ const dist2 = (a: paper.Point, b: paper.Point) => {
447
+ const dx = a.x - b.x;
448
+ const dy = a.y - b.y;
449
+ return dx * dx + dy * dy;
450
+ };
451
+
452
+ if (
453
+ dist2(topBase[0], leftHit.point) >
454
+ dist2(topBase[0], rightHit.point)
455
+ ) {
456
+ topBase = topBase.slice().reverse();
457
+ }
458
+
459
+ topBase = topBase.slice();
460
+ topBase[0] = leftHit.point;
461
+ topBase[topBase.length - 1] = rightHit.point;
462
+
463
+ const capShiftY =
464
+ f.operation === "subtract"
465
+ ? -Math.max(overlap * 2, delta)
466
+ : overlap;
467
+ const topPoints = topBase.map((p) =>
468
+ p.add(new paper.Point(0, capShiftY)),
469
+ );
470
+
471
+ const bridgeBottomY = bridgeBottom + overlap * 2;
472
+ const bridgePoly = new paper.Path({ insert: false });
473
+ for (const p of topPoints) bridgePoly.add(p);
474
+ bridgePoly.add(new paper.Point(xRight, bridgeBottomY));
475
+ bridgePoly.add(new paper.Point(xLeft, bridgeBottomY));
476
+ bridgePoly.closed = true;
477
+
478
+ const unitedItem = item.unite(bridgePoly);
479
+ item.remove();
480
+ bridgePoly.remove();
481
+
482
+ if (f.operation === "add") {
483
+ adds.push(unitedItem);
484
+ } else {
485
+ subtracts.push(unitedItem);
486
+ }
487
+ return;
488
+ }
489
+ }
490
+ }
491
+
492
+ if (f.operation === "add") {
493
+ adds.push(item);
494
+ } else {
495
+ subtracts.push(item);
496
+ }
497
+ } else {
498
+ if (f.operation === "add") {
499
+ adds.push(item);
500
+ } else {
501
+ subtracts.push(item);
502
+ }
503
+ }
504
+ } else {
505
+ if (f.operation === "add") {
506
+ adds.push(item);
507
+ } else {
508
+ subtracts.push(item);
509
+ }
510
+ }
511
+ });
512
+
513
+ // 2. Process Additions (Union)
514
+ if (adds.length > 0) {
515
+ for (const item of adds) {
516
+ try {
517
+ const temp = mainShape.unite(item);
518
+ mainShape.remove();
519
+ item.remove();
520
+ mainShape = normalizePathItem(temp);
521
+ } catch (e) {
522
+ console.error("Geometry: Failed to unite feature", e);
523
+ item.remove();
524
+ }
525
+ }
526
+ }
527
+
528
+ // 3. Process Subtractions (Difference)
529
+ if (subtracts.length > 0) {
530
+ for (const item of subtracts) {
531
+ try {
532
+ const temp = mainShape.subtract(item);
533
+ mainShape.remove();
534
+ item.remove();
535
+ mainShape = normalizePathItem(temp);
536
+ } catch (e) {
537
+ console.error("Geometry: Failed to subtract feature", e);
538
+ item.remove();
539
+ }
540
+ }
541
+ }
542
+ }
543
+
544
+ return mainShape;
545
+ }
546
+
547
+ /**
548
+ * Applies Internal/Surface features to a shape.
549
+ */
550
+ function applySurfaceFeatures(
551
+ shape: paper.PathItem,
552
+ features: DielineFeature[],
553
+ options: GeometryOptions,
554
+ ): paper.PathItem {
555
+ const surfaceFeatures = features.filter(
556
+ (f) => f.renderBehavior === "surface",
557
+ );
558
+
559
+ if (surfaceFeatures.length === 0) return shape;
560
+
561
+ let result = shape;
562
+
563
+ // Internal features are usually subtractive (holes)
564
+ // But we support 'add' too (islands? maybe just unite)
565
+
566
+ for (const f of surfaceFeatures) {
567
+ const pos = resolveFeaturePosition(f, options);
568
+ const center = new paper.Point(pos.x, pos.y);
569
+ const item = createFeatureItem(f, center);
570
+
571
+ try {
572
+ if (f.operation === "add") {
573
+ const temp = result.unite(item);
574
+ result.remove();
575
+ item.remove();
576
+ result = normalizePathItem(temp);
577
+ } else {
578
+ const temp = result.subtract(item);
579
+ result.remove();
580
+ item.remove();
581
+ result = normalizePathItem(temp);
582
+ }
583
+ } catch (e) {
584
+ console.error("Geometry: Failed to apply surface feature", e);
585
+ item.remove();
586
+ }
587
+ }
588
+
589
+ return result;
590
+ }
591
+
592
+ /**
593
+ * Generates the path data for the Dieline (Product Shape).
594
+ */
595
+ export function generateDielinePath(options: GeometryOptions): string {
596
+ const paperWidth = options.canvasWidth || options.width * 2 || 2000;
597
+ const paperHeight = options.canvasHeight || options.height * 2 || 2000;
598
+ ensurePaper(paperWidth, paperHeight);
599
+ paper.project.activeLayer.removeChildren();
600
+
601
+ const perimeter = getPerimeterShape(options);
602
+ const finalShape = applySurfaceFeatures(perimeter, options.features, options);
603
+
604
+ const pathData = finalShape.pathData;
605
+ finalShape.remove();
606
+
607
+ return pathData;
608
+ }
609
+
610
+ /**
611
+ * Generates the path data for the Mask (Background Overlay).
612
+ * Logic: Canvas SUBTRACT ProductShape
613
+ */
614
+ export function generateMaskPath(options: MaskGeometryOptions): string {
615
+ ensurePaper(options.canvasWidth, options.canvasHeight);
616
+ paper.project.activeLayer.removeChildren();
617
+
618
+ const { canvasWidth, canvasHeight } = options;
619
+
620
+ const maskRect = new paper.Path.Rectangle({
621
+ point: [0, 0],
622
+ size: [canvasWidth, canvasHeight],
623
+ });
624
+
625
+ const perimeter = getPerimeterShape(options);
626
+ const mainShape = applySurfaceFeatures(perimeter, options.features, options);
627
+
628
+ const finalMask = maskRect.subtract(mainShape);
629
+
630
+ maskRect.remove();
631
+ mainShape.remove();
632
+
633
+ const pathData = finalMask.pathData;
634
+ finalMask.remove();
635
+
636
+ return pathData;
637
+ }
638
+
639
+ /**
640
+ * Generates the path data for the Bleed Zone.
641
+ */
642
+ export function generateBleedZonePath(
643
+ originalOptions: GeometryOptions,
644
+ offsetOptions: GeometryOptions,
645
+ offset: number,
646
+ ): string {
647
+ const paperWidth =
648
+ originalOptions.canvasWidth || originalOptions.width * 2 || 2000;
649
+ const paperHeight =
650
+ originalOptions.canvasHeight || originalOptions.height * 2 || 2000;
651
+ ensurePaper(paperWidth, paperHeight);
652
+ paper.project.activeLayer.removeChildren();
653
+
654
+ // 1. Generate Original Shape
655
+ const pOriginal = getPerimeterShape(originalOptions);
656
+ const shapeOriginal = applySurfaceFeatures(
657
+ pOriginal,
658
+ originalOptions.features,
659
+ originalOptions,
660
+ );
661
+
662
+ // 2. Generate Offset Shape
663
+ const pOffset = getPerimeterShape(offsetOptions);
664
+ const shapeOffset = applySurfaceFeatures(
665
+ pOffset,
666
+ offsetOptions.features,
667
+ offsetOptions,
668
+ );
669
+
670
+ // 3. Calculate Difference
671
+ let bleedZone: paper.PathItem;
672
+ if (offset > 0) {
673
+ bleedZone = shapeOffset.subtract(shapeOriginal);
674
+ } else {
675
+ bleedZone = shapeOriginal.subtract(shapeOffset);
676
+ }
677
+
678
+ const pathData = bleedZone.pathData;
679
+
680
+ shapeOriginal.remove();
681
+ shapeOffset.remove();
682
+ bleedZone.remove();
683
+
684
+ return pathData;
685
+ }
686
+
687
+ /**
688
+ * Finds the lowest point (Max Y) on the Dieline geometry (Base Shape ONLY).
689
+ */
690
+ export function getLowestPointOnDieline(
691
+ options: GeometryOptions,
692
+ ): { x: number; y: number } {
693
+ ensurePaper(options.width * 2, options.height * 2);
694
+ paper.project.activeLayer.removeChildren();
695
+
696
+ const shape = createBaseShape(options);
697
+ const bounds = shape.bounds;
698
+
699
+ const result = {
700
+ x: bounds.center.x,
701
+ y: bounds.bottom,
702
+ };
703
+ shape.remove();
704
+
705
+ return result;
706
+ }
707
+
708
+ /**
709
+ * Finds the nearest point on the Dieline geometry (Base Shape ONLY) for a given target point.
710
+ * Used for constraining feature movement.
711
+ */
712
+ export function getNearestPointOnDieline(
713
+ point: { x: number; y: number },
714
+ options: GeometryOptions,
715
+ ): { x: number; y: number; normal?: { x: number; y: number } } {
716
+ ensurePaper(options.width * 2, options.height * 2);
717
+ paper.project.activeLayer.removeChildren();
718
+
719
+ // We constrain to the BASE shape, not including other features,
720
+ // because usually you want to snap to the main edge.
721
+ const shape = createBaseShape(options);
722
+
723
+ const p = new paper.Point(point.x, point.y);
724
+ const location = shape.getNearestLocation(p);
725
+
726
+ const result = {
727
+ x: location.point.x,
728
+ y: location.point.y,
729
+ normal: location.normal ? { x: location.normal.x, y: location.normal.y } : undefined
730
+ };
731
+ shape.remove();
732
+
733
+ return result;
734
+ }
735
+
736
+ export function getPathBounds(pathData: string): {
737
+ x: number;
738
+ y: number;
739
+ width: number;
740
+ height: number;
741
+ } {
742
+ const path = new paper.Path();
743
+ path.pathData = pathData;
744
+ const bounds = path.bounds;
745
+ path.remove();
746
+ return {
747
+ x: bounds.x,
748
+ y: bounds.y,
749
+ width: bounds.width,
750
+ height: bounds.height,
751
+ };
752
+ }