-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpattern-generator.js
More file actions
1313 lines (1148 loc) · 52.6 KB
/
Copy pathpattern-generator.js
File metadata and controls
1313 lines (1148 loc) · 52.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class PatternGenerator {
constructor() {
this.segments = [];
this.usedSpace = [];
this.canvas = null; // Will be set when needed for text detection
}
/**
* Generate pattern using a rasterized mask canvas
* @param {HTMLCanvasElement} maskCanvas - Canvas with black shapes on white background
* @param {Object} options - Configuration options
* @returns {Object} - Pattern data with paths and circles
*/
generateWithMask(maskCanvas, options = {}) {
const {
density = 20,
lineLengthMin = 20,
lineLengthMax = 150,
lineThickness = 2,
circleRadius = 4,
style = 'organic',
lineColor = '#00ff00',
patternScale = 1
} = options;
this.segments = [];
this.usedSpace = [];
const ctx = maskCanvas.getContext('2d');
const canvasWidth = maskCanvas.width;
const canvasHeight = maskCanvas.height;
// Scale the bounds for pattern generation
const scaledWidth = canvasWidth / patternScale;
const scaledHeight = canvasHeight / patternScale;
// Scale all dimensions: thickness, radius, and line lengths
const scaledLineThickness = lineThickness * patternScale;
const scaledCircleRadius = circleRadius * patternScale;
const scaledLineLengthMin = lineLengthMin * patternScale;
const scaledLineLengthMax = lineLengthMax * patternScale;
// Density scales inversely to maintain same number of lines per unit area
const scaledDensity = density / patternScale;
const bounds = {
x: 0,
y: 0,
width: scaledWidth,
height: scaledHeight
};
// Generate segments with variable length (between min and max)
// Use average length for generation, but allow variation
const avgLength = (scaledLineLengthMin + scaledLineLengthMax) / 2;
const gridSize = scaledDensity;
const minSpacing = Math.max(gridSize * 0.3, scaledLineThickness + scaledCircleRadius);
// Create potential segments with variable lengths
const potentialSegments = this.createPotentialSegments(bounds, gridSize, style, avgLength, scaledLineLengthMin, scaledLineLengthMax);
// Filter segments to only those inside the mask (simplified check)
const validSegments = potentialSegments.filter(segment => {
// Scale segment coordinates to original canvas space for mask checking
const scaledStart = {
x: segment.start.x * patternScale,
y: segment.start.y * patternScale
};
const scaledEnd = {
x: segment.end.x * patternScale,
y: segment.end.y * patternScale
};
// Check endpoints only (faster)
const startInside = this.isPointInMask(scaledStart, maskCanvas, ctx);
const endInside = this.isPointInMask(scaledEnd, maskCanvas, ctx);
if (!startInside || !endInside) {
return false;
}
// For curved segments, check midpoint
if (segment.points && segment.points.length > 2) {
const midPoint = segment.points[Math.floor(segment.points.length / 2)];
const scaledMid = {
x: midPoint.x * patternScale,
y: midPoint.y * patternScale
};
return this.isPointInMask(scaledMid, maskCanvas, ctx);
}
// For straight segments, check midpoint only
const midPoint = {
x: (scaledStart.x + scaledEnd.x) / 2,
y: (scaledStart.y + scaledEnd.y) / 2
};
return this.isPointInMask(midPoint, maskCanvas, ctx);
});
// Sort by length (longer first) - this ensures longest lines are placed first
validSegments.sort((a, b) => b.length - a.length);
// Place segments starting from longest
const placedSegments = [];
for (const segment of validSegments) {
// Only place if length is within range
if (segment.length >= scaledLineLengthMin && segment.length <= scaledLineLengthMax) {
if (this.canPlaceSegment(segment, placedSegments, minSpacing, scaledLineThickness, scaledCircleRadius)) {
placedSegments.push(segment);
}
}
}
// Find intersections and create forks
const forks = this.findIntersections(placedSegments);
// Extract endpoints for circles (before shortening)
const endpoints = this.getEndpoints(placedSegments, forks);
// Shorten segments to leave space for circles at endpoints (unless at forks)
const shortenedSegments = this.shortenSegmentsForCircles(placedSegments, forks, scaledCircleRadius);
// Scale all coordinates back to original canvas space
const scaledSegments = shortenedSegments.map(segment => {
if (segment.points && segment.points.length > 2) {
// Curved segment
return {
...segment,
start: {
x: segment.start.x * patternScale,
y: segment.start.y * patternScale
},
end: {
x: segment.end.x * patternScale,
y: segment.end.y * patternScale
},
points: segment.points.map(p => ({
x: p.x * patternScale,
y: p.y * patternScale
}))
};
} else {
// Straight segment
return {
...segment,
start: {
x: segment.start.x * patternScale,
y: segment.start.y * patternScale
},
end: {
x: segment.end.x * patternScale,
y: segment.end.y * patternScale
}
};
}
});
const scaledCircles = endpoints.map(circle => ({
...circle,
x: circle.x * patternScale,
y: circle.y * patternScale
}));
const scaledForks = forks.map(fork => ({
...fork,
x: fork.x * patternScale,
y: fork.y * patternScale
}));
return {
segments: scaledSegments,
circles: scaledCircles,
forks: scaledForks,
lineThickness: scaledLineThickness,
circleRadius: scaledCircleRadius,
lineColor,
gradientType: options.gradientType || 'none',
gradientColor: options.gradientColor || lineColor,
gradientStartPoint: options.gradientStartPoint,
gradientEndPoint: options.gradientEndPoint
};
}
/**
* Check if point is inside the mask (black pixel)
*/
isPointInMask(point, maskCanvas, ctx) {
const x = Math.floor(point.x);
const y = Math.floor(point.y);
if (x < 0 || y < 0 || x >= maskCanvas.width || y >= maskCanvas.height) {
return false;
}
try {
const imageData = ctx.getImageData(x, y, 1, 1);
// Black pixel = inside shape (RGB all 0 or very low)
return imageData.data[0] < 128; // Check if pixel is dark (black or near-black)
} catch (e) {
return false;
}
}
/**
* Generate pattern inside a shape or multiple shapes
* @param {SVGPathElement|Array|Array<Array>} shape - SVG path element, array of points, or array of shape arrays
* @param {Object} options - Configuration options
* @returns {Object} - Pattern data with paths and circles
*/
generate(shape, options = {}) {
// Handle multiple shapes (array of arrays)
if (Array.isArray(shape) && shape.length > 0 && Array.isArray(shape[0]) && typeof shape[0][0] === 'object' && shape[0][0].x !== undefined) {
// Multiple shapes - combine them
return this.generateForMultipleShapes(shape, options);
}
const {
density = 20,
lineLength = 80,
lineThickness = 2,
circleRadius = 4,
style = 'organic',
lineColor = '#00ff00'
} = options;
this.segments = [];
this.usedSpace = [];
// Get shape bounds and create spatial grid
const bounds = this.getShapeBounds(shape);
// Density controls spacing between potential segment start points
const gridSize = density;
// Create a set of potential line segments
const potentialSegments = this.createPotentialSegments(bounds, gridSize, style, lineLength);
// Filter and prioritize segments
// Handle text objects specially
let validSegments;
if (shape && typeof shape === 'object' && shape.type === 'text' && shape.textData) {
// Use text element for accurate detection
validSegments = potentialSegments.filter(segment => {
const midPoint = {
x: (segment.start.x + segment.end.x) / 2,
y: (segment.start.y + segment.end.y) / 2
};
return this.isPointInText(midPoint, shape.textData) &&
this.isPointInText(segment.start, shape.textData) &&
this.isPointInText(segment.end, shape.textData);
});
} else {
const shapeToCheck = (shape && typeof shape === 'object' && shape.bounds) ? shape.bounds : shape;
validSegments = this.filterSegments(potentialSegments, shapeToCheck);
}
// Sort by length (longer first)
validSegments.sort((a, b) => b.length - a.length);
// Place segments starting from longest
const placedSegments = [];
// Account for line thickness and circle radius in spacing
const minSpacing = Math.max(gridSize * 0.3, lineThickness + circleRadius);
for (const segment of validSegments) {
if (this.canPlaceSegment(segment, placedSegments, minSpacing, lineThickness, circleRadius)) {
placedSegments.push(segment);
}
}
// Find intersections and create forks
const forks = this.findIntersections(placedSegments);
// Extract endpoints for circles (before shortening, so circles are at original positions)
const endpoints = this.getEndpoints(placedSegments, forks);
// Shorten segments to leave space for circles at endpoints (unless at forks)
const shortenedSegments = this.shortenSegmentsForCircles(placedSegments, forks, circleRadius);
return {
segments: shortenedSegments,
circles: endpoints,
forks: forks,
lineThickness,
circleRadius,
lineColor,
gradientType: options.gradientType || 'none',
gradientColor: options.gradientColor || lineColor
};
}
/**
* Generate pattern for multiple shapes combined
*/
generateForMultipleShapes(shapes, options = {}) {
const {
density = 20,
lineLength = 80,
lineThickness = 2,
circleRadius = 4,
style = 'organic',
lineColor = '#00ff00'
} = options;
this.segments = [];
this.usedSpace = [];
// Get combined bounds of all shapes
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
shapes.forEach(shape => {
if (Array.isArray(shape) && shape.length > 0) {
shape.forEach(point => {
minX = Math.min(minX, point.x);
minY = Math.min(minY, point.y);
maxX = Math.max(maxX, point.x);
maxY = Math.max(maxY, point.y);
});
}
});
const bounds = {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
};
const gridSize = density;
const minSpacing = Math.max(gridSize * 0.3, lineThickness + circleRadius);
// Create potential segments
const potentialSegments = this.createPotentialSegments(bounds, gridSize, style, lineLength);
// Filter segments to only those inside any of the shapes
const validSegments = potentialSegments.filter(segment => {
// Check if segment is inside any shape
return shapes.some(shape => {
// Handle text objects specially
if (shape && typeof shape === 'object' && shape.type === 'text' && shape.textData) {
// For text, check multiple points along the segment
const pointsToCheck = [];
// Add start, end, and several points along the segment
pointsToCheck.push(segment.start);
pointsToCheck.push(segment.end);
// Add midpoints for curved segments
if (segment.points && segment.points.length > 2) {
for (let i = 1; i < segment.points.length - 1; i++) {
pointsToCheck.push(segment.points[i]);
}
} else {
const midPoint = {
x: (segment.start.x + segment.end.x) / 2,
y: (segment.start.y + segment.end.y) / 2
};
pointsToCheck.push(midPoint);
}
// Check if any points are inside text (lenient - include if any part touches text)
const pointsInside = pointsToCheck.filter(p => this.isPointInText(p, shape.textData));
// Include segment if any point is inside (more lenient for text)
return pointsInside.length > 0;
}
const midPoint = {
x: (segment.start.x + segment.end.x) / 2,
y: (segment.start.y + segment.end.y) / 2
};
const shapeToCheck = (shape && typeof shape === 'object' && shape.bounds) ? shape.bounds : shape;
return this.isPointInShape(midPoint, shapeToCheck) &&
this.isPointInShape(segment.start, shapeToCheck) &&
this.isPointInShape(segment.end, shapeToCheck);
});
});
// Sort by length (longer first)
validSegments.sort((a, b) => b.length - a.length);
// Place segments starting from longest
const placedSegments = [];
for (const segment of validSegments) {
if (this.canPlaceSegment(segment, placedSegments, minSpacing, lineThickness, circleRadius)) {
placedSegments.push(segment);
}
}
// Find intersections and create forks
const forks = this.findIntersections(placedSegments);
// Extract endpoints for circles (before shortening)
const endpoints = this.getEndpoints(placedSegments, forks);
// Shorten segments to leave space for circles at endpoints (unless at forks)
const shortenedSegments = this.shortenSegmentsForCircles(placedSegments, forks, circleRadius);
return {
segments: shortenedSegments,
circles: endpoints,
forks: forks,
lineThickness,
circleRadius,
lineColor,
gradientType: options.gradientType || 'none',
gradientColor: options.gradientColor || lineColor
};
}
/**
* Get bounding box of shape
*/
getShapeBounds(shape) {
if (shape instanceof SVGPathElement) {
const bbox = shape.getBBox();
return {
x: bbox.x,
y: bbox.y,
width: bbox.width,
height: bbox.height
};
} else if (Array.isArray(shape) && shape.length > 0) {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
shape.forEach(point => {
minX = Math.min(minX, point.x);
minY = Math.min(minY, point.y);
maxX = Math.max(maxX, point.x);
maxY = Math.max(maxY, point.y);
});
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
};
}
return { x: 0, y: 0, width: 800, height: 600 };
}
/**
* Create potential line segments
* @param {Object} bounds - Bounding box
* @param {number} gridSize - Spacing between potential segment start points (density)
* @param {string} style - Pattern style (grid or organic)
* @param {number} lineLength - Average length for segments
*/
createPotentialSegments(bounds, gridSize, style, lineLength = 80, minLength = null, maxLength = null) {
const segments = [];
const angles = [0, 45, 90, 135]; // 45-degree angles
// Use min/max if provided, otherwise use lineLength with variation
const useRange = minLength !== null && maxLength !== null;
const getLength = () => {
if (useRange) {
return minLength + Math.random() * (maxLength - minLength);
}
return lineLength * (0.7 + Math.random() * 0.6); // 70% to 130% of lineLength
};
if (style === 'grid') {
// Grid-based pattern - density controls grid spacing
for (let x = bounds.x; x < bounds.x + bounds.width; x += gridSize) {
for (let y = bounds.y; y < bounds.y + bounds.height; y += gridSize) {
const angle = angles[Math.floor(Math.random() * angles.length)];
const length = getLength();
segments.push(this.createSegment(x, y, angle, length));
}
}
} else {
// Organic pattern - density controls how many segments to generate
const numSegments = Math.floor((bounds.width * bounds.height) / (gridSize * gridSize * 0.5));
for (let i = 0; i < numSegments; i++) {
const startX = bounds.x + Math.random() * bounds.width;
const startY = bounds.y + Math.random() * bounds.height;
const angle = angles[Math.floor(Math.random() * angles.length)];
const length = getLength();
const numCurves = Math.floor(Math.random() * 3); // 0-2 curves
segments.push(this.createCurvedSegment(startX, startY, angle, length, numCurves));
}
}
return segments;
}
/**
* Create a straight line segment
*/
createSegment(x, y, angle, length) {
const rad = (angle * Math.PI) / 180;
const endX = x + Math.cos(rad) * length;
const endY = y + Math.sin(rad) * length;
return {
start: { x, y },
end: { x: endX, y: endY },
angle,
length,
points: [{ x, y }, { x: endX, y: endY }]
};
}
/**
* Create a curved segment with 45-degree turns
*/
createCurvedSegment(startX, startY, startAngle, totalLength, numCurves) {
const points = [{ x: startX, y: startY }];
let currentX = startX;
let currentY = startY;
let currentAngle = startAngle;
const segmentLength = totalLength / (numCurves + 1);
for (let i = 0; i <= numCurves; i++) {
const rad = (currentAngle * Math.PI) / 180;
const length = segmentLength * (0.8 + Math.random() * 0.4);
currentX += Math.cos(rad) * length;
currentY += Math.sin(rad) * length;
points.push({ x: currentX, y: currentY });
if (i < numCurves) {
// Turn 45 degrees (random direction)
currentAngle += (Math.random() < 0.5 ? -45 : 45);
currentAngle = ((currentAngle % 360) + 360) % 360;
}
}
return {
start: points[0],
end: points[points.length - 1],
angle: startAngle,
length: totalLength,
points: points
};
}
/**
* Filter segments to only those inside the shape
*/
filterSegments(segments, shape) {
return segments.filter(segment => {
// Check multiple points along the segment to ensure it's inside
const startIn = this.isPointInShape(segment.start, shape);
const endIn = this.isPointInShape(segment.end, shape);
const midPoint = {
x: (segment.start.x + segment.end.x) / 2,
y: (segment.start.y + segment.end.y) / 2
};
const midIn = this.isPointInShape(midPoint, shape);
// For curved segments, check intermediate points too
if (segment.points.length > 2) {
let allPointsIn = true;
for (let i = 1; i < segment.points.length - 1; i++) {
if (!this.isPointInShape(segment.points[i], shape)) {
allPointsIn = false;
break;
}
}
return allPointsIn && startIn && endIn;
}
// For straight segments, at least start and end should be in
return startIn && endIn;
});
}
/**
* Check if point is inside shape
*/
isPointInShape(point, shape) {
if (shape instanceof SVGPathElement) {
// Use SVG path check
const svg = shape.ownerSVGElement;
if (!svg) return false;
const pointElement = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
pointElement.setAttribute('cx', point.x);
pointElement.setAttribute('cy', point.y);
pointElement.setAttribute('r', 1);
svg.appendChild(pointElement);
const isInside = shape.isPointInFill ? shape.isPointInFill(new DOMPoint(point.x, point.y)) : false;
svg.removeChild(pointElement);
return isInside;
} else if (Array.isArray(shape)) {
// Point-in-polygon test
return this.pointInPolygon(point, shape);
}
return false;
}
/**
* Check if point is inside SVG text element (with transform applied)
* Uses canvas-based pixel detection for accuracy
*/
isPointInText(point, textData) {
if (!textData) return false;
// Try canvas method first (most accurate)
if (textData.canvas && textData.ctx) {
try {
// Use canvas pixel data for accurate detection
const x = Math.floor(point.x);
const y = Math.floor(point.y);
// Check bounds
if (x < 0 || y < 0 || x >= textData.canvas.width || y >= textData.canvas.height) {
return false;
}
// Get pixel data at this point
const imageData = textData.ctx.getImageData(x, y, 1, 1);
// If alpha channel > 0, point is inside text
if (imageData.data[3] > 0) {
return true;
}
// Also check nearby pixels for better accuracy (small radius)
const checkRadius = 1;
for (let dx = -checkRadius; dx <= checkRadius; dx++) {
for (let dy = -checkRadius; dy <= checkRadius; dy++) {
if (dx === 0 && dy === 0) continue;
const checkX = x + dx;
const checkY = y + dy;
if (checkX >= 0 && checkY >= 0 && checkX < textData.canvas.width && checkY < textData.canvas.height) {
try {
const nearbyData = textData.ctx.getImageData(checkX, checkY, 1, 1);
if (nearbyData.data[3] > 0) {
return true;
}
} catch (e) {
// Continue
}
}
}
}
} catch (e) {
// Fall through to SVG method
}
}
// Fallback to SVG method
return this.isPointInTextSVG(point, textData);
}
/**
* Fallback SVG-based method for checking if point is in text
*/
isPointInTextSVG(point, textData) {
if (!textData || !textData.text || !textData.text.isPointInFill) return false;
try {
const centerX = textData.centerX;
const centerY = textData.centerY;
const scaleX = textData.scaleX || 1;
const scaleY = textData.scaleY || 1;
// Transform point to local coordinates
// The transform is: translate(x,y) scale(sx,sy) translate(-x,-y)
// To invert: translate(x,y) scale(1/sx,1/sy) translate(-x,-y)
const localX = centerX + (point.x - centerX) / scaleX;
const localY = centerY + (point.y - centerY) / scaleY;
const domPoint = new DOMPoint(localX, localY);
return textData.text.isPointInFill && textData.text.isPointInFill(domPoint);
} catch (e2) {
return false;
}
}
/**
* Point-in-polygon test using ray casting algorithm
*/
pointInPolygon(point, polygon) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const xi = polygon[i].x, yi = polygon[i].y;
const xj = polygon[j].x, yj = polygon[j].y;
const intersect = ((yi > point.y) !== (yj > point.y)) &&
(point.x < (xj - xi) * (point.y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}
/**
* Check if segment can be placed without crossing existing segments
*/
canPlaceSegment(segment, placedSegments, minDistance, lineThickness = 2, circleRadius = 4) {
const endpointThreshold = 3; // Pixels - endpoints closer than this are considered the same
// Account for line thickness in distance calculations
const effectiveMinDistance = minDistance + lineThickness / 2;
// Minimum distance between circle centers to prevent overlap
// Two circles with radius r need at least 2r distance between centers, plus padding
const circleClearance = 2 * circleRadius + lineThickness + 3; // Extra 3px padding between circles
for (const placed of placedSegments) {
// Check if segments share endpoints (this is allowed for forks)
const sharesStart = this.pointsClose(segment.start, placed.start, endpointThreshold) ||
this.pointsClose(segment.start, placed.end, endpointThreshold);
const sharesEnd = this.pointsClose(segment.end, placed.start, endpointThreshold) ||
this.pointsClose(segment.end, placed.end, endpointThreshold);
const sharesPlacedStart = this.pointsClose(placed.start, segment.start, endpointThreshold) ||
this.pointsClose(placed.start, segment.end, endpointThreshold);
const sharesPlacedEnd = this.pointsClose(placed.end, segment.start, endpointThreshold) ||
this.pointsClose(placed.end, segment.end, endpointThreshold);
const sharesEndpoints = sharesStart || sharesEnd || sharesPlacedStart || sharesPlacedEnd;
// Even if segments share endpoints, we still need to check if they're too close along their paths
// But we'll use a more lenient threshold for endpoint sharing cases
// Check if new segment endpoints are too close to placed segment endpoints (that will have circles)
// This prevents circles at endpoints from touching each other
// We need to check this even if endpoints are "close" but not exactly shared
const distToPlacedStart = this.pointDistance(segment.start, placed.start);
const distToPlacedEnd = this.pointDistance(segment.start, placed.end);
const distToPlacedStart2 = this.pointDistance(segment.end, placed.start);
const distToPlacedEnd2 = this.pointDistance(segment.end, placed.end);
// Check if any endpoint of the new segment is too close to endpoints of placed segments
// Only allow if endpoints are exactly shared (forks) - otherwise enforce circle clearance
const startSharesStart = this.pointsClose(segment.start, placed.start, endpointThreshold);
const startSharesEnd = this.pointsClose(segment.start, placed.end, endpointThreshold);
const endSharesStart = this.pointsClose(segment.end, placed.start, endpointThreshold);
const endSharesEnd = this.pointsClose(segment.end, placed.end, endpointThreshold);
// If endpoints are not exactly shared, they must maintain circle clearance distance
if (!startSharesStart && distToPlacedStart < circleClearance) return false;
if (!startSharesEnd && distToPlacedEnd < circleClearance) return false;
if (!endSharesStart && distToPlacedStart2 < circleClearance) return false;
if (!endSharesEnd && distToPlacedEnd2 < circleClearance) return false;
// Check if placed segment endpoints are too close to new segment's path
// Skip if the endpoint is shared (fork)
if (!sharesPlacedStart && !sharesPlacedEnd) {
const distFromPlacedStartToSeg = this.pointToSegmentDistance(placed.start, segment);
const distFromPlacedEndToSeg = this.pointToSegmentDistance(placed.end, segment);
if (distFromPlacedStartToSeg < circleClearance || distFromPlacedEndToSeg < circleClearance) {
return false;
}
}
// Check if new segment endpoints are too close to placed segment's path
// Skip if the endpoint is shared (fork)
if (!sharesStart && !sharesEnd) {
const distFromNewStartToPlaced = this.pointToSegmentDistance(segment.start, placed);
const distFromNewEndToPlaced = this.pointToSegmentDistance(segment.end, placed);
if (distFromNewStartToPlaced < circleClearance || distFromNewEndToPlaced < circleClearance) {
return false;
}
}
// Check if segments cross each other (not at endpoints)
const intersection = this.findSegmentIntersection(segment, placed);
if (intersection) {
// Check if intersection is at an endpoint (allowed) or in the middle (not allowed)
const isAtEndpoint = this.pointsClose(intersection, segment.start, endpointThreshold) ||
this.pointsClose(intersection, segment.end, endpointThreshold) ||
this.pointsClose(intersection, placed.start, endpointThreshold) ||
this.pointsClose(intersection, placed.end, endpointThreshold);
if (!isAtEndpoint) {
// Segments cross in the middle - not allowed
return false;
}
}
// Always check if segments are too close along their paths (accounting for line thickness)
// This check runs even if endpoints are shared, to prevent parallel segments from overlapping
if (this.segmentsTooClose(segment, placed, effectiveMinDistance)) {
return false;
}
}
return true;
}
/**
* Calculate distance from a point to a line segment
*/
pointToSegmentDistance(point, segment) {
let minDist = Infinity;
// Check distance to each segment of the path
for (let i = 0; i < segment.points.length - 1; i++) {
const p1 = segment.points[i];
const p2 = segment.points[i + 1];
// Vector from p1 to p2
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const segLengthSq = dx * dx + dy * dy;
if (segLengthSq < 0.001) {
// Degenerate segment, just use point distance
minDist = Math.min(minDist, this.pointDistance(point, p1));
continue;
}
// Project point onto line segment
const t = Math.max(0, Math.min(1, ((point.x - p1.x) * dx + (point.y - p1.y) * dy) / segLengthSq));
const projX = p1.x + t * dx;
const projY = p1.y + t * dy;
const projPoint = { x: projX, y: projY };
const dist = this.pointDistance(point, projPoint);
minDist = Math.min(minDist, dist);
}
return minDist;
}
/**
* Check if two points are close to each other
*/
pointsClose(p1, p2, threshold) {
return this.pointDistance(p1, p2) < threshold;
}
/**
* Check if two segments are too close (accounting for line thickness)
* Checks minimum distance along entire segment paths
*/
segmentsTooClose(seg1, seg2, minDistance) {
// Check minimum distance between all points on both segments
let minDist = Infinity;
// Sample points along seg1 and check distance to seg2
for (let i = 0; i < seg1.points.length; i++) {
const dist = this.pointToSegmentDistance(seg1.points[i], seg2);
minDist = Math.min(minDist, dist);
}
// Sample points along seg2 and check distance to seg1
for (let i = 0; i < seg2.points.length; i++) {
const dist = this.pointToSegmentDistance(seg2.points[i], seg1);
minDist = Math.min(minDist, dist);
}
// Also check distances between all segment sub-paths
for (let i = 0; i < seg1.points.length - 1; i++) {
for (let j = 0; j < seg2.points.length - 1; j++) {
const p1 = seg1.points[i];
const p2 = seg1.points[i + 1];
const p3 = seg2.points[j];
const p4 = seg2.points[j + 1];
// Check distance between these two line segments
const segDist = this.segmentToSegmentDistance(p1, p2, p3, p4);
minDist = Math.min(minDist, segDist);
}
}
return minDist < minDistance;
}
/**
* Calculate minimum distance between two line segments
*/
segmentToSegmentDistance(p1, p2, p3, p4) {
// Check if segments intersect
const intersection = this.lineIntersection(p1, p2, p3, p4);
if (intersection) {
return 0; // They intersect, distance is 0
}
// Check distances from endpoints of first segment to second segment
const d1 = this.pointToLineSegmentDistance(p1, p3, p4);
const d2 = this.pointToLineSegmentDistance(p2, p3, p4);
// Check distances from endpoints of second segment to first segment
const d3 = this.pointToLineSegmentDistance(p3, p1, p2);
const d4 = this.pointToLineSegmentDistance(p4, p1, p2);
return Math.min(d1, d2, d3, d4);
}
/**
* Calculate distance from a point to a line segment (single segment)
*/
pointToLineSegmentDistance(point, segStart, segEnd) {
const dx = segEnd.x - segStart.x;
const dy = segEnd.y - segStart.y;
const segLengthSq = dx * dx + dy * dy;
if (segLengthSq < 0.001) {
// Degenerate segment, just use point distance
return this.pointDistance(point, segStart);
}
// Project point onto line segment
const t = Math.max(0, Math.min(1, ((point.x - segStart.x) * dx + (point.y - segStart.y) * dy) / segLengthSq));
const projX = segStart.x + t * dx;
const projY = segStart.y + t * dy;
const projPoint = { x: projX, y: projY };
return this.pointDistance(point, projPoint);
}
/**
* Calculate distance between two points
*/
pointDistance(p1, p2) {
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
return Math.sqrt(dx * dx + dy * dy);
}
/**
* Find forks where segments meet at endpoints (no crossings allowed)
*/
findIntersections(segments) {
const forks = [];
const forkPoints = new Map(); // point -> array of segment indices
const endpointThreshold = 3; // Same threshold as in canPlaceSegment
// Find all endpoint connections
for (let i = 0; i < segments.length; i++) {
const seg1 = segments[i];
// Check start point
const startKey = this.getPointKey(seg1.start, endpointThreshold);
if (!forkPoints.has(startKey)) {
forkPoints.set(startKey, []);
}
forkPoints.get(startKey).push(i);
// Check end point
const endKey = this.getPointKey(seg1.end, endpointThreshold);
if (!forkPoints.has(endKey)) {
forkPoints.set(endKey, []);
}
forkPoints.get(endKey).push(i);
}
// Create forks where multiple segments meet at the same point
forkPoints.forEach((segmentIndices, pointKey) => {
if (segmentIndices.length > 1) {
// Multiple segments meet at this point - it's a fork
// Use the actual average position of all endpoints at this location
const point = this.getAverageEndpointPosition(segments, segmentIndices, pointKey, endpointThreshold);
forks.push({
point: point,
segments: segmentIndices,
type: segmentIndices.length > 2 ? 'cross' : 't-junction'
});
}
});
return forks;
}
/**
* Get average position of endpoints that are grouped together
*/
getAverageEndpointPosition(segments, segmentIndices, pointKey, threshold) {
const basePoint = this.parsePointKey(pointKey);
let sumX = 0, sumY = 0, count = 0;
segmentIndices.forEach(segIdx => {
const seg = segments[segIdx];
if (this.pointsClose(seg.start, basePoint, threshold * 2)) {
sumX += seg.start.x;
sumY += seg.start.y;
count++;
}
if (this.pointsClose(seg.end, basePoint, threshold * 2)) {
sumX += seg.end.x;
sumY += seg.end.y;
count++;
}
});
return count > 0 ? { x: sumX / count, y: sumY / count } : basePoint;
}
/**
* Get a string key for a point (for comparison with threshold)
*/
getPointKey(point, threshold = 3) {
// Round to nearest threshold to group nearby points
const roundedX = Math.round(point.x / threshold) * threshold;
const roundedY = Math.round(point.y / threshold) * threshold;
return `${roundedX},${roundedY}`;
}
/**
* Parse a point key back to coordinates
*/
parsePointKey(key) {
const [x, y] = key.split(',').map(Number);
return { x, y };
}
/**
* Find intersection point between two segments
*/
findSegmentIntersection(seg1, seg2) {
// Check all points in curved segments
for (let i = 0; i < seg1.points.length - 1; i++) {
for (let j = 0; j < seg2.points.length - 1; j++) {
const p1 = seg1.points[i];
const p2 = seg1.points[i + 1];
const p3 = seg2.points[j];
const p4 = seg2.points[j + 1];
const intersection = this.lineIntersection(p1, p2, p3, p4);
if (intersection && this.pointOnSegment(intersection, p1, p2) &&
this.pointOnSegment(intersection, p3, p4)) {
return intersection;