@maplat/tin 0.9.4 → 0.11.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.
package/src/kinks.ts ADDED
@@ -0,0 +1,1035 @@
1
+ import type { Position, Feature, Point } from "geojson";
2
+ import { point } from "@turf/helpers";
3
+ import type { IntersectionPoint } from "./types/kinks.ts";
4
+
5
+ /**
6
+ * 線分の交差点を検出するメインの関数
7
+ *
8
+ * @param coords - 線分群の座標配列。各線分は始点と終点の座標で表現
9
+ * @returns 検出された交差点のFeature配列
10
+ */
11
+ export default function findIntersections(coords: Position[][]) {
12
+ const arcs = new ArcCollection(coords);
13
+ const xy = arcs.findSegmentIntersections();
14
+ return dedupIntersections(xy).reduce(
15
+ (prev: Record<string, IntersectionPoint> | Feature<Point>[], apoint: IntersectionPoint, index: number, array: IntersectionPoint[]) => {
16
+ if (Array.isArray(prev)) return prev;
17
+ if (!prev) prev = {};
18
+ prev[`${apoint.x}:${apoint.y}`] = apoint;
19
+ if (index != array.length - 1) return prev;
20
+ return Object.keys(prev).map(key => point([prev[key].x, prev[key].y]));
21
+ },
22
+ {} as Record<string, IntersectionPoint>
23
+ ) as Feature<Point>[];
24
+ }
25
+
26
+ /**
27
+ * 線分群を管理するクラス
28
+ * 効率的な交差判定のためのデータ構造と機能を提供
29
+ */
30
+ class ArcCollection {
31
+ /**
32
+ * 座標データの配列
33
+ * _xx, _yy: Float64Array形式で座標を保持
34
+ * _ii: 各線分の開始インデックス
35
+ * _nn: 各線分の頂点数
36
+ */
37
+ _xx?: Float64Array;
38
+ _yy?: Float64Array; // coordinates data
39
+ _ii?: Uint32Array;
40
+ _nn?: Uint32Array; // indexes, sizes
41
+ _zz: any;
42
+ _zlimit = 0; // simplification
43
+ _bb: any;
44
+ _allBounds: any; // bounding boxes
45
+ _arcIter: any;
46
+ _filteredArcIter: any; // path iterators
47
+ buf?: ArrayBuffer;
48
+
49
+ /**
50
+ * 線分群からArcCollectionを初期化
51
+ * @param coords - 線分群の座標配列
52
+ */
53
+ constructor(coords: Position[][]) {
54
+ this.initArcs(coords);
55
+ }
56
+
57
+ initArcs(arcs: Position[][]) {
58
+ const xx: number[] = [],
59
+ yy: number[] = [];
60
+ const nn = arcs.map(points => {
61
+ const n = points ? points.length : 0;
62
+ for (let i = 0; i < n; i++) {
63
+ xx.push(points[i][0]);
64
+ yy.push(points[i][1]);
65
+ }
66
+ return n;
67
+ });
68
+ this.initXYData(nn, xx, yy);
69
+ }
70
+
71
+ initXYData(nn: number[], xx: number[], yy: number[]) {
72
+ const size = nn.length;
73
+ this._xx = new Float64Array(xx);
74
+ this._yy = new Float64Array(yy);
75
+ this._nn = new Uint32Array(nn);
76
+ this._zz = null;
77
+ this._zlimit = 0;
78
+ this._filteredArcIter = null;
79
+
80
+ // generate array of starting idxs of each arc
81
+ this._ii = new Uint32Array(size);
82
+ let idx = 0;
83
+ for (let j = 0; j < size; j++) {
84
+ this._ii[j] = idx;
85
+ idx += nn[j];
86
+ }
87
+
88
+ if (idx != this._xx.length || this._xx.length != this._yy.length) {
89
+ error("ArcCollection#initXYData() Counting error");
90
+ }
91
+
92
+ this.initBounds();
93
+ // Pre-allocate some path iterators for repeated use.
94
+ this._arcIter = new ArcIter(this._xx, this._yy);
95
+ }
96
+
97
+ initBounds() {
98
+ const data = this.calcArcBounds_(this._xx!, this._yy!, this._nn!);
99
+ this._bb = data.bb;
100
+ this._allBounds = data.bounds;
101
+ }
102
+
103
+ /**
104
+ * データの境界を計算
105
+ * @returns バウンディングボックス情報
106
+ */
107
+ calcArcBounds_(xx: Float64Array, yy: Float64Array, nn: Uint32Array) {
108
+ const numArcs = nn.length,
109
+ bb = new Float64Array(numArcs * 4),
110
+ bounds = new Bounds();
111
+ let arcOffs = 0,
112
+ arcLen: number,
113
+ j: number,
114
+ b: number[];
115
+ for (let i = 0; i < numArcs; i++) {
116
+ arcLen = nn[i];
117
+ if (arcLen > 0) {
118
+ j = i * 4;
119
+ b = calcArcBounds(xx, yy, arcOffs, arcLen) as number[];
120
+ bb[j++] = b[0];
121
+ bb[j++] = b[1];
122
+ bb[j++] = b[2];
123
+ bb[j] = b[3];
124
+ arcOffs += arcLen;
125
+ bounds.mergeBounds(b);
126
+ }
127
+ }
128
+ return {
129
+ bb,
130
+ bounds
131
+ };
132
+ }
133
+
134
+ getBounds() {
135
+ return this._allBounds.clone();
136
+ }
137
+
138
+ // @cb function(i, j, xx, yy)
139
+ forEachSegment(cb: any) {
140
+ let count = 0;
141
+ for (let i = 0, n = this.size(); i < n; i++) {
142
+ count += this.forEachArcSegment(i, cb);
143
+ }
144
+ return count;
145
+ }
146
+
147
+ size() {
148
+ return (this._ii && this._ii.length) || 0;
149
+ }
150
+
151
+ // @cb function(i, j, xx, yy)
152
+ forEachArcSegment(arcId: any, cb: any): any {
153
+ const fw = arcId >= 0,
154
+ absId = fw ? arcId : ~arcId,
155
+ zlim = this.getRetainedInterval(),
156
+ n = this._nn![absId],
157
+ step = fw ? 1 : -1;
158
+ let v1 = fw ? this._ii![absId] : this._ii![absId] + n - 1,
159
+ v2 = v1,
160
+ count = 0;
161
+
162
+ for (let j = 1; j < n; j++) {
163
+ v2 += step;
164
+ if (zlim === 0 || this._zz![v2] >= zlim) {
165
+ cb(v1, v2, this._xx!, this._yy!);
166
+ v1 = v2;
167
+ count++;
168
+ }
169
+ }
170
+ return count;
171
+ }
172
+
173
+ getRetainedInterval() {
174
+ return this._zlimit;
175
+ }
176
+
177
+ // Give access to raw data arrays...
178
+ getVertexData() {
179
+ return {
180
+ xx: this._xx,
181
+ yy: this._yy,
182
+ zz: this._zz,
183
+ bb: this._bb,
184
+ nn: this._nn,
185
+ ii: this._ii
186
+ };
187
+ }
188
+
189
+ getUint32Array(count: number) {
190
+ const bytes = count * 4;
191
+ if (!this.buf || this.buf.byteLength < bytes) {
192
+ this.buf = new ArrayBuffer(bytes);
193
+ }
194
+ return new Uint32Array(this.buf, 0, count);
195
+ }
196
+
197
+ // Return average magnitudes of dx, dy (with simplification)
198
+ getAvgSegment2() {
199
+ let dx = 0,
200
+ dy = 0;
201
+ const count = this.forEachSegment(
202
+ (i: number, j: number, xx: number[], yy: number[]) => {
203
+ dx += Math.abs(xx[i] - xx[j]);
204
+ dy += Math.abs(yy[i] - yy[j]);
205
+ }
206
+ );
207
+ return [dx / count || 0, dy / count || 0];
208
+ }
209
+
210
+ /**
211
+ * 交差判定のためのストライプ数を計算
212
+ * 線分の平均長さに基づいて最適な分割数を決定
213
+ */
214
+ calcSegmentIntersectionStripeCount() {
215
+ const yrange = this.getBounds().height(),
216
+ segLen = this.getAvgSegment2()[1];
217
+ let count = 1;
218
+ if (segLen > 0 && yrange > 0) {
219
+ count = Math.ceil(yrange / segLen / 20);
220
+ }
221
+ return count || 1;
222
+ }
223
+
224
+ /**
225
+ * 線分の交差を検出
226
+ * ストライプ分割による効率的な判定を実装
227
+ *
228
+ * @returns 検出された交差点の配列
229
+ */
230
+ findSegmentIntersections() {
231
+ const bounds = this.getBounds(),
232
+ ymin = bounds.ymin,
233
+ yrange = bounds.ymax - ymin,
234
+ stripeCount = this.calcSegmentIntersectionStripeCount(),
235
+ stripeSizes = new Uint32Array(stripeCount),
236
+ stripeId =
237
+ stripeCount > 1
238
+ ? (y: number) => Math.floor(((stripeCount - 1) * (y - ymin)) / yrange)
239
+ : () => 0;
240
+ let i, j;
241
+
242
+ // Count segments in each stripe
243
+ this.forEachSegment(
244
+ (id1: number, id2: number, _xx: number[], yy: number[]) => {
245
+ let s1 = stripeId(yy[id1]);
246
+ const s2 = stripeId(yy[id2]);
247
+ while (true) {
248
+ stripeSizes[s1] = stripeSizes[s1] + 2;
249
+ if (s1 == s2) break;
250
+ s1 += s2 > s1 ? 1 : -1;
251
+ }
252
+ }
253
+ );
254
+
255
+ // Allocate arrays for segments in each stripe
256
+ const stripeData = this.getUint32Array(utilsSum(stripeSizes));
257
+ let offs = 0;
258
+ const stripes: any[] = [];
259
+ utilsForEach(stripeSizes, (stripeSize: number) => {
260
+ const start = offs;
261
+ offs += stripeSize;
262
+ stripes.push(stripeData.subarray(start, offs));
263
+ });
264
+ // Assign segment ids to each stripe
265
+ initializeArray(stripeSizes, 0);
266
+
267
+ this.forEachSegment(
268
+ (id1: number, id2: number, _xx: number[], yy: number[]) => {
269
+ let s1 = stripeId(yy[id1]);
270
+ const s2 = stripeId(yy[id2]);
271
+ let count, stripe;
272
+ while (true) {
273
+ count = stripeSizes[s1];
274
+ stripeSizes[s1] = count + 2;
275
+ stripe = stripes[s1];
276
+ stripe[count] = id1;
277
+ stripe[count + 1] = id2;
278
+ if (s1 == s2) break;
279
+ s1 += s2 > s1 ? 1 : -1;
280
+ }
281
+ }
282
+ );
283
+
284
+ // Detect intersections among segments in each stripe.
285
+ const raw = this.getVertexData(),
286
+ intersections = [];
287
+ let arr;
288
+ for (i = 0; i < stripeCount; i++) {
289
+ arr = intersectSegments(stripes[i], raw.xx, raw.yy);
290
+ for (j = 0; j < arr.length; j++) {
291
+ intersections.push(arr[j]);
292
+ }
293
+ }
294
+ return dedupIntersections(intersections);
295
+ }
296
+ }
297
+
298
+ function error(...args: any[]) {
299
+ const msg = args.join(" ");
300
+ throw new Error(msg);
301
+ }
302
+
303
+ function isArrayLike(obj: any) {
304
+ if (!obj) return false;
305
+ if (isArray(obj)) return true;
306
+ if (isString(obj)) return false;
307
+ if (obj.length === 0) return true;
308
+ return obj.length > 0;
309
+ }
310
+
311
+ function isString(obj: any) {
312
+ return obj != null && obj.toString === String.prototype.toString;
313
+ }
314
+
315
+ function isArray(obj: any) {
316
+ return Array.isArray(obj);
317
+ }
318
+
319
+ // Calc sum, skip falsy and NaN values
320
+ // Assumes: no other non-numeric objects in array
321
+ //
322
+ function utilsSum(arr: Uint32Array, info?: any) {
323
+ if (!isArrayLike(arr)) error("utils.sum() expects an array, received:", arr);
324
+ let tot = 0,
325
+ nan = 0,
326
+ val;
327
+ for (let i = 0, n = arr.length; i < n; i++) {
328
+ val = arr[i];
329
+ if (val) {
330
+ tot += val;
331
+ } else if (isNaN(val)) {
332
+ nan++;
333
+ }
334
+ }
335
+ if (info) {
336
+ info.nan = nan;
337
+ }
338
+ return tot;
339
+ }
340
+
341
+ // Support for iterating over array-like objects, like typed arrays
342
+ function utilsForEach(arr: any, func: any, ctx?: any) {
343
+ if (!isArrayLike(arr)) {
344
+ throw new Error(`#forEach() takes an array-like argument. ${arr}`);
345
+ }
346
+ for (let i = 0, n = arr.length; i < n; i++) {
347
+ func.call(ctx, arr[i], i);
348
+ }
349
+ }
350
+
351
+ function initializeArray(arr: any, init: any) {
352
+ for (let i = 0, len = arr.length; i < len; i++) {
353
+ arr[i] = init;
354
+ }
355
+ return arr;
356
+ }
357
+
358
+ // Find intersections among a group of line segments
359
+ //
360
+ // TODO: handle case where a segment starts and ends at the same point (i.e. duplicate coords);
361
+ //
362
+ // @ids: Array of indexes: [s0p0, s0p1, s1p0, s1p1, ...] where xx[sip0] <= xx[sip1]
363
+ // @xx, @yy: Arrays of x- and y-coordinates
364
+ //
365
+ function intersectSegments(ids: any, xx: any, yy: any) {
366
+ const lim = ids.length - 2,
367
+ intersections = [];
368
+ let s1p1,
369
+ s1p2,
370
+ s2p1,
371
+ s2p2,
372
+ s1p1x,
373
+ s1p2x,
374
+ s2p1x,
375
+ s2p2x,
376
+ s1p1y,
377
+ s1p2y,
378
+ s2p1y,
379
+ s2p2y,
380
+ hit,
381
+ seg1,
382
+ seg2,
383
+ i,
384
+ j;
385
+
386
+ // Sort segments by xmin, to allow efficient exclusion of segments with
387
+ // non-overlapping x extents.
388
+ sortSegmentIds(xx, ids); // sort by ascending xmin
389
+
390
+ i = 0;
391
+ while (i < lim) {
392
+ s1p1 = ids[i];
393
+ s1p2 = ids[i + 1];
394
+ s1p1x = xx[s1p1];
395
+ s1p2x = xx[s1p2];
396
+ s1p1y = yy[s1p1];
397
+ s1p2y = yy[s1p2];
398
+ // count++;
399
+
400
+ j = i;
401
+ while (j < lim) {
402
+ j += 2;
403
+ s2p1 = ids[j];
404
+ s2p1x = xx[s2p1];
405
+
406
+ if (s1p2x < s2p1x) break; // x extent of seg 2 is greater than seg 1: done with seg 1
407
+ //if (s1p2x <= s2p1x) break; // this misses point-segment intersections when s1 or s2 is vertical
408
+
409
+ s2p1y = yy[s2p1];
410
+ s2p2 = ids[j + 1];
411
+ s2p2x = xx[s2p2];
412
+ s2p2y = yy[s2p2];
413
+
414
+ // skip segments with non-overlapping y ranges
415
+ if (s1p1y >= s2p1y) {
416
+ if (s1p1y > s2p2y && s1p2y > s2p1y && s1p2y > s2p2y) continue;
417
+ } else {
418
+ if (s1p1y < s2p2y && s1p2y < s2p1y && s1p2y < s2p2y) continue;
419
+ }
420
+
421
+ // skip segments that are adjacent in a path (optimization)
422
+ // TODO: consider if this eliminates some cases that should
423
+ // be detected, e.g. spikes formed by unequal segments
424
+ if (s1p1 == s2p1 || s1p1 == s2p2 || s1p2 == s2p1 || s1p2 == s2p2) {
425
+ continue;
426
+ }
427
+
428
+ // test two candidate segments for intersection
429
+ hit = segmentIntersection(
430
+ s1p1x,
431
+ s1p1y,
432
+ s1p2x,
433
+ s1p2y,
434
+ s2p1x,
435
+ s2p1y,
436
+ s2p2x,
437
+ s2p2y
438
+ );
439
+ if (hit) {
440
+ seg1 = [s1p1, s1p2];
441
+ seg2 = [s2p1, s2p2];
442
+ intersections.push(formatIntersection(hit, seg1, seg2, xx, yy));
443
+ if (hit.length == 4) {
444
+ // two collinear segments may have two endpoint intersections
445
+ intersections.push(
446
+ formatIntersection(hit.slice(2), seg1, seg2, xx, yy)
447
+ );
448
+ }
449
+ }
450
+ }
451
+ i += 2;
452
+ }
453
+ return intersections;
454
+ }
455
+
456
+ /**
457
+ * 2つの2D線分間の交差を判定し、交差点を計算します
458
+ *
459
+ * @param ax, ay - 第1線分の始点座標
460
+ * @param bx, by - 第1線分の終点座標
461
+ * @param cx, cy - 第2線分の始点座標
462
+ * @param dx, dy - 第2線分の終点座標
463
+ *
464
+ * @returns 以下のいずれか:
465
+ * - null: 交差なし
466
+ * - [x, y]: 1点での交差
467
+ * - [x1, y1, x2, y2]: 線分が重なる場合の2点での交差
468
+ *
469
+ * 特殊ケースの扱い:
470
+ * 1. 両線分の端点で接触する場合 → 交差としない
471
+ * 2. T字型に接触する場合 → 交差として扱う
472
+ * 3. 線分が同一直線上で部分的に重なる場合 → 重なる部分の端点を交差点として扱う(1または2点)
473
+ * - 例: 線分ABとCDが重なる場合、重なり部分の両端点が交差点となる
474
+ * - [x1, y1, x2, y2] の形式で返される
475
+ */
476
+ function segmentIntersection(
477
+ ax: any,
478
+ ay: any,
479
+ bx: any,
480
+ by: any,
481
+ cx: any,
482
+ cy: any,
483
+ dx: any,
484
+ dy: any
485
+ ) {
486
+ const hit = segmentHit(ax, ay, bx, by, cx, cy, dx, dy);
487
+ let p = null;
488
+ if (hit) {
489
+ p = crossIntersection(ax, ay, bx, by, cx, cy, dx, dy);
490
+ if (!p) {
491
+ // collinear if p is null
492
+ p = collinearIntersection(ax, ay, bx, by, cx, cy, dx, dy);
493
+ } else if (endpointHit(ax, ay, bx, by, cx, cy, dx, dy)) {
494
+ p = null; // filter out segments that only intersect at an endpoint
495
+ }
496
+ }
497
+ return p;
498
+ }
499
+
500
+ // Source: Sedgewick, _Algorithms in C_
501
+ // (Tried various other functions that failed owing to floating point errors)
502
+ function segmentHit(
503
+ ax: any,
504
+ ay: any,
505
+ bx: any,
506
+ by: any,
507
+ cx: any,
508
+ cy: any,
509
+ dx: any,
510
+ dy: any
511
+ ) {
512
+ return (
513
+ orient2D(ax, ay, bx, by, cx, cy) * orient2D(ax, ay, bx, by, dx, dy) <= 0 &&
514
+ orient2D(cx, cy, dx, dy, ax, ay) * orient2D(cx, cy, dx, dy, bx, by) <= 0
515
+ );
516
+ }
517
+
518
+ // returns a positive value if the points a, b, and c are arranged in
519
+ // counterclockwise order, a negative value if the points are in clockwise
520
+ // order, and zero if the points are collinear.
521
+ // Source: Jonathan Shewchuk http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf
522
+ function orient2D(ax: any, ay: any, bx: any, by: any, cx: any, cy: any) {
523
+ return determinant2D(ax - cx, ay - cy, bx - cx, by - cy);
524
+ }
525
+
526
+ /**
527
+ * 2次元の行列式を計算
528
+ *
529
+ * @param a, b - 行列の第1行
530
+ * @param c, d - 行列の第2行
531
+ * @returns 行列式の値
532
+ */
533
+ function determinant2D(a: any, b: any, c: any, d: any) {
534
+ return a * d - b * c;
535
+ }
536
+
537
+ // Get intersection point if segments are non-collinear, else return null
538
+ // Assumes that segments have been intersect
539
+ function crossIntersection(
540
+ ax: any,
541
+ ay: any,
542
+ bx: any,
543
+ by: any,
544
+ cx: any,
545
+ cy: any,
546
+ dx: any,
547
+ dy: any
548
+ ) {
549
+ let p = lineIntersection(ax, ay, bx, by, cx, cy, dx, dy);
550
+ let nearest;
551
+ if (p) {
552
+ // Re-order operands so intersection point is closest to a (better precision)
553
+ // Source: Jonathan Shewchuk http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf
554
+ nearest = nearestPoint(p[0], p[1], ax, ay, bx, by, cx, cy, dx, dy);
555
+ if (nearest == 1) {
556
+ p = lineIntersection(bx, by, ax, ay, cx, cy, dx, dy);
557
+ } else if (nearest == 2) {
558
+ p = lineIntersection(cx, cy, dx, dy, ax, ay, bx, by);
559
+ } else if (nearest == 3) {
560
+ p = lineIntersection(dx, dy, cx, cy, ax, ay, bx, by);
561
+ }
562
+ }
563
+ if (p) {
564
+ clampIntersectionPoint(p, ax, ay, bx, by, cx, cy, dx, dy);
565
+ }
566
+ return p;
567
+ }
568
+
569
+ function lineIntersection(
570
+ ax: any,
571
+ ay: any,
572
+ bx: any,
573
+ by: any,
574
+ cx: any,
575
+ cy: any,
576
+ dx: any,
577
+ dy: any
578
+ ) {
579
+ const den = determinant2D(bx - ax, by - ay, dx - cx, dy - cy);
580
+ const eps = 1e-18;
581
+ let p;
582
+ if (den === 0) return null;
583
+ const m = orient2D(cx, cy, dx, dy, ax, ay) / den;
584
+ if (den <= eps && den >= -eps) {
585
+ // tiny denominator = low precision; using one of the endpoints as intersection
586
+ p = findEndpointInRange(ax, ay, bx, by, cx, cy, dx, dy);
587
+ /*if (!p) {
588
+ debug("[lineIntersection()]");
589
+ debugSegmentIntersection([], ax, ay, bx, by, cx, cy, dx, dy);
590
+ }*/
591
+ } else {
592
+ p = [ax + m * (bx - ax), ay + m * (by - ay)];
593
+ }
594
+ return p;
595
+ }
596
+
597
+ function findEndpointInRange(
598
+ ax: any,
599
+ ay: any,
600
+ bx: any,
601
+ by: any,
602
+ cx: any,
603
+ cy: any,
604
+ dx: any,
605
+ dy: any
606
+ ) {
607
+ let p = null;
608
+ if (!outsideRange(ax, cx, dx) && !outsideRange(ay, cy, dy)) {
609
+ p = [ax, ay];
610
+ } else if (!outsideRange(bx, cx, dx) && !outsideRange(by, cy, dy)) {
611
+ p = [bx, by];
612
+ } else if (!outsideRange(cx, ax, bx) && !outsideRange(cy, ay, by)) {
613
+ p = [cx, cy];
614
+ } else if (!outsideRange(dx, ax, bx) && !outsideRange(dy, ay, by)) {
615
+ p = [dx, dy];
616
+ }
617
+ return p;
618
+ }
619
+
620
+ /**
621
+ * 点が線分の範囲外にあるかを判定
622
+ *
623
+ * @param a - 判定する点の座標
624
+ * @param b - 線分の一方の端点
625
+ * @param c - 線分のもう一方の端点
626
+ */
627
+ function outsideRange(a: any, b: any, c: any) {
628
+ let out;
629
+ if (b < c) {
630
+ out = a < b || a > c;
631
+ } else if (b > c) {
632
+ out = a > b || a < c;
633
+ } else {
634
+ out = a != b;
635
+ }
636
+ return out;
637
+ }
638
+
639
+ // Return id of nearest point to x, y, among x0, y0, x1, y1, ...
640
+ function nearestPoint(x: any, y: any, ...args: any[]) {
641
+ let minIdx = -1,
642
+ minDist = Infinity,
643
+ dist;
644
+ for (let i = 0, j = 0, n = args.length; j < n; i++, j += 2) {
645
+ dist = distanceSq(x, y, args[j], args[j + 1]);
646
+ if (dist < minDist) {
647
+ minDist = dist;
648
+ minIdx = i;
649
+ }
650
+ }
651
+ return minIdx;
652
+ }
653
+
654
+ function distanceSq(ax: any, ay: any, bx: any, by: any) {
655
+ const dx = ax - bx,
656
+ dy = ay - by;
657
+ return dx * dx + dy * dy;
658
+ }
659
+
660
+ function clampIntersectionPoint(
661
+ p: any,
662
+ ax: any,
663
+ ay: any,
664
+ bx: any,
665
+ by: any,
666
+ cx: any,
667
+ cy: any,
668
+ dx: any,
669
+ dy: any
670
+ ) {
671
+ // Handle intersection points that fall outside the x-y range of either
672
+ // segment by snapping to nearest endpoint coordinate. Out-of-range
673
+ // intersection points can be caused by floating point rounding errors
674
+ // when a segment is vertical or horizontal. This has caused problems when
675
+ // repeatedly applying bbox clipping along the same segment
676
+ let x = p[0],
677
+ y = p[1];
678
+ // assumes that segment ranges intersect
679
+ x = clampToCloseRange(x, ax, bx);
680
+ x = clampToCloseRange(x, cx, dx);
681
+ y = clampToCloseRange(y, ay, by);
682
+ y = clampToCloseRange(y, cy, dy);
683
+ p[0] = x;
684
+ p[1] = y;
685
+ }
686
+
687
+ function clampToCloseRange(a: any, b: any, c: any) {
688
+ let lim;
689
+ if (outsideRange(a, b, c)) {
690
+ lim = Math.abs(a - b) < Math.abs(a - c) ? b : c;
691
+ if (Math.abs(a - lim) > 1e-15) {
692
+ //debug("[clampToCloseRange()] large clamping interval", a, b, c);
693
+ }
694
+ a = lim;
695
+ }
696
+ return a;
697
+ }
698
+
699
+ // Assume segments s1 and s2 are collinear and overlap; find one or two internal endpoints
700
+ function collinearIntersection(
701
+ ax: any,
702
+ ay: any,
703
+ bx: any,
704
+ by: any,
705
+ cx: any,
706
+ cy: any,
707
+ dx: any,
708
+ dy: any
709
+ ) {
710
+ const minX = Math.min(ax, bx, cx, dx),
711
+ maxX = Math.max(ax, bx, cx, dx),
712
+ minY = Math.min(ay, by, cy, dy),
713
+ maxY = Math.max(ay, by, cy, dy),
714
+ useY = maxY - minY > maxX - minX;
715
+ let coords: any = [];
716
+
717
+ if (useY ? inside(ay, minY, maxY) : inside(ax, minX, maxX)) {
718
+ coords.push(ax, ay);
719
+ }
720
+ if (useY ? inside(by, minY, maxY) : inside(bx, minX, maxX)) {
721
+ coords.push(bx, by);
722
+ }
723
+ if (useY ? inside(cy, minY, maxY) : inside(cx, minX, maxX)) {
724
+ coords.push(cx, cy);
725
+ }
726
+ if (useY ? inside(dy, minY, maxY) : inside(dx, minX, maxX)) {
727
+ coords.push(dx, dy);
728
+ }
729
+ if (coords.length != 2 && coords.length != 4) {
730
+ coords = null;
731
+ //debug("Invalid collinear segment intersection", coords);
732
+ } else if (
733
+ coords.length == 4 &&
734
+ coords[0] == coords[2] &&
735
+ coords[1] == coords[3]
736
+ ) {
737
+ // segs that meet in the middle don't count
738
+ coords = null;
739
+ }
740
+ return coords;
741
+ }
742
+
743
+ function endpointHit(
744
+ ax: any,
745
+ ay: any,
746
+ bx: any,
747
+ by: any,
748
+ cx: any,
749
+ cy: any,
750
+ dx: any,
751
+ dy: any
752
+ ) {
753
+ return (
754
+ (ax == cx && ay == cy) ||
755
+ (ax == dx && ay == dy) ||
756
+ (bx == cx && by == cy) ||
757
+ (bx == dx && by == dy)
758
+ );
759
+ }
760
+
761
+ function inside(x: any, minX: any, maxX: any) {
762
+ return x > minX && x < maxX;
763
+ }
764
+
765
+ // @xx array of x coords
766
+ // @ids an array of segment endpoint ids [a0, b0, a1, b1, ...]
767
+ // Sort @ids in place so that xx[a(n)] <= xx[b(n)] and xx[a(n)] <= xx[a(n+1)]
768
+ function sortSegmentIds(xx: any, ids: any) {
769
+ orderSegmentIds(xx, ids);
770
+ quicksortSegmentIds(xx, ids, 0, ids.length - 2);
771
+ }
772
+
773
+ function orderSegmentIds(xx: any, ids: any) {
774
+ for (let i = 0, n = ids.length; i < n; i += 2) {
775
+ if (xx[ids[i]] > xx[ids[i + 1]]) {
776
+ swap(ids, i, i + 1);
777
+ }
778
+ }
779
+ }
780
+
781
+ function swap(ids: any, i: number, j: number) {
782
+ const tmp = ids[i];
783
+ ids[i] = ids[j];
784
+ ids[j] = tmp;
785
+ }
786
+
787
+ function quicksortSegmentIds(a: any, ids: any, lo: any, hi: any) {
788
+ let i = lo,
789
+ j = hi,
790
+ pivot,
791
+ tmp;
792
+ while (i < hi) {
793
+ pivot = a[ids[((lo + hi) >> 2) << 1]]; // avoid n^2 performance on sorted arrays
794
+ while (i <= j) {
795
+ while (a[ids[i]] < pivot) i += 2;
796
+ while (a[ids[j]] > pivot) j -= 2;
797
+ if (i <= j) {
798
+ tmp = ids[i];
799
+ ids[i] = ids[j];
800
+ ids[j] = tmp;
801
+ tmp = ids[i + 1];
802
+ ids[i + 1] = ids[j + 1];
803
+ ids[j + 1] = tmp;
804
+ i += 2;
805
+ j -= 2;
806
+ }
807
+ }
808
+
809
+ if (j - lo < 40) insertionSortSegmentIds(a, ids, lo, j);
810
+ else quicksortSegmentIds(a, ids, lo, j);
811
+ if (hi - i < 40) {
812
+ insertionSortSegmentIds(a, ids, i, hi);
813
+ return;
814
+ }
815
+ lo = i;
816
+ j = hi;
817
+ }
818
+ }
819
+
820
+ function insertionSortSegmentIds(arr: any, ids: any, start: any, end: any) {
821
+ let id, id2;
822
+ for (let j = start + 2; j <= end; j += 2) {
823
+ id = ids[j];
824
+ id2 = ids[j + 1];
825
+ let i;
826
+ for (i = j - 2; i >= start && arr[id] < arr[ids[i]]; i -= 2) {
827
+ ids[i + 2] = ids[i];
828
+ ids[i + 3] = ids[i + 1];
829
+ }
830
+ ids[i + 2] = id;
831
+ ids[i + 3] = id2;
832
+ }
833
+ }
834
+
835
+ function formatIntersection(xy: any, s1: any, s2: any, xx: any, yy: any) {
836
+ const x = xy[0],
837
+ y = xy[1];
838
+ s1 = formatIntersectingSegment(x, y, s1[0], s1[1], xx, yy);
839
+ s2 = formatIntersectingSegment(x, y, s2[0], s2[1], xx, yy);
840
+ const a = s1[0] < s2[0] ? s1 : s2;
841
+ const b = a == s1 ? s2 : s1;
842
+ return { x, y, a, b };
843
+ }
844
+
845
+ function formatIntersectingSegment(
846
+ x: any,
847
+ y: any,
848
+ id1: any,
849
+ id2: any,
850
+ xx: any,
851
+ yy: any
852
+ ) {
853
+ let i = id1 < id2 ? id1 : id2,
854
+ j = i === id1 ? id2 : id1;
855
+ if (xx[i] == x && yy[i] == y) {
856
+ j = i;
857
+ } else if (xx[j] == x && yy[j] == y) {
858
+ i = j;
859
+ }
860
+ return [i, j];
861
+ }
862
+
863
+ /**
864
+ * 交差判定結果から重複を除去
865
+ *
866
+ * @param arr - 交差点情報の配列
867
+ * @returns 重複を除去した交差点情報の配列
868
+ */
869
+ function dedupIntersections(arr: any) {
870
+ const index: any = {};
871
+ return arr.filter((o: any) => {
872
+ const key = getIntersectionKey(o);
873
+ if (key in index) {
874
+ return false;
875
+ }
876
+ index[key] = true;
877
+ return true;
878
+ });
879
+ }
880
+
881
+ // Get an indexable key from an intersection object
882
+ // Assumes that vertex ids of o.a and o.b are sorted
883
+ function getIntersectionKey(o: any) {
884
+ return `${o.a.join(",")};${o.b.join(",")}`;
885
+ }
886
+
887
+ // Constructor takes arrays of coords: xx, yy, zz (optional)
888
+ //
889
+ class ArcIter {
890
+ _i = 0;
891
+ _n = 0;
892
+ _inc = 1;
893
+ _xx: Float64Array;
894
+ _yy: Float64Array;
895
+ i = 0;
896
+ x = 0;
897
+ y = 0;
898
+
899
+ constructor(xx: Float64Array, yy: Float64Array) {
900
+ this._xx = xx;
901
+ this._yy = yy;
902
+ }
903
+ }
904
+
905
+ function calcArcBounds(
906
+ xx: Float64Array,
907
+ yy: Float64Array,
908
+ start: number,
909
+ len: number
910
+ ) {
911
+ let i = start | 0;
912
+ const n = isNaN(len) ? xx.length - i : len + i;
913
+ let x: number,
914
+ y: number,
915
+ xmin: number,
916
+ ymin: number,
917
+ xmax: number,
918
+ ymax: number;
919
+ if (n > 0) {
920
+ xmin = xmax = xx[i];
921
+ ymin = ymax = yy[i];
922
+ } else return [undefined, undefined, undefined, undefined];
923
+ for (i++; i < n; i++) {
924
+ x = xx[i];
925
+ y = yy[i];
926
+ if (x < xmin) xmin = x;
927
+ if (x > xmax) xmax = x;
928
+ if (y < ymin) ymin = y;
929
+ if (y > ymax) ymax = y;
930
+ }
931
+ return [xmin, ymin, xmax, ymax];
932
+ }
933
+
934
+ class Bounds {
935
+ xmin?: number;
936
+ ymin?: number;
937
+ xmax?: number;
938
+ ymax?: number;
939
+
940
+ constructor(...args: any[]) {
941
+ if (args.length > 0) {
942
+ this.setBounds(args);
943
+ }
944
+ }
945
+
946
+ // Return a bounding box with the same extent as this one.
947
+ cloneBounds() {
948
+ return this.clone();
949
+ }
950
+
951
+ clone() {
952
+ // alias so child classes can override clone()
953
+ return new Bounds(this.xmin, this.ymin, this.xmax, this.ymax);
954
+ }
955
+
956
+ width() {
957
+ return this.xmax! - this.xmin! || 0;
958
+ }
959
+
960
+ height() {
961
+ return this.ymax! - this.ymin! || 0;
962
+ }
963
+
964
+ setBounds(a: any, b?: number, c?: number, d?: number) {
965
+ if (arguments.length == 1) {
966
+ // assume first arg is a Bounds or array
967
+ if (isArrayLike(a)) {
968
+ b = a[1];
969
+ c = a[2];
970
+ d = a[3];
971
+ a = a[0];
972
+ } else {
973
+ b = a.ymin;
974
+ c = a.xmax;
975
+ d = a.ymax;
976
+ a = a.xmin;
977
+ }
978
+ }
979
+
980
+ this.xmin = a;
981
+ this.ymin = b;
982
+ this.xmax = c;
983
+ this.ymax = d;
984
+ if (a > c! || b! > d!) this.update();
985
+ // error("Bounds#setBounds() min/max reversed:", a, b, c, d);
986
+ return this;
987
+ }
988
+
989
+ update() {
990
+ let tmp: number;
991
+ if (this.xmin! > this.xmax!) {
992
+ tmp = this.xmin!;
993
+ this.xmin = this.xmax;
994
+ this.xmax = tmp;
995
+ }
996
+ if (this.ymin! > this.ymax!) {
997
+ tmp = this.ymin!;
998
+ this.ymin = this.ymax;
999
+ this.ymax = tmp;
1000
+ }
1001
+ }
1002
+
1003
+ mergeBounds(bb: number | number[] | Bounds, ...args: number[]) {
1004
+ let a: number, b: number, c: number, d: number;
1005
+ if (bb instanceof Bounds) {
1006
+ a = bb.xmin!;
1007
+ b = bb.ymin!;
1008
+ c = bb.xmax!;
1009
+ d = bb.ymax!;
1010
+ } else if (args.length == 3) {
1011
+ a = bb as number;
1012
+ b = args[0];
1013
+ c = args[1];
1014
+ d = args[2];
1015
+ } else if ((bb as number[]).length == 4) {
1016
+ // assume array: [xmin, ymin, xmax, ymax]
1017
+ a = (bb as number[])[0];
1018
+ b = (bb as number[])[1];
1019
+ c = (bb as number[])[2];
1020
+ d = (bb as number[])[3];
1021
+ } else {
1022
+ error("Bounds#mergeBounds() invalid argument:", bb);
1023
+ }
1024
+
1025
+ if (this.xmin === void 0) {
1026
+ this.setBounds(a!, b!, c!, d!);
1027
+ } else {
1028
+ if (a! < this.xmin) this.xmin = a!;
1029
+ if (b! < this.ymin!) this.ymin = b!;
1030
+ if (c! > this.xmax!) this.xmax = c!;
1031
+ if (d! > this.ymax!) this.ymax = d!;
1032
+ }
1033
+ return this;
1034
+ }
1035
+ }