@maplat/tin 0.11.0 → 0.11.2

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/index.ts CHANGED
@@ -1,934 +1,41 @@
1
1
  /**
2
- * Tin (Triangulated Irregular Network) Class
3
- *
4
- * このクラスは2つの平面座標系間の同相変換を実現します。
5
- * Transformクラスを継承し、設定ファイルの生成と管理の機能を追加しています。
6
- *
7
- * 主な機能:
8
- * - 制御点に基づくTINネットワークの生成
9
- * - 双方向の座標変換(順方向・逆方向)
10
- * - 境界チェックと管理
11
- * - 設定の永続化(コンパイル)と復元
12
- *
13
- * @extends Transform
2
+ * @maplat/tin - TIN (Triangulated Irregular Network) generation library
3
+ *
4
+ * This is the main entry point for the library.
5
+ * Provides TIN generation with constrained edges for map transformation.
14
6
  */
15
7
 
16
- "use strict";
17
- import booleanPointInPolygon from "@turf/boolean-point-in-polygon";
18
- import centroidFunc from "@turf/centroid";
19
- import convex from "@turf/convex";
20
- import { featureCollection, lineString, point, polygon } from "@turf/helpers";
21
-
22
- import lineIntersect from "@turf/line-intersect";
23
- import { Feature, Point, Position } from "geojson";
24
- import findIntersections from "./kinks";
25
- import type { EdgeSet, EdgeSetLegacy } from "@maplat/transform";
26
- import constrainedTin from "./constrained-tin";
27
- import { transformArr } from "@maplat/transform";
28
- import type { Tri, PropertyTriKey } from "@maplat/transform";
29
- import { rotateVerticesTriangle, counterTri } from "@maplat/transform";
30
- import { createPoint, counterPoint, vertexCalc } from "./vertexutils";
31
- import { normalizeEdges } from "@maplat/transform";
32
- import { insertSearchIndex } from "./searchutils";
33
- import type { SearchIndex } from "./searchutils";
34
- import { Transform, Compiled, format_version } from "@maplat/transform";
35
- import type {
36
- BiDirectionKey, VertexMode, StrictMode, YaxisMode, PointSet,
37
- WeightBufferBD
8
+ // Main class exports
9
+ export { Tin } from "./tin.ts";
10
+ export type { Options } from "./tin.ts";
11
+
12
+ // Utility function exports
13
+ export { default as constrainedTin } from "./constrained-tin.ts";
14
+ export { default as findIntersections } from "./kinks.ts";
15
+ export { insertSearchIndex } from "./searchutils.ts";
16
+ export { counterPoint, createPoint, vertexCalc } from "./vertexutils.ts";
17
+
18
+ // Type exports
19
+ export type { SearchIndex } from "./searchutils.ts";
20
+ export type { IntersectionPoint } from "./types/kinks.d.ts";
21
+ export type { TriangleProperties } from "./types/tin.d.ts";
22
+
23
+ // Re-export types from @maplat/transform
24
+ export type {
25
+ Compiled,
26
+ Edge,
27
+ EdgeSet,
28
+ EdgeSetLegacy,
29
+ PointSet,
30
+ PropertyTriKey,
31
+ StrictMode,
32
+ StrictStatus,
33
+ Tins,
34
+ Transform,
35
+ Tri,
36
+ VertexMode,
37
+ YaxisMode,
38
38
  } from "@maplat/transform";
39
39
 
40
- /**
41
- * Tinクラスの初期化オプション
42
- *
43
- * @property {Position[]} bounds - 境界ポリゴンを定義する頂点配列
44
- * @property {number[]} wh - 幅と高さ [width, height]
45
- * @property {VertexMode} vertexMode - 頂点モード ("plain" | "birdeye")
46
- * @property {StrictMode} strictMode - 厳密性モード ("strict" | "auto" | "loose")
47
- * @property {YaxisMode} yaxisMode - Y軸の向き ("follow" | "invert")
48
- * @property {number} importance - 重要度
49
- * @property {number} priority - 優先度
50
- * @property {boolean} stateFull - 状態を保持するかどうか
51
- * @property {PointSet[]} points - 制御点の配列
52
- * @property {EdgeSet[]} edges - エッジ(制約線)の配列
53
- */
54
- export interface Options {
55
- bounds: Position[];
56
- wh: number[];
57
- vertexMode: VertexMode;
58
- strictMode: StrictMode;
59
- yaxisMode: YaxisMode;
60
- importance: number;
61
- priority: number;
62
- stateFull: boolean;
63
- points: PointSet[];
64
- edges: EdgeSet[];
65
- }
66
-
67
- /**
68
- * Tin (Triangulated Irregular Network) クラス
69
- * 2つの平面座標系間の同相変換を実現します。
70
- *
71
- * @property {number} importance - マップの重要度
72
- * @property {number} priority - マップの優先度
73
- * @property {any} pointsSet - 変換用の点群セット
74
- */
75
- export default class Tin extends Transform {
76
- importance: number;
77
- priority: number;
78
- pointsSet: any;
79
-
80
- /**
81
- * Tinクラスのインスタンスを生成します
82
- *
83
- * @param {Partial<Options>} options - 初期化オプション
84
- * bounds または wh のどちらかが必須です
85
- */
86
- constructor(options: Partial<Options> = {} as Options) {
87
- super();
88
- if (options.bounds) {
89
- this.setBounds(options.bounds);
90
- } else {
91
- this.setWh(options.wh!);
92
- this.vertexMode = options.vertexMode || Tin.VERTEX_PLAIN;
93
- }
94
- this.strictMode = options.strictMode || Tin.MODE_AUTO;
95
- this.yaxisMode = options.yaxisMode || Tin.YAXIS_INVERT;
96
- this.importance = options.importance || 0;
97
- this.priority = options.priority || 0;
98
- this.stateFull = options.stateFull || false;
99
- if (options.points) {
100
- this.setPoints(options.points);
101
- }
102
- if (options.edges) {
103
- this.setEdges(options.edges);
104
- }
105
- }
106
-
107
- /**
108
- * フォーマットバージョンを取得します
109
- *
110
- * @returns {number} 現在のフォーマットバージョン
111
- */
112
- getFormatVersion() {
113
- return format_version;
114
- }
115
-
116
- /**
117
- * 制御点(GCP: Ground Control Points)を設定します
118
- *
119
- * @param points - 制御点の配列。各要素は [ソース座標, ターゲット座標] の形式
120
- *
121
- * 注意:この操作によりTINネットワークはリセットされ、
122
- * 再度updateTin()を呼び出す必要があります。
123
- */
124
- setPoints(points: PointSet[]) {
125
- if (this.yaxisMode == Tin.YAXIS_FOLLOW) {
126
- points = points.map(point => [point[0], [point[1][0], -1 * point[1][1]]]);
127
- }
128
- this.points = points;
129
- this.tins = undefined;
130
- this.indexedTins = undefined;
131
- }
132
-
133
- /**
134
- * エッジ(制約線)を設定します
135
- *
136
- * @param edges - エッジの配列。新規フォーマットまたはレガシーフォーマットに対応
137
- *
138
- * 注意:この操作によりTINネットワークはリセットされ、
139
- * 再度updateTin()を呼び出す必要があります。
140
- */
141
- setEdges(edges: EdgeSet[] | EdgeSetLegacy[] = []) {
142
- this.edges = normalizeEdges(edges);
143
- this.edgeNodes = undefined;
144
- this.tins = undefined;
145
- this.indexedTins = undefined;
146
- }
147
-
148
- /**
149
- * 境界ポリゴンを設定します
150
- *
151
- * @param bounds - 境界を定義する頂点座標の配列
152
- *
153
- * - 境界ポリゴンの計算
154
- * - バウンディングボックスの計算
155
- * - 内部状態の更新
156
- */
157
- setBounds(bounds: number[][]) {
158
- this.bounds = bounds;
159
- let minx = bounds[0][0];
160
- let maxx = minx;
161
- let miny = bounds[0][1];
162
- let maxy = miny;
163
- const coords = [bounds[0]];
164
- for (let i = 1; i < bounds.length; i++) {
165
- const xy = bounds[i];
166
- if (xy[0] < minx) minx = xy[0];
167
- if (xy[0] > maxx) maxx = xy[0];
168
- if (xy[1] < miny) miny = xy[1];
169
- if (xy[1] > maxy) maxy = xy[1];
170
- coords.push(xy);
171
- }
172
- coords.push(bounds[0]);
173
- this.boundsPolygon = polygon([coords]);
174
- this.xy = [minx, miny];
175
- this.wh = [maxx - minx, maxy - miny];
176
- this.vertexMode = Tin.VERTEX_PLAIN;
177
- this.tins = undefined;
178
- this.indexedTins = undefined;
179
- }
180
-
181
- /**
182
- * 現在の設定を永続化可能な形式にコンパイルします
183
- *
184
- * @returns Compiled - コンパイルされた設定オブジェクト
185
- *
186
- * 以下の情報が含まれます:
187
- * - バージョン情報
188
- * - 制御点データ
189
- * - TINネットワーク情報
190
- * - 境界情報
191
- * - 各種モード設定
192
- */
193
- getCompiled(): Compiled {
194
- const compiled: Partial<Compiled> = {};
195
- // 新compileロジック
196
- // Formatバージョン
197
- compiled.version = format_version;
198
- // points, weightBufferはそのまま保存
199
- compiled.points = this.points;
200
- compiled.weight_buffer = this.pointsWeightBuffer;
201
- // centroidは座標の対応のみ保存
202
- compiled.centroid_point = [
203
- this.centroid!.forw!.geometry!.coordinates,
204
- this.centroid!.forw!.properties!.target.geom
205
- ];
206
- // vertices_paramsの最初の値はそのまま保存
207
- compiled.vertices_params = [
208
- this.vertices_params!.forw![0],
209
- this.vertices_params!.bakw![0]
210
- ];
211
- // vertices_paramsの2番目の値(セントロイドと地図頂点の三角形ポリゴン)は、地図頂点座標のみ記録
212
- compiled.vertices_points = [];
213
- const vertices = this.vertices_params!.forw![1];
214
- [0, 1, 2, 3].map(i => {
215
- const vertex_data = vertices![i].features[0];
216
- const forw = vertex_data.geometry!.coordinates[0][1];
217
- const bakw = vertex_data.properties!.b.geom;
218
- compiled.vertices_points![i] = [forw, bakw];
219
- });
220
- compiled.strict_status = this.strict_status;
221
- // tinは座標インデックスのみ記録
222
- compiled.tins_points = [[]];
223
- this.tins!.forw!.features.map((tin: Tri) => {
224
- compiled.tins_points![0].push(
225
- (["a", "b", "c"] as PropertyTriKey[]).map(
226
- idx => tin.properties![idx]!.index
227
- )
228
- );
229
- });
230
- // 自動モードでエラーがある時(loose)は、逆方向のtinも記録。
231
- // 厳格モードでエラーがある時(strict_error)は、エラー点情報(kinks)を記録。
232
- if (this.strict_status == Tin.STATUS_LOOSE) {
233
- compiled.tins_points[1] = [];
234
- this.tins!.bakw!.features.map((tin: Tri) => {
235
- compiled.tins_points![1].push(
236
- (["a", "b", "c"] as PropertyTriKey[]).map(
237
- idx => tin.properties![idx]!.index
238
- )
239
- );
240
- });
241
- } else if (this.strict_status == Tin.STATUS_ERROR) {
242
- compiled.kinks_points = this.kinks!.bakw!.features.map(
243
- (kink: Feature<Point>) => kink.geometry!.coordinates
244
- );
245
- }
246
- // After 0.7.3: Freeze strict_mode & vertex_mode & Update yAxis logic
247
- compiled.yaxisMode = this.yaxisMode;
248
- compiled.vertexMode = this.vertexMode;
249
- compiled.strictMode = this.strictMode;
250
- // bounds対応
251
- if (this.bounds) {
252
- compiled.bounds = this.bounds;
253
- compiled.boundsPolygon = this.boundsPolygon;
254
- compiled.xy = this.xy;
255
- compiled.wh = this.wh;
256
- } else {
257
- compiled.wh = this.wh;
258
- }
259
- // edge対応
260
- compiled.edges = this.edges;
261
- compiled.edgeNodes = this.edgeNodes;
262
- return compiled as Compiled;
263
- }
264
-
265
- /**
266
- * 幅と高さを設定します
267
- *
268
- * @param {number[]} wh - [width, height] の形式で指定
269
- * この操作によりTINネットワークはリセットされます
270
- */
271
- setWh(wh: number[]) {
272
- this.wh = wh;
273
- this.xy = [0, 0];
274
- this.bounds = undefined;
275
- this.boundsPolygon = undefined;
276
- this.tins = undefined;
277
- this.indexedTins = undefined;
278
- }
279
-
280
- /**
281
- * 頂点モードを設定します
282
- *
283
- * @param {VertexMode} mode - "plain" または "birdeye"
284
- * この操作によりTINネットワークはリセットされます
285
- */
286
- setVertexMode(mode: VertexMode) {
287
- this.vertexMode = mode;
288
- this.tins = undefined;
289
- this.indexedTins = undefined;
290
- }
291
-
292
- /**
293
- * 厳密性モードを設定します
294
- *
295
- * @param {StrictMode} mode - "strict", "auto", または "loose"
296
- * この操作によりTINネットワークはリセットされます
297
- */
298
- setStrictMode(mode: StrictMode) {
299
- this.strictMode = mode;
300
- this.tins = undefined;
301
- this.indexedTins = undefined;
302
- }
303
-
304
- /**
305
- * 厳密なTINを計算します
306
- *
307
- * - 逆方向の三角形を生成
308
- * - 交差チェックを実行
309
- * - 結果に基づいてstrict_statusを更新
310
- *
311
- * strict_statusは以下のいずれかになります:
312
- * - STATUS_STRICT: 交差なし
313
- * - STATUS_ERROR: 交差あり
314
- */
315
- calcurateStrictTin() {
316
- const tris = this.tins!.forw!.features.map((tri: Tri) => counterTri(tri));
317
- this.tins!.bakw = featureCollection(tris);
318
-
319
- const searchIndex: SearchIndex = {};
320
- this.tins!.forw!.features.forEach((forTri: Tri, index: number) => {
321
- const bakTri: Tri = this.tins!.bakw!.features[index];
322
- insertSearchIndex(searchIndex, { forw: forTri, bakw: bakTri });
323
- });
324
-
325
- const result = (["forw", "bakw"] as BiDirectionKey[]).map(direc => {
326
- const coords = this.tins![direc]!.features.map(
327
- poly => poly.geometry!.coordinates[0]
328
- );
329
- return findIntersections(coords);
330
- });
331
-
332
- if (result[0].length == 0 && result[1].length == 0) {
333
- this.strict_status = Tin.STATUS_STRICT;
334
- delete this.kinks;
335
- } else {
336
- this.strict_status = Tin.STATUS_ERROR;
337
- this.kinks = {};
338
- if (result[0].length > 0)
339
- this.kinks.forw = featureCollection(result[0]);
340
- if (result[1].length > 0)
341
- this.kinks.bakw = featureCollection(result[1]);
342
- }
343
- }
344
-
345
- /**
346
- * 点群セットを生成します
347
- *
348
- * 以下の処理を行います:
349
- * 1. 制御点からポイントセットを生成
350
- * 2. エッジ節点の生成と追加
351
- * 3. エッジの接続関係の構築
352
- *
353
- * @returns {object} 生成された点群セットと接続情報
354
- * @property {FeatureCollection} forw - 順方向の点群
355
- * @property {FeatureCollection} bakw - 逆方向の点群
356
- * @property {Array} edges - エッジ接続情報
357
- */
358
- generatePointsSet() {
359
- const pointsArray = { forw: [] as any[], bakw: [] as any[] };
360
- for (let i = 0; i < this.points.length; i++) {
361
- const mapxy = this.points[i][0];
362
- const mercs = this.points[i][1];
363
- const forPoint = createPoint(mapxy, mercs, i);
364
- pointsArray.forw.push(forPoint as any);
365
- pointsArray.bakw.push(counterPoint(forPoint));
366
- }
367
- const edges = [];
368
- let edgeNodeIndex = 0;
369
- this.edgeNodes = [];
370
- if (!this.edges) this.edges = [];
371
- for (let i = 0; i < this.edges.length; i++) {
372
- const startEnd = this.edges[i][2];
373
- const illstNodes = Object.assign([], this.edges[i][0]);
374
- const mercNodes = Object.assign([], this.edges[i][1]);
375
- if (illstNodes.length === 0 && mercNodes.length === 0) {
376
- edges.push(startEnd);
377
- continue;
378
- }
379
- illstNodes.unshift(this.points[startEnd[0]][0]);
380
- illstNodes.push(this.points[startEnd[1]][0]);
381
- mercNodes.unshift(this.points[startEnd[0]][1]);
382
- mercNodes.push(this.points[startEnd[1]][1]);
383
- const lengths = [illstNodes, mercNodes].map(nodes => {
384
- const eachLengths = nodes.map((node: any, index: any, arr: any) => {
385
- if (index === 0) return 0;
386
- const prev = arr[index - 1];
387
- return Math.sqrt(
388
- Math.pow(node[0] - prev[0], 2) + Math.pow(node[1] - prev[1], 2)
389
- );
390
- });
391
- const sumLengths = eachLengths.reduce(
392
- (prev: any, node: any, index: any) => {
393
- if (index === 0) return [0];
394
- prev.push(prev[index - 1] + node);
395
- return prev;
396
- },
397
- []
398
- );
399
- return sumLengths.map((eachSum: any, index: any, arr: any) => {
400
- const ratio = eachSum / arr[arr.length - 1];
401
- return [nodes[index], eachLengths[index], sumLengths[index], ratio];
402
- });
403
- });
404
- lengths
405
- .map((thisLengths, i) => {
406
- const anotherLengths = lengths[i ? 0 : 1];
407
- return thisLengths
408
- .filter(
409
- (val: any, index: any) =>
410
- !(
411
- index === 0 ||
412
- index === thisLengths.length - 1 ||
413
- val[4] === "handled"
414
- )
415
- )
416
- .map((lengthItem: any) => {
417
- const node = lengthItem[0];
418
- const ratio = lengthItem[3];
419
- const anotherSets = anotherLengths.reduce(
420
- (prev: any, item: any, index: any, arr: any) => {
421
- if (prev) return prev;
422
- const next = arr[index + 1];
423
- if (item[3] === ratio) {
424
- item[4] = "handled";
425
- return [item];
426
- }
427
- if (item[3] < ratio && next[3] > ratio) return [item, next];
428
- return;
429
- },
430
- undefined
431
- );
432
- if (anotherSets.length === 1) {
433
- return i === 0
434
- ? [node, anotherSets[0][0], ratio]
435
- : [anotherSets[0][0], node, ratio];
436
- } else {
437
- const anotherPrev = anotherSets[0];
438
- const anotherNext = anotherSets[1];
439
- const ratioDelta = ratio - anotherPrev[3];
440
- const ratioAnother = anotherNext[3] - anotherPrev[3];
441
- const ratioInEdge = ratioDelta / ratioAnother;
442
- const anotherNode = [
443
- (anotherNext[0][0] - anotherPrev[0][0]) * ratioInEdge +
444
- anotherPrev[0][0],
445
- (anotherNext[0][1] - anotherPrev[0][1]) * ratioInEdge +
446
- anotherPrev[0][1]
447
- ];
448
- return i === 0
449
- ? [node, anotherNode, ratio]
450
- : [anotherNode, node, ratio];
451
- }
452
- });
453
- })
454
- .reduce((prev, nodes) => prev.concat(nodes), [])
455
- .sort((a: any, b: any) => (a[2] < b[2] ? -1 : 1))
456
- .map((node: any, index: any, arr: any) => {
457
- this.edgeNodes![edgeNodeIndex] = [node[0], node[1]];
458
- const forPoint = createPoint(node[0], node[1], `e${edgeNodeIndex}`);
459
- edgeNodeIndex++;
460
- pointsArray.forw.push(forPoint);
461
- pointsArray.bakw.push(counterPoint(forPoint));
462
- if (index === 0) {
463
- edges.push([startEnd[0], pointsArray.forw.length - 1]);
464
- } else {
465
- edges.push([
466
- pointsArray.forw.length - 2,
467
- pointsArray.forw.length - 1
468
- ]);
469
- }
470
- if (index === arr.length - 1) {
471
- edges.push([pointsArray.forw.length - 1, startEnd[1]]);
472
- }
473
- });
474
- }
475
- return {
476
- forw: featureCollection(pointsArray.forw),
477
- bakw: featureCollection(pointsArray.bakw),
478
- edges
479
- };
480
- }
481
-
482
- /**
483
- * 入力データの検証と初期データの準備
484
- * - 境界値のチェック
485
- * - バッファー付き境界の計算
486
- * - 点群セットの生成
487
- * @returns {object} 検証済みの点群セットと境界データ
488
- * @throws {Error} "SOME POINTS OUTSIDE" 制御点が境界外にある場合
489
- */
490
- private validateAndPrepareInputs() {
491
- // バッファー付き境界の計算
492
- const minx = this.xy![0] - 0.05 * this.wh![0];
493
- const maxx = this.xy![0] + 1.05 * this.wh![0];
494
- const miny = this.xy![1] - 0.05 * this.wh![1];
495
- const maxy = this.xy![1] + 1.05 * this.wh![1];
496
-
497
- // 境界チェック
498
- const inside = this.points.reduce(
499
- (prev: boolean, curr: PointSet) => prev && (
500
- this.bounds
501
- ? booleanPointInPolygon(curr[0], this.boundsPolygon!)
502
- : (
503
- curr[0][0] >= minx &&
504
- curr[0][0] <= maxx &&
505
- curr[0][1] >= miny &&
506
- curr[0][1] <= maxy
507
- )
508
- ),
509
- true
510
- );
511
-
512
- if (!inside) {
513
- throw "SOME POINTS OUTSIDE";
514
- }
515
-
516
- // 境界ボックスの準備
517
- let bbox: number[][] = [];
518
- if (this.wh) {
519
- bbox = [
520
- [minx, miny],
521
- [maxx, miny],
522
- [minx, maxy],
523
- [maxx, maxy]
524
- ];
525
- }
526
-
527
- // 点群セットの生成
528
- const pointsSet = this.generatePointsSet();
529
-
530
- return { pointsSet, bbox, minx, maxx, miny, maxy };
531
- }
532
-
533
- /**
534
- * TINネットワークを更新し、座標変換の準備を行います
535
- *
536
- * このメソッドは以下の処理を実行します:
537
- * 1. 入力データの検証
538
- * 2. 制御点のTIN生成
539
- * 3. Convex Hull(凸包)の計算
540
- * 4. 境界の調整
541
- * 5. 変換パラメータの計算
542
- *
543
- * @throws {Error} "TOO LINEAR1" - 制御点が直線的すぎる場合
544
- * @throws {Error} "TOO LINEAR2" - 変換後の点が直線的すぎる場合
545
- * @throws {Error} "SOME POINTS OUTSIDE" - 制御点が境界外にある場合
546
- */
547
- updateTin() {
548
- let strict = this.strictMode;
549
- if (strict != Tin.MODE_STRICT && strict != Tin.MODE_LOOSE) {
550
- strict = Tin.MODE_AUTO;
551
- }
552
-
553
- const { pointsSet, bbox, minx, maxx, miny, maxy } = this.validateAndPrepareInputs();
554
-
555
- const tinForCentroid = constrainedTin(pointsSet.forw, pointsSet.edges, "target");
556
- const tinBakCentroid = constrainedTin(pointsSet.bakw, pointsSet.edges, "target");
557
- const forCentroidFt = centroidFunc(pointsSet.forw);
558
-
559
- if ( tinForCentroid.features.length == 0 || tinBakCentroid.features.length == 0 ) {
560
- throw "TOO LINEAR1";
561
- }
562
-
563
- // Convex Hull(凸包)の計算と変換
564
- const convexBuf: { [key: string]: { forw: Position; bakw: Position } } = {};
565
-
566
- // Forward方向の凸包計算
567
- const forConvex = (convex(pointsSet.forw)!.geometry).coordinates[0];
568
- let vconvex;
569
- try {
570
- // Forward方向の頂点の変換
571
- vconvex = forConvex.map((forw) => ({
572
- forw,
573
- bakw: transformArr(point(forw), tinForCentroid)
574
- }));
575
- vconvex.forEach(vertex => {
576
- convexBuf[`${vertex.forw[0]}:${vertex.forw[1]}`] = vertex;
577
- });
578
- } catch (_e) {
579
- throw "TOO LINEAR2";
580
- }
581
-
582
- // Backward方向の凸包計算
583
- const bakConvex = (convex(pointsSet.bakw)!.geometry).coordinates[0];
584
- try {
585
- // Backward方向の頂点の変換
586
- vconvex = bakConvex.map((bakw) => ({
587
- bakw,
588
- forw: transformArr(point(bakw), tinBakCentroid)
589
- }));
590
- vconvex.forEach(vertex => {
591
- convexBuf[`${vertex.forw[0]}:${vertex.forw[1]}`] = vertex;
592
- });
593
- } catch (_e) {
594
- throw "TOO LINEAR2";
595
- }
596
-
597
- // Calcurating Forward/Backward Centroid
598
- const centroid = {
599
- forw: forCentroidFt.geometry.coordinates,
600
- bakw: transformArr(forCentroidFt, tinForCentroid)
601
- };
602
- const forwBuf = createPoint(centroid.forw, centroid.bakw, "c");
603
- this.centroid = { forw: forwBuf, bakw: counterPoint(forwBuf) };
604
-
605
- // Calcurating Convex full to get Convex full polygon's vertices
606
- const expandConvex = Object.keys(convexBuf).reduce(
607
- (prev, key, _, _array) => {
608
- const forVertex = convexBuf[key].forw;
609
- const bakVertex = convexBuf[key].bakw;
610
- // Convexhullの各頂点に対し、重心からの差分を取る
611
- const vertexDelta = {
612
- forw: [
613
- forVertex[0] - centroid.forw[0],
614
- forVertex[1] - centroid.forw[1]
615
- ]
616
- };
617
- (vertexDelta as any).bakw = [
618
- bakVertex[0] - centroid.bakw[0],
619
- bakVertex[1] - centroid.bakw[1]
620
- ];
621
- // X軸方向、Y軸方向それぞれに対し、地図外郭XY座標との重心との比を取る
622
- const xRate =
623
- vertexDelta.forw[0] == 0
624
- ? Infinity
625
- : ((vertexDelta.forw[0] < 0 ? minx : maxx) - centroid.forw[0]) /
626
- vertexDelta.forw[0];
627
- const yRate =
628
- vertexDelta.forw[1] == 0
629
- ? Infinity
630
- : ((vertexDelta.forw[1] < 0 ? miny : maxy) - centroid.forw[1]) /
631
- vertexDelta.forw[1];
632
- // xRate, yRateが同じ値であれば重心と地図頂点を結ぶ線上に乗る
633
- if (Math.abs(xRate) / Math.abs(yRate) < 1.1) {
634
- const point = {
635
- forw: [
636
- vertexDelta.forw[0] * xRate + centroid.forw[0],
637
- vertexDelta.forw[1] * xRate + centroid.forw[1]
638
- ],
639
- bakw: [
640
- (vertexDelta as any).bakw[0] * xRate + centroid.bakw[0],
641
- (vertexDelta as any).bakw[1] * xRate + centroid.bakw[1]
642
- ]
643
- };
644
- if (vertexDelta.forw[0] < 0) (prev[3] as any[]).push(point);
645
- else (prev[1] as any[]).push(point);
646
- }
647
- if (Math.abs(yRate) / Math.abs(xRate) < 1.1) {
648
- const point = {
649
- forw: [
650
- vertexDelta.forw[0] * yRate + centroid.forw[0],
651
- vertexDelta.forw[1] * yRate + centroid.forw[1]
652
- ],
653
- bakw: [
654
- (vertexDelta as any).bakw[0] * yRate + centroid.bakw[0],
655
- (vertexDelta as any).bakw[1] * yRate + centroid.bakw[1]
656
- ]
657
- };
658
- if (vertexDelta.forw[1] < 0) (prev[0] as any[]).push(point);
659
- else (prev[2] as any[]).push(point);
660
- }
661
- return prev;
662
- },
663
- [[], [], [], []]
664
- );
665
-
666
- // Calcurating Average scaling factors and rotation factors per orthants
667
- let orthant = Object.keys(convexBuf)
668
- .reduce(
669
- (prev, key, idx, array) => {
670
- const forVertex = convexBuf[key].forw;
671
- const bakVertex = convexBuf[key].bakw;
672
- const vertexDelta = {
673
- forw: [
674
- forVertex[0] - centroid.forw[0],
675
- forVertex[1] - centroid.forw[1]
676
- ]
677
- };
678
- (vertexDelta as any).bakw = [
679
- bakVertex[0] - centroid.bakw[0],
680
- centroid.bakw[1] - bakVertex[1]
681
- ];
682
- if (vertexDelta.forw[0] == 0 || vertexDelta.forw[1] == 0)
683
- return prev;
684
- let index = 0;
685
- if (vertexDelta.forw[0] > 0) index += 1;
686
- if (vertexDelta.forw[1] > 0) index += 2;
687
- (prev[index] as any[]).push([
688
- vertexDelta.forw,
689
- (vertexDelta as any).bakw
690
- ]);
691
- if (idx == array.length - 1) {
692
- // If some orthants have no Convex full polygon's vertices, use same average factor to every orthants
693
- return prev.length ==
694
- prev.filter(val => val.length > 0).length &&
695
- this.vertexMode == Tin.VERTEX_BIRDEYE
696
- ? prev
697
- : prev.reduce((pre, cur) => [pre[0].concat(cur)], [[]]);
698
- }
699
- return prev;
700
- },
701
- [[], [], [], []]
702
- )
703
- .map(item =>
704
- // Finalize calcuration of Average scaling factors and rotation factors
705
- item.reduce(
706
- (prev: number[] | null, curr: any, index: number, arr: any[]) => {
707
- if (!prev) prev = [Infinity, 0, 0];
708
- // if (!prev) prev = [0, 0, 0];
709
- // var distanceSum = prev[0] + Math.sqrt(Math.pow(curr[0][0], 2) + Math.pow(curr[0][1], 2)) /
710
- // Math.sqrt(Math.pow(curr[1][0], 2) + Math.pow(curr[1][1], 2));
711
- let distanceSum =
712
- Math.sqrt(Math.pow(curr[0][0], 2) + Math.pow(curr[0][1], 2)) /
713
- Math.sqrt(Math.pow(curr[1][0], 2) + Math.pow(curr[1][1], 2));
714
- distanceSum = distanceSum < prev[0] ? distanceSum : prev[0];
715
- const thetaDelta =
716
- Math.atan2(curr[0][0], curr[0][1]) -
717
- Math.atan2(curr[1][0], curr[1][1]);
718
- const sumThetaX = prev[1] + Math.cos(thetaDelta);
719
- const sumThetaY = prev[2] + Math.sin(thetaDelta);
720
- if (index == arr.length - 1) {
721
- // return [distanceSum / arr.length, Math.atan2(sumThetaY, sumThetaX)];
722
- return [distanceSum, Math.atan2(sumThetaY, sumThetaX)];
723
- }
724
- return [distanceSum, sumThetaX, sumThetaY];
725
- },
726
- null
727
- )
728
- );
729
- // "Using same average factor to every orthants" case
730
- if (orthant.length == 1)
731
- orthant = [orthant[0], orthant[0], orthant[0], orthant[0]];
732
-
733
- // Calcurating Backward Bounding box of map
734
- let verticesSet = orthant.map((delta, index) => {
735
- const forVertex = bbox[index];
736
- const forDelta = [
737
- forVertex[0] - centroid.forw[0],
738
- forVertex[1] - centroid.forw[1]
739
- ];
740
- const forDistance = Math.sqrt(
741
- Math.pow(forDelta[0], 2) + Math.pow(forDelta[1], 2)
742
- );
743
- const bakDistance = forDistance / delta![0];
744
- const forTheta = Math.atan2(forDelta[0], forDelta[1]);
745
- const bakTheta = forTheta - delta![1];
746
- const bakVertex = [
747
- centroid.bakw[0] + bakDistance * Math.sin(bakTheta),
748
- centroid.bakw[1] - bakDistance * Math.cos(bakTheta)
749
- ];
750
- return { forw: forVertex, bakw: bakVertex };
751
- });
752
-
753
- const swap = verticesSet[2];
754
- verticesSet[2] = verticesSet[3];
755
- verticesSet[3] = swap;
756
- // Bounding Boxの頂点を、全てのgcpが内部に入るように引き延ばす
757
- const expandRate = [1, 1, 1, 1];
758
- for (let i = 0; i < 4; i++) {
759
- const j = (i + 1) % 4;
760
- const side = lineString([verticesSet[i].bakw, verticesSet[j].bakw]);
761
- const expands = expandConvex[i];
762
- expands.map((expand: any) => {
763
- const expandLine = lineString([centroid.bakw, expand.bakw]);
764
- const intersect = lineIntersect(side, expandLine);
765
- if (
766
- intersect.features.length > 0 &&
767
- intersect.features[0].geometry
768
- ) {
769
- const intersect_ = intersect.features[0];
770
- const expandDist = Math.sqrt(
771
- Math.pow(expand.bakw[0] - centroid.bakw[0], 2) +
772
- Math.pow(expand.bakw[1] - centroid.bakw[1], 2)
773
- );
774
- const onSideDist = Math.sqrt(
775
- Math.pow(
776
- (intersect_.geometry as any).coordinates[0] -
777
- centroid.bakw[0],
778
- 2
779
- ) +
780
- Math.pow(
781
- (intersect_.geometry as any).coordinates[1] -
782
- centroid.bakw[1],
783
- 2
784
- )
785
- );
786
- const rate = expandDist / onSideDist;
787
- if (rate > expandRate[i]) expandRate[i] = rate;
788
- if (rate > expandRate[j]) expandRate[j] = rate;
789
- }
790
- });
791
- }
792
- verticesSet = verticesSet.map((vertex, index) => {
793
- const rate = expandRate[index];
794
- const point = [
795
- (vertex.bakw[0] - centroid.bakw[0]) * rate + centroid.bakw[0],
796
- (vertex.bakw[1] - centroid.bakw[1]) * rate + centroid.bakw[1]
797
- ];
798
- return { forw: vertex.forw, bakw: point };
799
- });
800
-
801
- const verticesList = { forw: [] as any[], bakw: [] as any[] };
802
- for (let i = 0; i < verticesSet.length; i++) {
803
- const forVertex = verticesSet[i].forw;
804
- const bakVertex = verticesSet[i].bakw;
805
- const forVertexFt = createPoint(forVertex, bakVertex, `b${i}`);
806
- const bakVertexFt = counterPoint(forVertexFt);
807
- pointsSet.forw.features.push(forVertexFt);
808
- pointsSet.bakw.features.push(bakVertexFt);
809
- verticesList.forw.push(forVertexFt);
810
- verticesList.bakw.push(bakVertexFt);
811
- }
812
- (this as any).pointsSet = pointsSet;
813
- this.tins = {
814
- forw: rotateVerticesTriangle(
815
- constrainedTin(pointsSet.forw, pointsSet.edges, "target")
816
- )
817
- };
818
-
819
- if (strict == Tin.MODE_STRICT || strict == Tin.MODE_AUTO) {
820
- this.calcurateStrictTin();
821
- }
822
-
823
- if (
824
- strict == Tin.MODE_LOOSE ||
825
- (strict == Tin.MODE_AUTO &&
826
- this.strict_status == Tin.STATUS_ERROR)
827
- ) {
828
- this.tins!.bakw = rotateVerticesTriangle(
829
- constrainedTin(pointsSet.bakw, pointsSet.edges, "target")
830
- );
831
- delete this.kinks;
832
- this.strict_status = Tin.STATUS_LOOSE;
833
- }
834
- this.vertices_params = {
835
- forw: vertexCalc(verticesList.forw, this.centroid!.forw) as any,
836
- bakw: vertexCalc(verticesList.bakw, this.centroid!.bakw) as any
837
- };
838
- this.addIndexedTin();
839
- this.calculatePointsWeight();
840
- }
841
-
842
- /**
843
- * 点の重み付けを計算します
844
- *
845
- * - 各点について周辺の三角形から重みを計算
846
- * - 順方向と逆方向(必要な場合)の重みを計算
847
- * - 重心点の重みも計算
848
- *
849
- * 重みは変換の精度と安定性に影響を与えます
850
- */
851
- calculatePointsWeight() {
852
- const calcTargets: BiDirectionKey[] = ["forw"];
853
- if (this.strict_status == Tin.STATUS_LOOSE) calcTargets.push("bakw");
854
- const weightBuffer: any = {}; // Type of this is not WeightBufferBD
855
-
856
- calcTargets.forEach(target => {
857
- weightBuffer[target] = {};
858
- const alreadyChecked: any = {};
859
- const tin = this.tins![target];
860
- tin!.features.map((tri: Tri) => {
861
- const vtxes = ["a", "b", "c"] as PropertyTriKey[];
862
- for (let i = 0; i < 3; i++) {
863
- const j = (i + 1) % 3;
864
- const vi = vtxes[i];
865
- const vj = vtxes[j];
866
- const indexi = tri.properties![vi].index;
867
- const indexj = tri.properties![vj].index;
868
- const key = [indexi, indexj].sort().join("-");
869
- if (!alreadyChecked[key]) {
870
- const fromi = tri.geometry!.coordinates[0][i];
871
- const fromj = tri.geometry!.coordinates[0][j];
872
- const toi = tri.properties![vi].geom;
873
- const toj = tri.properties![vj].geom;
874
- alreadyChecked[key] = 1;
875
- const weight =
876
- Math.sqrt(
877
- Math.pow(toi[0] - toj[0], 2) +
878
- Math.pow(toi[1] - toj[1], 2)
879
- ) /
880
- Math.sqrt(
881
- Math.pow(fromi[0] - fromj[0], 2) +
882
- Math.pow(fromi[1] - fromj[1], 2)
883
- );
884
- if (!weightBuffer[target]![indexi])
885
- weightBuffer[target][indexi] = {};
886
- if (!weightBuffer[target]![indexj])
887
- weightBuffer[target][indexj] = {};
888
- weightBuffer[target]![indexi][key] = weight;
889
- weightBuffer[target]![indexj][key] = weight;
890
- }
891
- }
892
- })
893
- });
894
-
895
- const pointsWeightBuffer: WeightBufferBD = {};
896
- calcTargets.map(target => {
897
- pointsWeightBuffer[target] = {};
898
- if (this.strict_status == Tin.STATUS_STRICT)
899
- pointsWeightBuffer["bakw"] = {};
900
- Object.keys(weightBuffer[target]).map(vtx => {
901
- pointsWeightBuffer[target]![vtx] = Object.keys(
902
- weightBuffer[target][vtx]
903
- ).reduce((prev, key, idx, arr) => {
904
- prev = prev + weightBuffer[target][vtx][key];
905
- return idx == arr.length - 1 ? prev / arr.length : prev;
906
- }, 0);
907
- if (this.strict_status == Tin.STATUS_STRICT)
908
- pointsWeightBuffer["bakw"]![vtx] =
909
- 1 / pointsWeightBuffer[target]![vtx];
910
- });
911
- pointsWeightBuffer[target]!["c"] = [0, 1, 2, 3].reduce(
912
- (prev, curr) => {
913
- const key = `b${curr}`;
914
- prev = prev + pointsWeightBuffer[target]![key];
915
- return curr == 3 ? prev / 4 : prev;
916
- },
917
- 0
918
- );
919
- if (this.strict_status == Tin.STATUS_STRICT)
920
- pointsWeightBuffer["bakw"]!["c"] =
921
- 1 / pointsWeightBuffer[target]!["c"];
922
- });
923
- this.pointsWeightBuffer = pointsWeightBuffer;
924
- }
925
- }
926
-
927
- // @ts-ignore
928
- if (typeof window !== 'undefined') {
929
- // ブラウザ環境
930
- (window as any).Tin = Tin;
931
- } else if (typeof global !== 'undefined') {
932
- // Node環境
933
- (global as any).Tin = Tin;
934
- }
40
+ // Re-export format_version
41
+ export { format_version } from "@maplat/transform";