@maplibre/geojson-vt 5.0.0 → 5.0.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.
@@ -0,0 +1,1155 @@
1
+ /**
2
+ * calculate simplification data using optimized Douglas-Peucker algorithm
3
+ * @param coords - flat array of coordinates
4
+ * @param first - index of the first coordinate in the segment
5
+ * @param last - index of the last coordinate in the segment
6
+ * @param sqTolerance - square tolerance value
7
+ */
8
+ function simplify(coords, first, last, sqTolerance) {
9
+ let maxSqDist = sqTolerance;
10
+ const mid = first + ((last - first) >> 1);
11
+ let minPosToMid = last - first;
12
+ let index;
13
+ const ax = coords[first];
14
+ const ay = coords[first + 1];
15
+ const bx = coords[last];
16
+ const by = coords[last + 1];
17
+ for (let i = first + 3; i < last; i += 3) {
18
+ const d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);
19
+ if (d > maxSqDist) {
20
+ index = i;
21
+ maxSqDist = d;
22
+ continue;
23
+ }
24
+ if (d === maxSqDist) {
25
+ // a workaround to ensure we choose a pivot close to the middle of the list,
26
+ // reducing recursion depth, for certain degenerate inputs
27
+ // https://github.com/mapbox/geojson-vt/issues/104
28
+ const posToMid = Math.abs(i - mid);
29
+ if (posToMid < minPosToMid) {
30
+ index = i;
31
+ minPosToMid = posToMid;
32
+ }
33
+ }
34
+ }
35
+ if (maxSqDist > sqTolerance) {
36
+ if (index - first > 3)
37
+ simplify(coords, first, index, sqTolerance);
38
+ coords[index + 2] = maxSqDist;
39
+ if (last - index > 3)
40
+ simplify(coords, index, last, sqTolerance);
41
+ }
42
+ }
43
+ /**
44
+ * Claculates the square distance from a point to a segment
45
+ * @param px - x coordinate of the point
46
+ * @param py - y coordinate of the point
47
+ * @param x - x coordinate of the first segment endpoint
48
+ * @param y - y coordinate of the first segment endpoint
49
+ * @param bx - x coordinate of the second segment endpoint
50
+ * @param by - y coordinate of the second segment endpoint
51
+ * @returns square distance from a point to a segment
52
+ */
53
+ function getSqSegDist(px, py, x, y, bx, by) {
54
+ let dx = bx - x;
55
+ let dy = by - y;
56
+ if (dx !== 0 || dy !== 0) {
57
+ const t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
58
+ if (t > 1) {
59
+ x = bx;
60
+ y = by;
61
+ }
62
+ else if (t > 0) {
63
+ x += dx * t;
64
+ y += dy * t;
65
+ }
66
+ }
67
+ dx = px - x;
68
+ dy = py - y;
69
+ return dx * dx + dy * dy;
70
+ }
71
+
72
+ /**
73
+ *
74
+ * @param id - the feature's ID
75
+ * @param type - the feature's type
76
+ * @param geom - the feature's geometry
77
+ * @param tags - the feature's properties
78
+ * @returns the created feature
79
+ */
80
+ function createFeature(id, type, geom, tags) {
81
+ // This is mostly for TypeScript type narrowing
82
+ const data = { type, geom };
83
+ const feature = {
84
+ id: id == null ? null : id,
85
+ type: data.type,
86
+ geometry: data.geom,
87
+ tags,
88
+ minX: Infinity,
89
+ minY: Infinity,
90
+ maxX: -Infinity,
91
+ maxY: -Infinity
92
+ };
93
+ switch (data.type) {
94
+ case 'Point':
95
+ case 'MultiPoint':
96
+ case 'LineString':
97
+ calcLineBBox(feature, data.geom);
98
+ break;
99
+ case 'Polygon':
100
+ // the outer ring (ie [0]) contains all inner rings
101
+ calcLineBBox(feature, data.geom[0]);
102
+ break;
103
+ case 'MultiLineString':
104
+ for (const line of data.geom) {
105
+ calcLineBBox(feature, line);
106
+ }
107
+ break;
108
+ case 'MultiPolygon':
109
+ for (const polygon of data.geom) {
110
+ // the outer ring (ie [0]) contains all inner rings
111
+ calcLineBBox(feature, polygon[0]);
112
+ }
113
+ break;
114
+ }
115
+ return feature;
116
+ }
117
+ function calcLineBBox(feature, geom) {
118
+ for (let i = 0; i < geom.length; i += 3) {
119
+ feature.minX = Math.min(feature.minX, geom[i]);
120
+ feature.minY = Math.min(feature.minY, geom[i + 1]);
121
+ feature.maxX = Math.max(feature.maxX, geom[i]);
122
+ feature.maxY = Math.max(feature.maxY, geom[i + 1]);
123
+ }
124
+ }
125
+
126
+ /**
127
+ * converts GeoJSON feature into an intermediate projected JSON vector format with simplification data
128
+ * @param data
129
+ * @param options
130
+ * @returns
131
+ */
132
+ function convert(data, options) {
133
+ const features = [];
134
+ switch (data.type) {
135
+ case 'FeatureCollection':
136
+ for (let i = 0; i < data.features.length; i++) {
137
+ convertFeature(features, data.features[i], options, i);
138
+ }
139
+ break;
140
+ case 'Feature':
141
+ convertFeature(features, data, options);
142
+ break;
143
+ default:
144
+ convertFeature(features, { geometry: data, properties: undefined }, options);
145
+ }
146
+ return features;
147
+ }
148
+ function convertFeature(features, geojson, options, index) {
149
+ if (!geojson.geometry)
150
+ return;
151
+ if (geojson.geometry.type === 'GeometryCollection') {
152
+ for (const singleGeometry of geojson.geometry.geometries) {
153
+ convertFeature(features, {
154
+ id: geojson.id,
155
+ geometry: singleGeometry,
156
+ properties: geojson.properties
157
+ }, options, index);
158
+ }
159
+ return;
160
+ }
161
+ const coords = geojson.geometry.coordinates;
162
+ if (!coords?.length)
163
+ return;
164
+ const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);
165
+ let id = geojson.id;
166
+ if (options.promoteId) {
167
+ id = geojson.properties?.[options.promoteId];
168
+ }
169
+ else if (options.generateId) {
170
+ id = index || 0;
171
+ }
172
+ switch (geojson.geometry.type) {
173
+ case 'Point': {
174
+ const pointGeometry = [];
175
+ convertPoint(geojson.geometry.coordinates, pointGeometry);
176
+ features.push(createFeature(id, geojson.geometry.type, pointGeometry, geojson.properties));
177
+ return;
178
+ }
179
+ case 'MultiPoint': {
180
+ const multiPointGeometry = [];
181
+ for (const p of geojson.geometry.coordinates) {
182
+ convertPoint(p, multiPointGeometry);
183
+ }
184
+ features.push(createFeature(id, geojson.geometry.type, multiPointGeometry, geojson.properties));
185
+ return;
186
+ }
187
+ case 'LineString': {
188
+ const lineGeometry = [];
189
+ convertLine(geojson.geometry.coordinates, lineGeometry, tolerance, false);
190
+ features.push(createFeature(id, geojson.geometry.type, lineGeometry, geojson.properties));
191
+ return;
192
+ }
193
+ case 'MultiLineString': {
194
+ if (options.lineMetrics) {
195
+ // explode into linestrings in order to track metrics
196
+ for (const line of geojson.geometry.coordinates) {
197
+ const lineGeometry = [];
198
+ convertLine(line, lineGeometry, tolerance, false);
199
+ features.push(createFeature(id, 'LineString', lineGeometry, geojson.properties));
200
+ }
201
+ return;
202
+ }
203
+ const multiLineGeometry = [];
204
+ convertLines(geojson.geometry.coordinates, multiLineGeometry, tolerance, false);
205
+ features.push(createFeature(id, geojson.geometry.type, multiLineGeometry, geojson.properties));
206
+ return;
207
+ }
208
+ case 'Polygon': {
209
+ const polygonGeometry = [];
210
+ convertLines(geojson.geometry.coordinates, polygonGeometry, tolerance, true);
211
+ features.push(createFeature(id, geojson.geometry.type, polygonGeometry, geojson.properties));
212
+ return;
213
+ }
214
+ case 'MultiPolygon': {
215
+ const multiPolygonGeometry = [];
216
+ for (const polygon of geojson.geometry.coordinates) {
217
+ const newPolygon = [];
218
+ convertLines(polygon, newPolygon, tolerance, true);
219
+ multiPolygonGeometry.push(newPolygon);
220
+ }
221
+ features.push(createFeature(id, geojson.geometry.type, multiPolygonGeometry, geojson.properties));
222
+ return;
223
+ }
224
+ default:
225
+ throw new Error('Input data is not a valid GeoJSON object.');
226
+ }
227
+ }
228
+ function convertPoint(coords, out) {
229
+ out.push(projectX(coords[0]), projectY(coords[1]), 0);
230
+ }
231
+ function convertLine(ring, out, tolerance, isPolygon) {
232
+ let x0, y0;
233
+ let size = 0;
234
+ for (let j = 0; j < ring.length; j++) {
235
+ const x = projectX(ring[j][0]);
236
+ const y = projectY(ring[j][1]);
237
+ out.push(x, y, 0);
238
+ if (j > 0) {
239
+ if (isPolygon) {
240
+ size += (x0 * y - x * y0) / 2; // area
241
+ }
242
+ else {
243
+ size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); // length
244
+ }
245
+ }
246
+ x0 = x;
247
+ y0 = y;
248
+ }
249
+ const last = out.length - 3;
250
+ out[2] = 1;
251
+ if (tolerance > 0)
252
+ simplify(out, 0, last, tolerance);
253
+ out[last + 2] = 1;
254
+ out.size = Math.abs(size);
255
+ out.start = 0;
256
+ out.end = out.size;
257
+ }
258
+ function convertLines(rings, out, tolerance, isPolygon) {
259
+ for (let i = 0; i < rings.length; i++) {
260
+ const geom = [];
261
+ convertLine(rings[i], geom, tolerance, isPolygon);
262
+ out.push(geom);
263
+ }
264
+ }
265
+ function projectX(x) {
266
+ return x / 360 + 0.5;
267
+ }
268
+ function projectY(y) {
269
+ const sin = Math.sin(y * Math.PI / 180);
270
+ const y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
271
+ return y2 < 0 ? 0 : y2 > 1 ? 1 : y2;
272
+ }
273
+
274
+ /* clip features between two vertical or horizontal axis-parallel lines:
275
+ * | |
276
+ * ___|___ | /
277
+ * / | \____|____/
278
+ * | |
279
+ *
280
+ * k1 and k2 are the line coordinates
281
+ * axis: 0 for x, 1 for y
282
+ * minAll and maxAll: minimum and maximum coordinate value for all features
283
+ */
284
+ function clip(features, scale, k1, k2, axis, minAll, maxAll, options) {
285
+ k1 /= scale;
286
+ k2 /= scale;
287
+ if (minAll >= k1 && maxAll < k2) { // trivial accept
288
+ return features;
289
+ }
290
+ if (maxAll < k1 || minAll >= k2) { // trivial reject
291
+ return null;
292
+ }
293
+ const clipped = [];
294
+ for (const feature of features) {
295
+ const min = axis === 0 ? feature.minX : feature.minY;
296
+ const max = axis === 0 ? feature.maxX : feature.maxY;
297
+ if (min >= k1 && max < k2) { // trivial accept
298
+ clipped.push(feature);
299
+ continue;
300
+ }
301
+ if (max < k1 || min >= k2) { // trivial reject
302
+ continue;
303
+ }
304
+ switch (feature.type) {
305
+ case 'Point':
306
+ case 'MultiPoint': {
307
+ const pointGeometry = [];
308
+ clipPoints(feature.geometry, pointGeometry, k1, k2, axis);
309
+ if (!pointGeometry.length)
310
+ continue;
311
+ const type = pointGeometry.length === 3 ? 'Point' : 'MultiPoint';
312
+ clipped.push(createFeature(feature.id, type, pointGeometry, feature.tags));
313
+ continue;
314
+ }
315
+ case 'LineString': {
316
+ const lineGeometry = [];
317
+ clipLine(feature.geometry, lineGeometry, k1, k2, axis, false, options.lineMetrics);
318
+ if (!lineGeometry.length)
319
+ continue;
320
+ if (options.lineMetrics) {
321
+ for (const line of lineGeometry) {
322
+ clipped.push(createFeature(feature.id, feature.type, line, feature.tags));
323
+ }
324
+ continue;
325
+ }
326
+ if (lineGeometry.length > 1) {
327
+ clipped.push(createFeature(feature.id, "MultiLineString", lineGeometry, feature.tags));
328
+ continue;
329
+ }
330
+ clipped.push(createFeature(feature.id, feature.type, lineGeometry[0], feature.tags));
331
+ continue;
332
+ }
333
+ case 'MultiLineString': {
334
+ const multiLineGeometry = [];
335
+ clipLines(feature.geometry, multiLineGeometry, k1, k2, axis, false);
336
+ if (!multiLineGeometry.length)
337
+ continue;
338
+ if (multiLineGeometry.length === 1) {
339
+ clipped.push(createFeature(feature.id, "LineString", multiLineGeometry[0], feature.tags));
340
+ continue;
341
+ }
342
+ clipped.push(createFeature(feature.id, feature.type, multiLineGeometry, feature.tags));
343
+ continue;
344
+ }
345
+ case 'Polygon': {
346
+ const polygonGeometry = [];
347
+ clipLines(feature.geometry, polygonGeometry, k1, k2, axis, true);
348
+ if (!polygonGeometry.length)
349
+ continue;
350
+ clipped.push(createFeature(feature.id, feature.type, polygonGeometry, feature.tags));
351
+ continue;
352
+ }
353
+ case 'MultiPolygon': {
354
+ const multiPolygonGeometry = [];
355
+ for (const polygon of feature.geometry) {
356
+ const newPolygon = [];
357
+ clipLines(polygon, newPolygon, k1, k2, axis, true);
358
+ if (newPolygon.length)
359
+ multiPolygonGeometry.push(newPolygon);
360
+ }
361
+ if (!multiPolygonGeometry.length)
362
+ continue;
363
+ clipped.push(createFeature(feature.id, feature.type, multiPolygonGeometry, feature.tags));
364
+ continue;
365
+ }
366
+ }
367
+ }
368
+ if (!clipped.length)
369
+ return null;
370
+ return clipped;
371
+ }
372
+ function clipPoints(geom, newGeom, k1, k2, axis) {
373
+ for (let i = 0; i < geom.length; i += 3) {
374
+ const a = geom[i + axis];
375
+ if (a >= k1 && a <= k2) {
376
+ addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]);
377
+ }
378
+ }
379
+ }
380
+ function clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) {
381
+ let slice = newSlice(geom);
382
+ const intersect = axis === 0 ? intersectX : intersectY;
383
+ let len = geom.start;
384
+ let segLen, t;
385
+ for (let i = 0; i < geom.length - 3; i += 3) {
386
+ const ax = geom[i];
387
+ const ay = geom[i + 1];
388
+ const az = geom[i + 2];
389
+ const bx = geom[i + 3];
390
+ const by = geom[i + 4];
391
+ const a = axis === 0 ? ax : ay;
392
+ const b = axis === 0 ? bx : by;
393
+ let exited = false;
394
+ if (trackMetrics)
395
+ segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));
396
+ if (a < k1) {
397
+ // ---|--> | (line enters the clip region from the left)
398
+ if (b > k1) {
399
+ t = intersect(slice, ax, ay, bx, by, k1);
400
+ if (trackMetrics)
401
+ slice.start = len + segLen * t;
402
+ }
403
+ }
404
+ else if (a > k2) {
405
+ // | <--|--- (line enters the clip region from the right)
406
+ if (b < k2) {
407
+ t = intersect(slice, ax, ay, bx, by, k2);
408
+ if (trackMetrics)
409
+ slice.start = len + segLen * t;
410
+ }
411
+ }
412
+ else {
413
+ addPoint(slice, ax, ay, az);
414
+ }
415
+ if (b < k1 && a >= k1) {
416
+ // <--|--- | or <--|-----|--- (line exits the clip region on the left)
417
+ t = intersect(slice, ax, ay, bx, by, k1);
418
+ exited = true;
419
+ }
420
+ if (b > k2 && a <= k2) {
421
+ // | ---|--> or ---|-----|--> (line exits the clip region on the right)
422
+ t = intersect(slice, ax, ay, bx, by, k2);
423
+ exited = true;
424
+ }
425
+ if (!isPolygon && exited) {
426
+ if (trackMetrics)
427
+ slice.end = len + segLen * t;
428
+ newGeom.push(slice);
429
+ slice = newSlice(geom);
430
+ }
431
+ if (trackMetrics)
432
+ len += segLen;
433
+ }
434
+ // add the last point
435
+ let last = geom.length - 3;
436
+ const ax = geom[last];
437
+ const ay = geom[last + 1];
438
+ const az = geom[last + 2];
439
+ const a = axis === 0 ? ax : ay;
440
+ if (a >= k1 && a <= k2)
441
+ addPoint(slice, ax, ay, az);
442
+ // close the polygon if its endpoints are not the same after clipping
443
+ last = slice.length - 3;
444
+ if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) {
445
+ addPoint(slice, slice[0], slice[1], slice[2]);
446
+ }
447
+ // add the final slice
448
+ if (slice.length) {
449
+ newGeom.push(slice);
450
+ }
451
+ }
452
+ function newSlice(line) {
453
+ const slice = [];
454
+ slice.size = line.size;
455
+ slice.start = line.start;
456
+ slice.end = line.end;
457
+ return slice;
458
+ }
459
+ function clipLines(geom, newGeom, k1, k2, axis, isPolygon) {
460
+ for (const line of geom) {
461
+ clipLine(line, newGeom, k1, k2, axis, isPolygon, false);
462
+ }
463
+ }
464
+ function addPoint(out, x, y, z) {
465
+ out.push(x, y, z);
466
+ }
467
+ function intersectX(out, ax, ay, bx, by, x) {
468
+ const t = (x - ax) / (bx - ax);
469
+ addPoint(out, x, ay + (by - ay) * t, 1);
470
+ return t;
471
+ }
472
+ function intersectY(out, ax, ay, bx, by, y) {
473
+ const t = (y - ay) / (by - ay);
474
+ addPoint(out, ax + (bx - ax) * t, y, 1);
475
+ return t;
476
+ }
477
+
478
+ function wrap(features, options) {
479
+ const buffer = options.buffer / options.extent;
480
+ let merged = features;
481
+ const left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options); // left world copy
482
+ const right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options); // right world copy
483
+ if (!left && !right)
484
+ return merged;
485
+ merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || []; // center world copy
486
+ if (left)
487
+ merged = shiftFeatureCoords(left, 1).concat(merged); // merge left into center
488
+ if (right)
489
+ merged = merged.concat(shiftFeatureCoords(right, -1)); // merge right into center
490
+ return merged;
491
+ }
492
+ function shiftFeatureCoords(features, offset) {
493
+ const newFeatures = [];
494
+ for (const feature of features) {
495
+ switch (feature.type) {
496
+ case 'Point':
497
+ case 'MultiPoint':
498
+ case 'LineString': {
499
+ const newGeometry = shiftCoords(feature.geometry, offset);
500
+ newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
501
+ continue;
502
+ }
503
+ case 'MultiLineString':
504
+ case 'Polygon': {
505
+ const newGeometry = [];
506
+ for (const line of feature.geometry) {
507
+ newGeometry.push(shiftCoords(line, offset));
508
+ }
509
+ newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
510
+ continue;
511
+ }
512
+ case 'MultiPolygon': {
513
+ const newGeometry = [];
514
+ for (const polygon of feature.geometry) {
515
+ const newPolygon = [];
516
+ for (const line of polygon) {
517
+ newPolygon.push(shiftCoords(line, offset));
518
+ }
519
+ newGeometry.push(newPolygon);
520
+ }
521
+ newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
522
+ continue;
523
+ }
524
+ }
525
+ }
526
+ return newFeatures;
527
+ }
528
+ function shiftCoords(points, offset) {
529
+ const newPoints = [];
530
+ newPoints.size = points.size;
531
+ if (points.start !== undefined) {
532
+ newPoints.start = points.start;
533
+ newPoints.end = points.end;
534
+ }
535
+ for (let i = 0; i < points.length; i += 3) {
536
+ newPoints.push(points[i] + offset, points[i + 1], points[i + 2]);
537
+ }
538
+ return newPoints;
539
+ }
540
+
541
+ /**
542
+ * Transforms the coordinates of each feature in the given tile from
543
+ * mercator-projected space into (extent x extent) tile space.
544
+ * @param tile - the tile to transform, this gets modified in place
545
+ * @param extent - the tile extent (usually 4096)
546
+ * @returns the transformed tile
547
+ */
548
+ function transformTile(tile, extent) {
549
+ if (tile.transformed) {
550
+ return tile;
551
+ }
552
+ const z2 = 1 << tile.z;
553
+ const tx = tile.x;
554
+ const ty = tile.y;
555
+ for (const feature of tile.features) {
556
+ const geom = feature.geometry;
557
+ const type = feature.type;
558
+ feature.geometry = [];
559
+ if (type === 1) {
560
+ for (let j = 0; j < geom.length; j += 2) {
561
+ feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty));
562
+ }
563
+ continue;
564
+ }
565
+ for (const singleGeom of geom) {
566
+ const ring = [];
567
+ for (let k = 0; k < singleGeom.length; k += 2) {
568
+ ring.push(transformPoint(singleGeom[k], singleGeom[k + 1], extent, z2, tx, ty));
569
+ }
570
+ feature.geometry.push(ring);
571
+ }
572
+ }
573
+ tile.transformed = true;
574
+ return tile;
575
+ }
576
+ function transformPoint(x, y, extent, z2, tx, ty) {
577
+ return [
578
+ Math.round(extent * (x * z2 - tx)),
579
+ Math.round(extent * (y * z2 - ty))
580
+ ];
581
+ }
582
+
583
+ /**
584
+ * Creates a tile object from the given features
585
+ * @param features - the features to include in the tile
586
+ * @param z
587
+ * @param tx
588
+ * @param ty
589
+ * @param options - the options object
590
+ * @returns the created tile
591
+ */
592
+ function createTile(features, z, tx, ty, options) {
593
+ const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
594
+ const tile = {
595
+ features: [],
596
+ numPoints: 0,
597
+ numSimplified: 0,
598
+ numFeatures: features.length,
599
+ source: null,
600
+ x: tx,
601
+ y: ty,
602
+ z,
603
+ transformed: false,
604
+ minX: 2,
605
+ minY: 1,
606
+ maxX: -1,
607
+ maxY: 0
608
+ };
609
+ for (const feature of features) {
610
+ addFeature(tile, feature, tolerance, options);
611
+ }
612
+ return tile;
613
+ }
614
+ function addFeature(tile, feature, tolerance, options) {
615
+ const simplified = [];
616
+ tile.minX = Math.min(tile.minX, feature.minX);
617
+ tile.minY = Math.min(tile.minY, feature.minY);
618
+ tile.maxX = Math.max(tile.maxX, feature.maxX);
619
+ tile.maxY = Math.max(tile.maxY, feature.maxY);
620
+ switch (feature.type) {
621
+ case 'Point':
622
+ case 'MultiPoint':
623
+ for (let i = 0; i < feature.geometry.length; i += 3) {
624
+ simplified.push(feature.geometry[i], feature.geometry[i + 1]);
625
+ tile.numPoints++;
626
+ tile.numSimplified++;
627
+ }
628
+ break;
629
+ case 'LineString':
630
+ addLine(simplified, feature.geometry, tile, tolerance, false, false);
631
+ break;
632
+ case 'MultiLineString':
633
+ case 'Polygon':
634
+ for (let i = 0; i < feature.geometry.length; i++) {
635
+ addLine(simplified, feature.geometry[i], tile, tolerance, feature.type === 'Polygon', i === 0);
636
+ }
637
+ break;
638
+ case 'MultiPolygon':
639
+ for (let k = 0; k < feature.geometry.length; k++) {
640
+ const polygon = feature.geometry[k];
641
+ for (let i = 0; i < polygon.length; i++) {
642
+ addLine(simplified, polygon[i], tile, tolerance, true, i === 0);
643
+ }
644
+ }
645
+ break;
646
+ }
647
+ if (!simplified.length)
648
+ return;
649
+ let tags = feature.tags || null;
650
+ if (feature.type === 'LineString' && options.lineMetrics) {
651
+ tags = {};
652
+ for (const key in feature.tags)
653
+ tags[key] = feature.tags[key];
654
+ // HM TODO: replace with geojsonvt
655
+ tags['mapbox_clip_start'] = feature.geometry.start / feature.geometry.size;
656
+ tags['mapbox_clip_end'] = feature.geometry.end / feature.geometry.size;
657
+ }
658
+ const tileFeature = {
659
+ geometry: simplified,
660
+ type: feature.type === 'Polygon' || feature.type === 'MultiPolygon' ? 3 :
661
+ (feature.type === 'LineString' || feature.type === 'MultiLineString' ? 2 : 1),
662
+ tags
663
+ };
664
+ if (feature.id !== null) {
665
+ tileFeature.id = feature.id;
666
+ }
667
+ tile.features.push(tileFeature);
668
+ }
669
+ function addLine(result, geom, tile, tolerance, isPolygon, isOuter) {
670
+ const sqTolerance = tolerance * tolerance;
671
+ if (tolerance > 0 && (geom.size < (isPolygon ? sqTolerance : tolerance))) {
672
+ tile.numPoints += geom.length / 3;
673
+ return;
674
+ }
675
+ const ring = [];
676
+ for (let i = 0; i < geom.length; i += 3) {
677
+ if (tolerance === 0 || geom[i + 2] > sqTolerance) {
678
+ tile.numSimplified++;
679
+ ring.push(geom[i], geom[i + 1]);
680
+ }
681
+ tile.numPoints++;
682
+ }
683
+ if (isPolygon)
684
+ rewind(ring, isOuter);
685
+ result.push(ring);
686
+ }
687
+ function rewind(ring, clockwise) {
688
+ let area = 0;
689
+ for (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) {
690
+ area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);
691
+ }
692
+ if (area > 0 !== clockwise)
693
+ return;
694
+ for (let i = 0, len = ring.length; i < len / 2; i += 2) {
695
+ const x = ring[i];
696
+ const y = ring[i + 1];
697
+ ring[i] = ring[len - 2 - i];
698
+ ring[i + 1] = ring[len - 1 - i];
699
+ ring[len - 2 - i] = x;
700
+ ring[len - 1 - i] = y;
701
+ }
702
+ }
703
+
704
+ /**
705
+ * Applies a GeoJSON Source Diff to an existing set of simplified features
706
+ * @param source
707
+ * @param dataDiff
708
+ * @param options
709
+ * @returns
710
+ */
711
+ function applySourceDiff(source, dataDiff, options) {
712
+ // convert diff to sets/maps for o(1) lookups
713
+ const diff = diffToHashed(dataDiff);
714
+ // collection for features that will be affected by this update
715
+ let affected = [];
716
+ // full removal - clear everything before applying diff
717
+ if (diff.removeAll) {
718
+ affected = source;
719
+ source = [];
720
+ }
721
+ // remove/add features and collect affected ones
722
+ if (diff.remove.size || diff.add.size) {
723
+ const removeFeatures = [];
724
+ // collect source features to be removed
725
+ for (const feature of source) {
726
+ const { id } = feature;
727
+ // explicit feature removal
728
+ if (diff.remove.has(id)) {
729
+ removeFeatures.push(feature);
730
+ // feature with duplicate id being added
731
+ }
732
+ else if (diff.add.has(id)) {
733
+ removeFeatures.push(feature);
734
+ }
735
+ }
736
+ // collect affected and remove from source
737
+ if (removeFeatures.length) {
738
+ affected.push(...removeFeatures);
739
+ const removeIds = new Set(removeFeatures.map(f => f.id));
740
+ source = source.filter(f => !removeIds.has(f.id));
741
+ }
742
+ // convert and add new features
743
+ if (diff.add.size) {
744
+ // projects and adds simplification info
745
+ let addFeatures = convert({ type: 'FeatureCollection', features: Array.from(diff.add.values()) }, options);
746
+ // wraps features (ie extreme west and extreme east)
747
+ addFeatures = wrap(addFeatures, options);
748
+ affected.push(...addFeatures);
749
+ source.push(...addFeatures);
750
+ }
751
+ }
752
+ if (diff.update.size) {
753
+ for (const [id, update] of diff.update) {
754
+ const featureIndex = source.findIndex(f => f.id === id);
755
+ if (featureIndex === -1)
756
+ continue;
757
+ const feature = source[featureIndex];
758
+ // get updated geojsonvt simplified feature
759
+ const updatedFeature = getUpdatedFeature(feature, update, options);
760
+ if (!updatedFeature)
761
+ continue;
762
+ // track both features for invalidation
763
+ affected.push(feature, updatedFeature);
764
+ // replace old feature with updated feature
765
+ source[featureIndex] = updatedFeature;
766
+ }
767
+ }
768
+ return { affected, source };
769
+ }
770
+ // return an updated geojsonvt simplified feature
771
+ function getUpdatedFeature(vtFeature, update, options) {
772
+ const changeGeometry = !!update.newGeometry;
773
+ const changeProps = update.removeAllProperties ||
774
+ update.removeProperties?.length > 0 ||
775
+ update.addOrUpdateProperties?.length > 0;
776
+ // if geometry changed, need to create new geojson feature and convert to simplified format
777
+ if (changeGeometry) {
778
+ const geojsonFeature = {
779
+ type: 'Feature',
780
+ id: vtFeature.id,
781
+ geometry: update.newGeometry,
782
+ properties: changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags
783
+ };
784
+ // projects and adds simplification info
785
+ let features = convert({ type: 'FeatureCollection', features: [geojsonFeature] }, options);
786
+ // wraps features (ie extreme west and extreme east)
787
+ features = wrap(features, options);
788
+ return features[0];
789
+ }
790
+ // only properties changed - update tags directly
791
+ if (changeProps) {
792
+ const feature = { ...vtFeature };
793
+ feature.tags = applyPropertyUpdates(feature.tags, update);
794
+ return feature;
795
+ }
796
+ return null;
797
+ }
798
+ /**
799
+ * helper to apply property updates from a diff update object to a properties object
800
+ */
801
+ function applyPropertyUpdates(tags, update) {
802
+ if (update.removeAllProperties) {
803
+ return {};
804
+ }
805
+ const properties = { ...tags || {} };
806
+ if (update.removeProperties) {
807
+ for (const key of update.removeProperties) {
808
+ delete properties[key];
809
+ }
810
+ }
811
+ if (update.addOrUpdateProperties) {
812
+ for (const { key, value } of update.addOrUpdateProperties) {
813
+ properties[key] = value;
814
+ }
815
+ }
816
+ return properties;
817
+ }
818
+ /**
819
+ * Convert a GeoJSON Source Diff to an idempotent hashed representation using Sets and Maps
820
+ */
821
+ function diffToHashed(diff) {
822
+ if (!diff)
823
+ return {
824
+ remove: new Set(),
825
+ add: new Map(),
826
+ update: new Map()
827
+ };
828
+ const hashed = {
829
+ removeAll: diff.removeAll,
830
+ remove: new Set(diff.remove || []),
831
+ add: new Map(diff.add?.map(feature => [feature.id, feature])),
832
+ update: new Map(diff.update?.map(update => [update.id, update]))
833
+ };
834
+ return hashed;
835
+ }
836
+
837
+ const defaultOptions = {
838
+ maxZoom: 14,
839
+ indexMaxZoom: 5,
840
+ indexMaxPoints: 100000,
841
+ tolerance: 3,
842
+ extent: 4096,
843
+ buffer: 64,
844
+ lineMetrics: false,
845
+ promoteId: null,
846
+ generateId: false,
847
+ updateable: false,
848
+ debug: 0
849
+ };
850
+ /**
851
+ * Main class for creating and managing a vector tile index from GeoJSON data.
852
+ */
853
+ class GeoJSONVT {
854
+ options;
855
+ /** @internal */
856
+ tiles;
857
+ tileCoords;
858
+ /** @internal */
859
+ stats = {};
860
+ /** @internal */
861
+ total = 0;
862
+ source;
863
+ constructor(data, options) {
864
+ options = this.options = Object.assign({}, defaultOptions, options);
865
+ const debug = options.debug;
866
+ if (debug)
867
+ console.time('preprocess data');
868
+ if (options.maxZoom < 0 || options.maxZoom > 24)
869
+ throw new Error('maxZoom should be in the 0-24 range');
870
+ if (options.promoteId && options.generateId)
871
+ throw new Error('promoteId and generateId cannot be used together.');
872
+ // projects and adds simplification info
873
+ let features = convert(data, options);
874
+ // tiles and tileCoords are part of the public API
875
+ this.tiles = {};
876
+ this.tileCoords = [];
877
+ if (debug) {
878
+ console.timeEnd('preprocess data');
879
+ console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);
880
+ console.time('generate tiles');
881
+ this.stats = {};
882
+ this.total = 0;
883
+ }
884
+ // wraps features (ie extreme west and extreme east)
885
+ features = wrap(features, options);
886
+ // start slicing from the top tile down
887
+ if (features.length) {
888
+ this.splitTile(features, 0, 0, 0);
889
+ }
890
+ // for updateable indexes, store a copy of the original simplified features
891
+ if (options.updateable) {
892
+ this.source = features;
893
+ }
894
+ if (debug) {
895
+ if (features.length)
896
+ console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints);
897
+ console.timeEnd('generate tiles');
898
+ console.log('tiles generated:', this.total, JSON.stringify(this.stats));
899
+ }
900
+ }
901
+ /**
902
+ * splits features from a parent tile to sub-tiles.
903
+ * z, x, and y are the coordinates of the parent tile
904
+ * cz, cx, and cy are the coordinates of the target tile
905
+ *
906
+ * If no target tile is specified, splitting stops when we reach the maximum
907
+ * zoom or the number of points is low as specified in the options.
908
+ * @internal
909
+ * @param features - features to split
910
+ * @param z - tile zoom level
911
+ * @param x - tile x coordinate
912
+ * @param y - tile y coordinate
913
+ * @param cz - target tile zoom level
914
+ * @param cx - target tile x coordinate
915
+ * @param cy - target tile y coordinate
916
+ */
917
+ splitTile(features, z, x, y, cz, cx, cy) {
918
+ const stack = [features, z, x, y];
919
+ const options = this.options;
920
+ const debug = options.debug;
921
+ // avoid recursion by using a processing queue
922
+ while (stack.length) {
923
+ y = stack.pop();
924
+ x = stack.pop();
925
+ z = stack.pop();
926
+ features = stack.pop();
927
+ const z2 = 1 << z;
928
+ const id = toID(z, x, y);
929
+ let tile = this.tiles[id];
930
+ if (!tile) {
931
+ if (debug > 1)
932
+ console.time('creation');
933
+ tile = this.tiles[id] = createTile(features, z, x, y, options);
934
+ this.tileCoords.push({ z, x, y, id });
935
+ if (debug) {
936
+ if (debug > 1) {
937
+ console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
938
+ console.timeEnd('creation');
939
+ }
940
+ const key = `z${z}`;
941
+ this.stats[key] = (this.stats[key] || 0) + 1;
942
+ this.total++;
943
+ }
944
+ }
945
+ // save reference to original geometry in tile so that we can drill down later if we stop now
946
+ tile.source = features;
947
+ // if it's the first-pass tiling
948
+ if (cz == null) {
949
+ // stop tiling if we reached max zoom, or if the tile is too simple
950
+ if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints)
951
+ continue;
952
+ // if a drilldown to a specific tile
953
+ }
954
+ else if (z === options.maxZoom || z === cz) {
955
+ // stop tiling if we reached base zoom or our target tile zoom
956
+ continue;
957
+ }
958
+ else if (cz != null) {
959
+ // stop tiling if it's not an ancestor of the target tile
960
+ const zoomSteps = cz - z;
961
+ if (x !== cx >> zoomSteps || y !== cy >> zoomSteps)
962
+ continue;
963
+ }
964
+ // if we slice further down, no need to keep source geometry
965
+ tile.source = null;
966
+ if (!features.length)
967
+ continue;
968
+ if (debug > 1)
969
+ console.time('clipping');
970
+ // values we'll use for clipping
971
+ const k1 = 0.5 * options.buffer / options.extent;
972
+ const k2 = 0.5 - k1;
973
+ const k3 = 0.5 + k1;
974
+ const k4 = 1 + k1;
975
+ let tl = null;
976
+ let bl = null;
977
+ let tr = null;
978
+ let br = null;
979
+ const left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);
980
+ const right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options);
981
+ if (left) {
982
+ tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
983
+ bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
984
+ }
985
+ if (right) {
986
+ tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
987
+ br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
988
+ }
989
+ if (debug > 1)
990
+ console.timeEnd('clipping');
991
+ stack.push(tl || [], z + 1, x * 2, y * 2);
992
+ stack.push(bl || [], z + 1, x * 2, y * 2 + 1);
993
+ stack.push(tr || [], z + 1, x * 2 + 1, y * 2);
994
+ stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);
995
+ }
996
+ }
997
+ /**
998
+ * Given z, x, and y tile coordinates, returns the corresponding tile with geometries in tile coordinates, much like MVT data is stored.
999
+ * @param z - tile zoom level
1000
+ * @param x - tile x coordinate
1001
+ * @param y - tile y coordinate
1002
+ * @returns the transformed tile or null if not found
1003
+ */
1004
+ getTile(z, x, y) {
1005
+ z = +z;
1006
+ x = +x;
1007
+ y = +y;
1008
+ const options = this.options;
1009
+ const { extent, debug } = options;
1010
+ if (z < 0 || z > 24)
1011
+ return null;
1012
+ const z2 = 1 << z;
1013
+ x = (x + z2) & (z2 - 1); // wrap tile x coordinate
1014
+ const id = toID(z, x, y);
1015
+ if (this.tiles[id]) {
1016
+ return transformTile(this.tiles[id], extent);
1017
+ }
1018
+ if (debug > 1)
1019
+ console.log('drilling down to z%d-%d-%d', z, x, y);
1020
+ let z0 = z;
1021
+ let x0 = x;
1022
+ let y0 = y;
1023
+ let parent;
1024
+ while (!parent && z0 > 0) {
1025
+ z0--;
1026
+ x0 = x0 >> 1;
1027
+ y0 = y0 >> 1;
1028
+ parent = this.tiles[toID(z0, x0, y0)];
1029
+ }
1030
+ if (!parent?.source)
1031
+ return null;
1032
+ // if we found a parent tile containing the original geometry, we can drill down from it
1033
+ if (debug > 1) {
1034
+ console.log('found parent tile z%d-%d-%d', z0, x0, y0);
1035
+ console.time('drilling down');
1036
+ }
1037
+ this.splitTile(parent.source, z0, x0, y0, z, x, y);
1038
+ if (debug > 1)
1039
+ console.timeEnd('drilling down');
1040
+ if (!this.tiles[id])
1041
+ return null;
1042
+ return transformTile(this.tiles[id], extent);
1043
+ }
1044
+ /**
1045
+ * Invalidates (removes) tiles affected by the provided features
1046
+ * @internal
1047
+ * @param features
1048
+ */
1049
+ invalidateTiles(features) {
1050
+ const options = this.options;
1051
+ const { debug } = options;
1052
+ // calculate bounding box of all features for trivial reject
1053
+ let minX = Infinity;
1054
+ let maxX = -Infinity;
1055
+ let minY = Infinity;
1056
+ let maxY = -Infinity;
1057
+ for (const feature of features) {
1058
+ minX = Math.min(minX, feature.minX);
1059
+ maxX = Math.max(maxX, feature.maxX);
1060
+ minY = Math.min(minY, feature.minY);
1061
+ maxY = Math.max(maxY, feature.maxY);
1062
+ }
1063
+ // tile buffer clipping value - not halved as in splitTile above because checking against tile's own extent
1064
+ const k1 = options.buffer / options.extent;
1065
+ // track removed tile ids for o(1) lookup
1066
+ const removedLookup = new Set();
1067
+ // iterate through existing tiles and remove ones that are affected by features
1068
+ for (const id in this.tiles) {
1069
+ const tile = this.tiles[id];
1070
+ // calculate tile bounds including buffer
1071
+ const z2 = 1 << tile.z;
1072
+ const tileMinX = (tile.x - k1) / z2;
1073
+ const tileMaxX = (tile.x + 1 + k1) / z2;
1074
+ const tileMinY = (tile.y - k1) / z2;
1075
+ const tileMaxY = (tile.y + 1 + k1) / z2;
1076
+ // trivial reject if feature bounds don't intersect tile
1077
+ if (maxX < tileMinX || minX >= tileMaxX ||
1078
+ maxY < tileMinY || minY >= tileMaxY) {
1079
+ continue;
1080
+ }
1081
+ // check if any feature intersects with the tile
1082
+ let intersects = false;
1083
+ for (const feature of features) {
1084
+ if (feature.maxX >= tileMinX && feature.minX < tileMaxX &&
1085
+ feature.maxY >= tileMinY && feature.minY < tileMaxY) {
1086
+ intersects = true;
1087
+ break;
1088
+ }
1089
+ }
1090
+ if (!intersects)
1091
+ continue;
1092
+ if (debug) {
1093
+ if (debug > 1) {
1094
+ console.log('invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', tile.z, tile.x, tile.y, tile.numFeatures, tile.numPoints, tile.numSimplified);
1095
+ }
1096
+ const key = `z${tile.z}`;
1097
+ this.stats[key] = (this.stats[key] || 0) - 1;
1098
+ this.total--;
1099
+ }
1100
+ delete this.tiles[id];
1101
+ removedLookup.add(id);
1102
+ }
1103
+ // remove tile coords that are no longer in the index
1104
+ if (removedLookup.size) {
1105
+ this.tileCoords = this.tileCoords.filter(c => !removedLookup.has(c.id));
1106
+ }
1107
+ }
1108
+ /**
1109
+ * Updates the tile index by adding and/or removing geojson features
1110
+ * invalidates tiles that are affected by the update for regeneration on next getTile call.
1111
+ * @param diff - the source diff object
1112
+ */
1113
+ updateData(diff) {
1114
+ const options = this.options;
1115
+ const debug = options.debug;
1116
+ if (!options.updateable)
1117
+ throw new Error('to update tile geojson `updateable` option must be set to true');
1118
+ // apply diff and collect affected features and updated source that will be used to invalidate tiles
1119
+ const { affected, source } = applySourceDiff(this.source, diff, options);
1120
+ // nothing has changed
1121
+ if (!affected.length)
1122
+ return;
1123
+ // update source with new simplified feature set
1124
+ this.source = source;
1125
+ if (debug > 1) {
1126
+ console.log('invalidating tiles');
1127
+ console.time('invalidating');
1128
+ }
1129
+ this.invalidateTiles(affected);
1130
+ if (debug > 1)
1131
+ console.timeEnd('invalidating');
1132
+ // re-generate root tile with updated feature set
1133
+ const [z, x, y] = [0, 0, 0];
1134
+ const rootTile = createTile(this.source, z, x, y, this.options);
1135
+ rootTile.source = this.source;
1136
+ // update tile index with new root tile - ready for getTile calls
1137
+ const id = toID(z, x, y);
1138
+ this.tiles[id] = rootTile;
1139
+ this.tileCoords.push({ z, x, y, id });
1140
+ if (debug) {
1141
+ const key = `z${z}`;
1142
+ this.stats[key] = (this.stats[key] || 0) + 1;
1143
+ this.total++;
1144
+ }
1145
+ }
1146
+ }
1147
+ function toID(z, x, y) {
1148
+ return (((1 << z) * y + x) * 32) + z;
1149
+ }
1150
+ function geojsonvt(data, options) {
1151
+ return new GeoJSONVT(data, options);
1152
+ }
1153
+
1154
+ export { geojsonvt as default };
1155
+ //# sourceMappingURL=geojson-vt.mjs.map