@maplat/tin 1.1.1 → 1.1.2-rc.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.
@@ -3,7 +3,7 @@ import type { FeatureCollection, Point, Polygon } from "geojson";
3
3
  import Delaunator from "delaunator";
4
4
  import { Constrain as EdgeBound } from "./edgebound/index.ts";
5
5
  import type { Edge } from "@maplat/transform";
6
- import type { TriangleProperties } from "./types/tin.d.ts";
6
+ import type { TriangleProperties } from "./types/tin.ts";
7
7
 
8
8
  /**
9
9
  * 制約付きTIN(Triangulated Irregular Network)を生成します
@@ -75,11 +75,25 @@ export class Constrain extends Base {
75
75
  */
76
76
  constrainOne(segP1: number, segP2: number): number {
77
77
  const { triangles, halfedges } = this.del;
78
+ this.assertVertex(segP1, segP1, segP2);
79
+ this.assertVertex(segP2, segP1, segP2);
80
+ this.assertInTriangulation(segP1, segP1, segP2);
81
+ this.assertInTriangulation(segP2, segP1, segP2);
78
82
  const start = this.vertMap[segP1];
79
83
 
84
+ // The limit only guards against a walk that never terminates.
85
+ // See maxConstrainSteps() for how it relates to valid input.
86
+ const maxSteps = this.maxConstrainSteps();
87
+ let steps = 0;
88
+
80
89
  // Loop over the edges touching segP1.
81
90
  let edg = start;
82
91
  do {
92
+ if (++steps > maxSteps) {
93
+ throw new Error(
94
+ `Constraining edge [${segP1}, ${segP2}] exceeded the iteration limit`,
95
+ );
96
+ }
83
97
  const p4 = triangles[edg];
84
98
  const nxt = nextEdge(edg);
85
99
 
@@ -115,6 +129,11 @@ export class Constrain extends Base {
115
129
  // no more intersects.
116
130
  let rescan = -1;
117
131
  while (edg !== -1) {
132
+ if (++steps > maxSteps) {
133
+ throw new Error(
134
+ `Constraining edge [${segP1}, ${segP2}] exceeded the iteration limit`,
135
+ );
136
+ }
118
137
  const adj = halfedges[edg];
119
138
  const bot = prevEdge(edg);
120
139
  const top = prevEdge(adj);
@@ -220,6 +239,50 @@ export class Constrain extends Base {
220
239
  return this.findEdge(segP1, segP2);
221
240
  }
222
241
 
242
+ /**
243
+ * Upper bound for the number of steps taken while constraining one edge.
244
+ *
245
+ * A constraint that crosses k edges is resolved in passes over the crossed
246
+ * edges, so the number of steps can grow with k squared (for example when
247
+ * the crossed edges fan out between two bowed rows of points). k is less
248
+ * than the number of half-edges, so the square of that number is never
249
+ * reached by a walk that terminates. The floor keeps tiny meshes away from
250
+ * the limit.
251
+ */
252
+ private maxConstrainSteps(): number {
253
+ const numEdges = this.del.triangles.length;
254
+ return Math.max(numEdges * numEdges, 4096);
255
+ }
256
+
257
+ /**
258
+ * Throw unless `vertex` is part of the triangulation. Delaunator leaves out
259
+ * points that coincide with another point, so a valid point id may have no
260
+ * triangle. An edge cannot start or end at such a point.
261
+ */
262
+ private assertInTriangulation(
263
+ vertex: number,
264
+ segP1: number,
265
+ segP2: number,
266
+ ): void {
267
+ if (this.vertMap[vertex] >= this.del.triangles.length) {
268
+ throw new Error(
269
+ `Invalid edge [${segP1}, ${segP2}]: vertex ${vertex} is not part of the triangulation`,
270
+ );
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Throw unless `vertex` is an id of a point given to Delaunator.
276
+ */
277
+ private assertVertex(vertex: number, segP1: number, segP2: number): void {
278
+ const numPoints = this.vertMap.length;
279
+ if (!Number.isInteger(vertex) || vertex < 0 || vertex >= numPoints) {
280
+ throw new Error(
281
+ `Invalid edge [${String(segP1)}, ${String(segP2)}]: vertex ids must be integers from 0 to ${numPoints - 1}`,
282
+ );
283
+ }
284
+ }
285
+
223
286
  /**
224
287
  * Fix the Delaunay condition.
225
288
  */
@@ -281,10 +344,21 @@ export class Constrain extends Base {
281
344
  findEdge(p1: number, p2: number): number {
282
345
  const start1 = this.vertMap[p2];
283
346
  const { triangles, halfedges } = this.del;
347
+ // p2 is not a point of the triangulation: there is no edge to find.
348
+ if (!(start1 < triangles.length)) {
349
+ return Infinity;
350
+ }
284
351
  let edg = start1;
285
352
  let prv: number;
353
+ // A walk around one vertex visits each half-edge at most once.
354
+ let steps = 0;
286
355
  // Walk around p2, iterating over the edges pointing to it.
287
356
  do {
357
+ if (++steps > triangles.length) {
358
+ throw new Error(
359
+ `Looking up edge [${p1}, ${p2}] exceeded the iteration limit`,
360
+ );
361
+ }
288
362
  if (triangles[edg] === p1) {
289
363
  return edg;
290
364
  }
package/src/index.ts CHANGED
@@ -18,8 +18,8 @@ export { counterPoint, createPoint, vertexCalc } from "./vertexutils.ts";
18
18
 
19
19
  // Type exports
20
20
  export type { SearchIndex } from "./searchutils.ts";
21
- export type { IntersectionPoint } from "./types/kinks.d.ts";
22
- export type { TriangleProperties } from "./types/tin.d.ts";
21
+ export type { IntersectionPoint } from "./types/kinks.ts";
22
+ export type { TriangleProperties } from "./types/tin.ts";
23
23
 
24
24
  // Re-export types from @maplat/transform
25
25
  export type {
package/src/kinks.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Feature, Point, Position } from "geojson";
2
2
  import { point } from "@turf/turf";
3
- import type { IntersectionPoint } from "./types/kinks.d.ts";
3
+ import type { IntersectionPoint } from "./types/kinks.ts";
4
4
 
5
5
  /**
6
6
  * 線分の交差点を検出するメインの関数
@@ -11,18 +11,48 @@ import type { IntersectionPoint } from "./types/kinks.d.ts";
11
11
  */
12
12
  export default function findIntersections(
13
13
  coords: Position[][],
14
+ ): Feature<Point>[] {
15
+ return findIntersectionsUpTo(coords, Infinity);
16
+ }
17
+
18
+ /**
19
+ * Tin が 1 方向(forw / bakw)について数え上げる交差の件数の上限
20
+ * (同じ位置の交差を 1 件に数えた件数)。
21
+ *
22
+ * 交差の件数は線分の数の 2 乗まで増えうる。対応が大きく乱れた制御点では
23
+ * 時間とメモリを使い切るため、ここで打ち切る。
24
+ * 同梱の実データで strict の交差が最も多いもの(約 3 万件)の 3 倍強にあたる。
25
+ */
26
+ export const MAX_KINKS_PER_DIRECTION = 100000;
27
+
28
+ /**
29
+ * 件数の上限 1 件あたりに許す「見つけた交差の総数(重複を含む)」。
30
+ *
31
+ * 同じ位置の交差は 1 件に数えるので、位置が重なる交差ばかりの入力では
32
+ * 件数の上限に届かない。総数がこの倍率を超えたら数え上げをやめる。
33
+ * 同梱の実データでは、総数は残る件数の約 4 倍。
34
+ */
35
+ const MAX_FOUND_PER_LIMIT = 16;
36
+
37
+ /**
38
+ * 線分の交差点を、件数の上限つきで検出する(Tin の内部用)
39
+ *
40
+ * @param coords - 線分群の座標配列
41
+ * @param limit - 返す交差点の件数の上限。同じ位置の交差を 1 件に数えた件数で数え、
42
+ * 届いた時点で検出をやめる。位置が重なる交差ばかりのときは、見つけた交差の総数が
43
+ * limit の 16 倍に届いた時点でもやめる
44
+ * @returns 検出された交差点のFeature配列(同じ位置の重複なし・高々 limit 件)
45
+ * @throws {Error} 座標に有限数(Number.isFinite)でない値が含まれる場合
46
+ */
47
+ export function findIntersectionsUpTo(
48
+ coords: Position[][],
49
+ limit: number,
14
50
  ): Feature<Point>[] {
15
51
  validateCoordinateValues(coords);
16
52
  const arcs = new ArcCollection(coords);
17
- const xy = arcs.findSegmentIntersections();
18
- const deduped: IntersectionPoint[] = dedupIntersections(xy);
19
- const unique = new Map<string, IntersectionPoint>();
20
-
21
- deduped.forEach((apoint: IntersectionPoint) => {
22
- unique.set(`${apoint.x}:${apoint.y}`, apoint);
23
- });
53
+ const unique = arcs.findSegmentIntersections(limit);
24
54
 
25
- return Array.from(unique.values()).map((apoint) =>
55
+ return unique.map((apoint) =>
26
56
  point([apoint.x, apoint.y])
27
57
  );
28
58
  }
@@ -271,9 +301,10 @@ class ArcCollection {
271
301
  * 線分の交差を検出
272
302
  * ストライプ分割による効率的な判定を実装
273
303
  *
274
- * @returns 検出された交差点の配列
304
+ * @param limit - 返す交差点の件数の上限(同じ位置の交差は 1 件に数える)
305
+ * @returns 検出された交差点の配列(同じ位置の重複なし)
275
306
  */
276
- findSegmentIntersections() {
307
+ findSegmentIntersections(limit = Infinity) {
277
308
  const bounds = this.getBounds(),
278
309
  ymin = bounds.ymin || 0,
279
310
  yrange = (bounds.ymax || 0) - ymin,
@@ -285,7 +316,7 @@ class ArcCollection {
285
316
  // 線分が属するストライプを辿る走査は、高々 stripeCount 回で終わる。
286
317
  // 万一の迷走(非有限数に由来する NaN など)に備えて上限を設ける。
287
318
  const maxStripeSteps = stripeCount + 1;
288
- let i, j;
319
+ let i;
289
320
 
290
321
  // Count segments in each stripe
291
322
  this.forEachSegment(
@@ -350,18 +381,30 @@ class ArcCollection {
350
381
  );
351
382
 
352
383
  // Detect intersections among segments in each stripe.
353
- const raw = this.getVertexData(),
354
- intersections = [];
355
- let arr;
356
- for (i = 0; i < stripeCount; i++) {
357
- if (raw.xx && raw.yy) {
358
- arr = intersectSegments(stripes[i], raw.xx, raw.yy);
359
- for (j = 0; j < arr.length; j++) {
360
- intersections.push(arr[j]);
361
- }
384
+ const raw = this.getVertexData();
385
+ // 同じ線分の組は複数のストライプで見つかることがあり、別の組が同じ位置で
386
+ // 交わることもある。上限は、同じ位置の交差を 1 件に数えた件数に掛ける。
387
+ // 位置が重なる交差ばかりだと、件数の上限に届かないまま数え上げが続く。
388
+ // 見つけた交差の総数(重複を含む)にも上限を置き、時間と seenKeys の大きさを抑える。
389
+ const maxFound = limit * MAX_FOUND_PER_LIMIT;
390
+ let found = 0;
391
+ const seenKeys = new Set<string>();
392
+ const unique = new Map<string, IntersectionPoint>();
393
+ const collect = (o: IntersectionPoint): boolean => {
394
+ found++;
395
+ const key = getIntersectionKey(o);
396
+ if (!seenKeys.has(key)) {
397
+ seenKeys.add(key);
398
+ unique.set(`${o.x}:${o.y}`, o);
399
+ }
400
+ return unique.size >= limit || found >= maxFound;
401
+ };
402
+ if (raw.xx && raw.yy) {
403
+ for (i = 0; i < stripeCount; i++) {
404
+ if (intersectSegments(stripes[i], raw.xx, raw.yy, collect)) break;
362
405
  }
363
406
  }
364
- return dedupIntersections(intersections);
407
+ return Array.from(unique.values());
365
408
  }
366
409
  }
367
410
 
@@ -444,9 +487,9 @@ function intersectSegments(
444
487
  ids: Uint32Array,
445
488
  xx: Float64Array,
446
489
  yy: Float64Array,
447
- ) {
448
- const lim = ids.length - 2,
449
- intersections = [];
490
+ collect: (intersection: IntersectionPoint) => boolean,
491
+ ): boolean {
492
+ const lim = ids.length - 2;
450
493
  let s1p1,
451
494
  s1p2,
452
495
  s2p1,
@@ -521,18 +564,21 @@ function intersectSegments(
521
564
  if (hit) {
522
565
  seg1 = [s1p1, s1p2];
523
566
  seg2 = [s2p1, s2p2];
524
- intersections.push(formatIntersection(hit, seg1, seg2, xx, yy));
567
+ // collect() returns true once enough intersections have been found.
568
+ if (collect(formatIntersection(hit, seg1, seg2, xx, yy))) return true;
525
569
  if (hit.length == 4) {
526
570
  // two collinear segments may have two endpoint intersections
527
- intersections.push(
528
- formatIntersection(hit.slice(2), seg1, seg2, xx, yy),
529
- );
571
+ if (
572
+ collect(formatIntersection(hit.slice(2), seg1, seg2, xx, yy))
573
+ ) {
574
+ return true;
575
+ }
530
576
  }
531
577
  }
532
578
  }
533
579
  i += 2;
534
580
  }
535
- return intersections;
581
+ return false;
536
582
  }
537
583
 
538
584
  /**
@@ -971,18 +1017,6 @@ function formatIntersectingSegment(
971
1017
  * @param arr - 交差点情報の配列
972
1018
  * @returns 重複を除去した交差点情報の配列
973
1019
  */
974
- function dedupIntersections(arr: IntersectionPoint[]) {
975
- const index: Record<string, boolean> = {};
976
- return arr.filter((o: IntersectionPoint) => {
977
- const key = getIntersectionKey(o);
978
- if (key in index) {
979
- return false;
980
- }
981
- index[key] = true;
982
- return true;
983
- });
984
- }
985
-
986
1020
  // Get an indexable key from an intersection object
987
1021
  // Assumes that vertex ids of o.a and o.b are sorted
988
1022
  function getIntersectionKey(o: IntersectionPoint) {
package/src/tin.ts CHANGED
@@ -45,12 +45,12 @@ import {
45
45
  calculatePlainVertices,
46
46
  type BoundaryVerticesParams,
47
47
  } from "./boundary-vertices.ts";
48
- import findIntersections from "./kinks.ts";
48
+ import { findIntersectionsUpTo, MAX_KINKS_PER_DIRECTION } from "./kinks.ts";
49
49
  import { insertSearchIndex } from "./searchutils.ts";
50
50
  import { counterPoint, createPoint, vertexCalc } from "./vertexutils.ts";
51
51
  import { resolveOverlaps } from "./strict-overlap.ts";
52
52
  import type { SearchIndex } from "./searchutils.ts";
53
- import type { PointsSetBD, VertexPosition } from "./types/tin.d.ts";
53
+ import type { PointsSetBD, VertexPosition } from "./types/tin.ts";
54
54
 
55
55
  type EdgeSegmentItem = [Position, number, number, number, string?];
56
56
  type EdgeNodeItem = [Position, Position, number];
@@ -300,8 +300,11 @@ export class Tin extends Transform {
300
300
 
301
301
  /**
302
302
  * 厳密なTINを計算します
303
+ *
304
+ * @param kinkLimit - forw / bakw それぞれで残す交差(kinks)の件数の上限
305
+ * (同じ位置の交差を 1 件に数えた件数)。届いた時点で数え上げをやめます
303
306
  */
304
- calculateStrictTin(): void {
307
+ calculateStrictTin(kinkLimit: number = MAX_KINKS_PER_DIRECTION): void {
305
308
  const bakTins = this.tins!.forw!.features.map((tri: Tri) =>
306
309
  counterTri(tri)
307
310
  );
@@ -332,7 +335,7 @@ export class Tin extends Transform {
332
335
  const tins = this.tins![direction as keyof TinsBD]!.features.map(
333
336
  (tin: Tri) => tin.geometry!.coordinates[0],
334
337
  );
335
- return findIntersections(tins);
338
+ return findIntersectionsUpTo(tins, kinkLimit);
336
339
  });
337
340
 
338
341
  if (kinks[0].length === 0 && kinks[1].length === 0) {
@@ -382,6 +385,10 @@ export class Tin extends Transform {
382
385
  const illstNodes = Object.assign([], this.edges[i][0]);
383
386
  const mercNodes = Object.assign([], this.edges[i][1]);
384
387
 
388
+ // 端点は GCP の添字で指す。範囲に無い・整数でない添字は、
389
+ // 以降の計算に渡さずここで止める。
390
+ assertEdgeIndices(edge, this.points.length, i);
391
+
385
392
  if (illstNodes.length === 0 && mercNodes.length === 0) {
386
393
  edges.push(edge);
387
394
  continue;
@@ -782,7 +789,11 @@ export class Tin extends Transform {
782
789
 
783
790
  // Calculate strict TIN if needed
784
791
  if (strict === Tin.MODE_STRICT || strict === Tin.MODE_AUTO) {
785
- this.calculateStrictTin();
792
+ // auto は交差の有無しか使わない(あれば loose に切り替えて kinks を捨てる)
793
+ // ので、1 件見つけた時点で数え上げをやめる。
794
+ this.calculateStrictTin(
795
+ strict === Tin.MODE_AUTO ? 1 : MAX_KINKS_PER_DIRECTION,
796
+ );
786
797
  }
787
798
 
788
799
  // Generate backward TIN if needed
@@ -824,3 +835,29 @@ export class Tin extends Transform {
824
835
  this.updateTin();
825
836
  }
826
837
  }
838
+
839
+ /**
840
+ * edge の両端が GCP の添字(0 以上・GCP の数未満の整数)であることを確かめます。
841
+ *
842
+ * @param edge - 検査する edge の両端([始点の添字, 終点の添字])
843
+ * @param pointCount - GCP の数
844
+ * @param edgeIndex - edges の中での位置(エラーメッセージ用)
845
+ * @throws {Error} 添字が整数でない、または GCP の範囲に無い場合
846
+ */
847
+ function assertEdgeIndices(
848
+ edge: Edge,
849
+ pointCount: number,
850
+ edgeIndex: number,
851
+ ): void {
852
+ const isValid = (index: unknown) =>
853
+ Number.isInteger(index) &&
854
+ (index as number) >= 0 &&
855
+ (index as number) < pointCount;
856
+ if (!Array.isArray(edge) || !isValid(edge[0]) || !isValid(edge[1])) {
857
+ throw new Error(
858
+ `Invalid edge at edges[${edgeIndex}]: start/end ${
859
+ JSON.stringify(edge)
860
+ } must be integer indices of points (0 to ${pointCount - 1})`,
861
+ );
862
+ }
863
+ }
@@ -0,0 +1,24 @@
1
+ export interface IntersectionPoint {
2
+ x: number;
3
+ y: number;
4
+ a: number[];
5
+ b: number[];
6
+ }
7
+
8
+ export type ArcCallback = (
9
+ i: number,
10
+ j: number,
11
+ xx: Float64Array,
12
+ yy: Float64Array,
13
+ ) => void;
14
+ export type ForEachSegmentCallback = (
15
+ v1: number,
16
+ v2: number,
17
+ xx: Float64Array,
18
+ yy: Float64Array,
19
+ ) => void;
20
+
21
+ export interface Arc {
22
+ i: number;
23
+ j: number;
24
+ }
@@ -1,51 +0,0 @@
1
- export interface IntersectionPoint {
2
- x: number;
3
- y: number;
4
- a: number[];
5
- b: number[];
6
- }
7
-
8
- export type ArcCallback = (
9
- i: number,
10
- j: number,
11
- xx: Float64Array,
12
- yy: Float64Array,
13
- ) => void;
14
- export type ForEachSegmentCallback = (
15
- v1: number,
16
- v2: number,
17
- xx: Float64Array,
18
- yy: Float64Array,
19
- ) => void;
20
-
21
- export interface Arc {
22
- i: number;
23
- j: number;
24
- }
25
-
26
- export class ArcIter {
27
- _xx: Float64Array | null;
28
- _yy: Float64Array | null;
29
- _zz: Float64Array | null;
30
- _arc: Arc | null;
31
- _i: number;
32
- _n: number;
33
- _inc: number;
34
- _useZ: boolean;
35
- x: number;
36
- y: number;
37
- z: number;
38
-
39
- constructor(
40
- xx: Float64Array | null,
41
- yy: Float64Array | null,
42
- zz?: Float64Array | null,
43
- );
44
- init(i: number, len: number, fw: boolean, zlim?: number): ArcIter;
45
- hasNext(): boolean;
46
- next(): void;
47
- }
48
-
49
- export class FilteredArcIter extends ArcIter {
50
- constructor();
51
- }
File without changes