@maplat/tin 0.9.4 → 0.11.0

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