@tangram.gl/basemap-layers 0.0.0 → 10.0.0-alpha.3
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/README.md +12 -7
- package/THIRD-PARTY-NOTICES.md +7 -5
- package/dist/geojson-task-worker.js +3166 -0
- package/dist/geojson-task-worker.js.map +6 -0
- package/dist/geojson-worker.js +1089 -7
- package/dist/geojson-worker.js.map +3 -3
- package/dist/index.cjs +9588 -2093
- package/dist/index.cjs.map +3 -3
- package/dist/index.js +9599 -2090
- package/dist/index.js.map +3 -3
- package/dist/map-style.cjs +456 -20
- package/dist/map-style.cjs.map +3 -3
- package/dist/map-style.js +456 -19
- package/dist/map-style.js.map +2 -2
- package/dist/types/basemap-error.d.ts +52 -0
- package/dist/types/basemap-layer.d.ts +378 -25
- package/dist/types/basemap-protocol.d.ts +91 -0
- package/dist/types/basemap-request.d.ts +73 -0
- package/dist/types/circle-layer.d.ts +65 -8
- package/dist/types/color-relief-layer.d.ts +184 -0
- package/dist/types/dem-pixels.d.ts +40 -0
- package/dist/types/feature-state.d.ts +55 -0
- package/dist/types/fill-extrusion-lighting-extension.d.ts +1 -2
- package/dist/types/fill-outline-extension.d.ts +2 -3
- package/dist/types/fill-pattern.d.ts +35 -3
- package/dist/types/fill-style-extensions.d.ts +11 -59
- package/dist/types/geojson-resource.d.ts +18 -0
- package/dist/types/geojson-source.d.ts +13 -2
- package/dist/types/geojson-task-handler.d.ts +2 -0
- package/dist/types/geojson-task.d.ts +26 -0
- package/dist/types/geojson-tiler.d.ts +29 -2
- package/dist/types/geojson-worker.d.ts +5 -1
- package/dist/types/globe-horizon-extension.d.ts +2 -45
- package/dist/types/globe-layers.d.ts +141 -45
- package/dist/types/globe-line-angle-extension.d.ts +20 -17
- package/dist/types/glyph-store.d.ts +10 -1
- package/dist/types/heatmap-layer.d.ts +99 -0
- package/dist/types/hillshade-layer.d.ts +159 -27
- package/dist/types/icon-text-fit.d.ts +92 -0
- package/dist/types/image-source-layer.d.ts +142 -0
- package/dist/types/index.d.ts +25 -1
- package/dist/types/line-blur-extension.d.ts +3 -11
- package/dist/types/line-dash-extension.d.ts +53 -0
- package/dist/types/line-gradient-extension.d.ts +69 -0
- package/dist/types/line-metrics.d.ts +24 -0
- package/dist/types/line-pattern-extension.d.ts +50 -0
- package/dist/types/line-shape-extension.d.ts +76 -0
- package/dist/types/map-style-loader.d.ts +1 -1
- package/dist/types/map-style.d.ts +2 -2
- package/dist/types/mvt-label-layer.d.ts +111 -20
- package/dist/types/pmtiles-source.d.ts +38 -0
- package/dist/types/projected-background-layer.d.ts +63 -0
- package/dist/types/projected-bitmap-layer.d.ts +58 -0
- package/dist/types/projected-tile-data.d.ts +16 -0
- package/dist/types/projected-tile-selection.d.ts +72 -0
- package/dist/types/projected-tileset.d.ts +92 -0
- package/dist/types/projected-viewport.d.ts +76 -0
- package/dist/types/raster-color-extension.d.ts +4 -7
- package/dist/types/raster-fade.d.ts +155 -0
- package/dist/types/raster-tile-fingerprint.d.ts +11 -0
- package/dist/types/raster-tile-loader.d.ts +80 -0
- package/dist/types/shader-injection-plugin.d.ts +8 -0
- package/dist/types/source-features.d.ts +58 -0
- package/dist/types/source-tiles.d.ts +32 -0
- package/dist/types/sprite.d.ts +37 -3
- package/dist/types/stretch-icon-layer.d.ts +28 -0
- package/dist/types/style-accessor.d.ts +50 -12
- package/dist/types/style-expression.d.ts +22 -2
- package/dist/types/style-resolver.d.ts +47 -2
- package/dist/types/terrain-query.d.ts +39 -0
- package/dist/types/zoom-load-gate.d.ts +22 -0
- package/dist/types/zoom-paint-extension.d.ts +80 -11
- package/package.json +24 -21
- package/src/basemap-error.ts +82 -0
- package/src/basemap-layer.ts +1289 -101
- package/src/basemap-protocol.ts +353 -0
- package/src/basemap-request.ts +212 -0
- package/src/circle-layer.ts +430 -54
- package/src/color-relief-layer.ts +572 -0
- package/src/dem-pixels.ts +174 -0
- package/src/feature-state.ts +164 -0
- package/src/fill-extrusion-lighting-extension.ts +126 -9
- package/src/fill-outline-extension.ts +4 -4
- package/src/fill-pattern.ts +87 -9
- package/src/fill-style-extensions.ts +114 -44
- package/src/geojson-resource.ts +58 -0
- package/src/geojson-source.ts +106 -85
- package/src/geojson-task-handler.ts +11 -0
- package/src/geojson-task-worker.ts +8 -0
- package/src/geojson-task.ts +34 -0
- package/src/geojson-tiler.ts +270 -4
- package/src/geojson-worker.ts +36 -6
- package/src/globe-horizon-extension.ts +14 -4
- package/src/globe-layers.ts +1905 -406
- package/src/globe-line-angle-extension.ts +183 -23
- package/src/glyph-store.ts +28 -6
- package/src/heatmap-layer.ts +591 -0
- package/src/hillshade-layer.ts +309 -88
- package/src/icon-text-fit.ts +358 -0
- package/src/image-source-layer.ts +380 -0
- package/src/index.ts +58 -1
- package/src/line-blur-extension.ts +14 -12
- package/src/line-dash-extension.ts +303 -0
- package/src/line-gradient-extension.ts +191 -0
- package/src/line-metrics.ts +90 -0
- package/src/line-pattern-extension.ts +173 -0
- package/src/line-shape-extension.ts +272 -0
- package/src/map-style-loader.ts +5 -4
- package/src/map-style.ts +2 -1
- package/src/mvt-label-layer.ts +568 -144
- package/src/pmtiles-source.ts +276 -0
- package/src/projected-background-layer.ts +202 -0
- package/src/projected-bitmap-layer.ts +262 -0
- package/src/projected-tile-data.ts +132 -0
- package/src/projected-tile-selection.ts +605 -0
- package/src/projected-tileset.ts +183 -0
- package/src/projected-viewport.ts +254 -0
- package/src/raster-color-extension.ts +43 -18
- package/src/raster-fade.ts +319 -0
- package/src/raster-tile-fingerprint.ts +31 -0
- package/src/raster-tile-loader.ts +211 -0
- package/src/shader-injection-plugin.ts +25 -0
- package/src/source-features.ts +170 -0
- package/src/source-tiles.ts +102 -0
- package/src/sprite.ts +122 -15
- package/src/stretch-icon-layer.ts +87 -0
- package/src/style-accessor.ts +105 -17
- package/src/style-expression.ts +80 -3
- package/src/style-resolver.ts +200 -22
- package/src/terrain-query.ts +86 -0
- package/src/text-layout.ts +2 -3
- package/src/zoom-load-gate.ts +57 -0
- package/src/zoom-paint-extension.ts +245 -47
- package/dist/types/arabic-shaping.d.ts +0 -7
- package/dist/types/bidi.d.ts +0 -8
- package/dist/types/polylabel.d.ts +0 -17
- package/src/arabic-shaping.ts +0 -366
- package/src/bidi.ts +0 -199
- package/src/polylabel.ts +0 -312
|
@@ -0,0 +1,3166 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
(() => {
|
|
3
|
+
// ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/node/worker_threads-browser.js
|
|
4
|
+
var parentPort = globalThis.process?.getBuiltinModule?.("node:worker_threads")?.parentPort ?? null;
|
|
5
|
+
|
|
6
|
+
// ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-utils/get-transfer-list.js
|
|
7
|
+
function getTransferList(object, recursive = true, transfers) {
|
|
8
|
+
const transfersSet = transfers || /* @__PURE__ */ new Set();
|
|
9
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10
|
+
function visit(value) {
|
|
11
|
+
if (!value || typeof value !== "object" || seen.has(value))
|
|
12
|
+
return;
|
|
13
|
+
seen.add(value);
|
|
14
|
+
if (isTransferable(value))
|
|
15
|
+
transfersSet.add(value);
|
|
16
|
+
else if (ArrayBuffer.isView(value)) {
|
|
17
|
+
if (isTransferable(value.buffer))
|
|
18
|
+
transfersSet.add(value.buffer);
|
|
19
|
+
} else if (recursive && typeof MessageChannel !== "undefined" && value instanceof MessageChannel) {
|
|
20
|
+
visit(value.port1);
|
|
21
|
+
visit(value.port2);
|
|
22
|
+
} else if (recursive && value instanceof Map) {
|
|
23
|
+
for (const [key, item] of value) {
|
|
24
|
+
visit(key);
|
|
25
|
+
visit(item);
|
|
26
|
+
}
|
|
27
|
+
} else if (recursive && value instanceof Set) {
|
|
28
|
+
for (const item of value)
|
|
29
|
+
visit(item);
|
|
30
|
+
} else if (recursive) {
|
|
31
|
+
for (const key of Object.keys(value))
|
|
32
|
+
visit(value[key]);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
visit(object);
|
|
36
|
+
return transfers === void 0 ? Array.from(transfersSet) : [];
|
|
37
|
+
}
|
|
38
|
+
function isTransferable(object) {
|
|
39
|
+
if (!object) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
if (object instanceof ArrayBuffer) {
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
if (typeof MessagePort !== "undefined" && object instanceof MessagePort) {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
if (typeof ImageBitmap !== "undefined" && object instanceof ImageBitmap) {
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
if (typeof OffscreenCanvas !== "undefined" && object instanceof OffscreenCanvas) {
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-body.js
|
|
58
|
+
async function getParentPort() {
|
|
59
|
+
return parentPort;
|
|
60
|
+
}
|
|
61
|
+
var onMessageWrapperMap = /* @__PURE__ */ new Map();
|
|
62
|
+
var WorkerBody = class {
|
|
63
|
+
/** Check that we are actually in a worker thread */
|
|
64
|
+
static async inWorkerThread() {
|
|
65
|
+
const workerGlobalScope = globalThis.WorkerGlobalScope;
|
|
66
|
+
return typeof workerGlobalScope === "function" && globalThis instanceof workerGlobalScope || Boolean(await getParentPort());
|
|
67
|
+
}
|
|
68
|
+
/*
|
|
69
|
+
* (type: WorkerMessageType, payload: WorkerMessagePayload) => any
|
|
70
|
+
*/
|
|
71
|
+
static set onmessage(onMessage) {
|
|
72
|
+
async function handleMessage(message) {
|
|
73
|
+
const parentPort2 = await getParentPort();
|
|
74
|
+
const { type, payload } = parentPort2 ? message : message.data;
|
|
75
|
+
onMessage(type, payload);
|
|
76
|
+
}
|
|
77
|
+
getParentPort().then((parentPort2) => {
|
|
78
|
+
if (parentPort2) {
|
|
79
|
+
parentPort2.on("message", (message) => {
|
|
80
|
+
handleMessage(message);
|
|
81
|
+
});
|
|
82
|
+
parentPort2.on("exit", () => console.debug("Node worker closing"));
|
|
83
|
+
} else {
|
|
84
|
+
globalThis.onmessage = handleMessage;
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
static async addEventListener(onMessage) {
|
|
89
|
+
let onMessageWrapper = onMessageWrapperMap.get(onMessage);
|
|
90
|
+
if (!onMessageWrapper) {
|
|
91
|
+
onMessageWrapper = (message) => {
|
|
92
|
+
const messageData = getWorkerMessageData(message);
|
|
93
|
+
if (!messageData) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
onMessage(messageData.type, messageData.payload);
|
|
97
|
+
};
|
|
98
|
+
onMessageWrapperMap.set(onMessage, onMessageWrapper);
|
|
99
|
+
}
|
|
100
|
+
const parentPort2 = await getParentPort();
|
|
101
|
+
if (parentPort2) {
|
|
102
|
+
parentPort2.on("message", onMessageWrapper);
|
|
103
|
+
} else {
|
|
104
|
+
globalThis.addEventListener("message", onMessageWrapper);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
static async removeEventListener(onMessage) {
|
|
108
|
+
const onMessageWrapper = onMessageWrapperMap.get(onMessage);
|
|
109
|
+
onMessageWrapperMap.delete(onMessage);
|
|
110
|
+
if (!onMessageWrapper) {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const parentPort2 = await getParentPort();
|
|
114
|
+
if (parentPort2) {
|
|
115
|
+
parentPort2.off("message", onMessageWrapper);
|
|
116
|
+
} else {
|
|
117
|
+
globalThis.removeEventListener("message", onMessageWrapper);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Send a message from a worker to creating thread (main thread)
|
|
122
|
+
* @param type
|
|
123
|
+
* @param payload
|
|
124
|
+
*/
|
|
125
|
+
static async postMessage(type, payload, copy = false) {
|
|
126
|
+
const data = { source: "loaders.gl", type, payload };
|
|
127
|
+
const transferList = copy ? [] : getTransferList(payload);
|
|
128
|
+
const parentPort2 = await getParentPort();
|
|
129
|
+
if (parentPort2) {
|
|
130
|
+
parentPort2.postMessage(data, transferList);
|
|
131
|
+
} else {
|
|
132
|
+
globalThis.postMessage(data, transferList);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
function getWorkerMessageData(message) {
|
|
137
|
+
if (!message || typeof message !== "object") {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
const messageData = "data" in message && message.type === "message" ? message.data : message;
|
|
141
|
+
return messageData && typeof messageData.source === "string" && messageData.source.startsWith("loaders.gl") ? messageData : null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/async-queue/async-queue.js
|
|
145
|
+
var AsyncQueue = class {
|
|
146
|
+
constructor() {
|
|
147
|
+
this._values = [];
|
|
148
|
+
this._settlers = [];
|
|
149
|
+
this._closed = false;
|
|
150
|
+
}
|
|
151
|
+
/** Return an async iterator for this queue */
|
|
152
|
+
[Symbol.asyncIterator]() {
|
|
153
|
+
return this;
|
|
154
|
+
}
|
|
155
|
+
/** Push a new value - the async iterator will yield a promise resolved to this value */
|
|
156
|
+
push(value) {
|
|
157
|
+
return this.enqueue(value);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Push a new value - the async iterator will yield a promise resolved to this value
|
|
161
|
+
* Add an error - the async iterator will yield a promise rejected with this value
|
|
162
|
+
*/
|
|
163
|
+
enqueue(value) {
|
|
164
|
+
if (this._closed) {
|
|
165
|
+
throw new Error("Closed");
|
|
166
|
+
}
|
|
167
|
+
if (this._settlers.length > 0) {
|
|
168
|
+
if (this._values.length > 0) {
|
|
169
|
+
throw new Error("Illegal internal state");
|
|
170
|
+
}
|
|
171
|
+
const settler = this._settlers.shift();
|
|
172
|
+
if (value instanceof Error) {
|
|
173
|
+
settler.reject(value);
|
|
174
|
+
} else {
|
|
175
|
+
settler.resolve({ value });
|
|
176
|
+
}
|
|
177
|
+
} else {
|
|
178
|
+
this._values.push(value);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** Indicate that we not waiting for more values - The async iterator will be done */
|
|
182
|
+
close() {
|
|
183
|
+
while (this._settlers.length > 0) {
|
|
184
|
+
const settler = this._settlers.shift();
|
|
185
|
+
settler.resolve({ done: true });
|
|
186
|
+
}
|
|
187
|
+
this._closed = true;
|
|
188
|
+
}
|
|
189
|
+
// ITERATOR IMPLEMENTATION
|
|
190
|
+
/** @returns a Promise for an IteratorResult */
|
|
191
|
+
next() {
|
|
192
|
+
if (this._values.length > 0) {
|
|
193
|
+
const value = this._values.shift();
|
|
194
|
+
if (value instanceof Error) {
|
|
195
|
+
return Promise.reject(value);
|
|
196
|
+
}
|
|
197
|
+
return Promise.resolve({ done: false, value });
|
|
198
|
+
}
|
|
199
|
+
if (this._closed) {
|
|
200
|
+
if (this._settlers.length > 0) {
|
|
201
|
+
throw new Error("Illegal internal state");
|
|
202
|
+
}
|
|
203
|
+
return Promise.resolve({ done: true, value: void 0 });
|
|
204
|
+
}
|
|
205
|
+
return new Promise((resolve, reject) => {
|
|
206
|
+
this._settlers.push({ resolve, reject });
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
// ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/shared-state.js
|
|
212
|
+
var SharedWorkerState = class {
|
|
213
|
+
constructor(buffer) {
|
|
214
|
+
if (typeof SharedArrayBuffer === "undefined" || !(buffer instanceof SharedArrayBuffer) || buffer.byteLength !== 16)
|
|
215
|
+
throw new Error("Expected a 16-byte shared worker control buffer");
|
|
216
|
+
this.buffer = buffer;
|
|
217
|
+
this.values = new Int32Array(buffer);
|
|
218
|
+
}
|
|
219
|
+
get snapshot() {
|
|
220
|
+
return {
|
|
221
|
+
cancelled: Atomics.load(this.values, 0) !== 0,
|
|
222
|
+
completed: Atomics.load(this.values, 1),
|
|
223
|
+
total: Atomics.load(this.values, 2),
|
|
224
|
+
revision: Atomics.load(this.values, 3)
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
cancel() {
|
|
228
|
+
Atomics.store(this.values, 0, 1);
|
|
229
|
+
Atomics.add(this.values, 3, 1);
|
|
230
|
+
Atomics.notify(this.values, 0);
|
|
231
|
+
}
|
|
232
|
+
throwIfCancelled() {
|
|
233
|
+
if (Atomics.load(this.values, 0) !== 0) {
|
|
234
|
+
const error = new Error("Shared worker task was cancelled");
|
|
235
|
+
error.name = "AbortError";
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/** Integer counters for application-defined work; messages still carry phase names and units. */
|
|
240
|
+
setProgress(completed, total = -1) {
|
|
241
|
+
if (!Number.isInteger(completed) || completed < 0 || completed > 2147483647 || !Number.isInteger(total) || total < -1 || total > 2147483647) {
|
|
242
|
+
throw new RangeError("Shared progress requires nonnegative int32 counts (or total -1)");
|
|
243
|
+
}
|
|
244
|
+
Atomics.store(this.values, 1, completed);
|
|
245
|
+
Atomics.store(this.values, 2, total);
|
|
246
|
+
Atomics.add(this.values, 3, 1);
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
// ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/validate-output-ownership.js
|
|
251
|
+
function validateOutputOwnership(ownership) {
|
|
252
|
+
if (ownership !== void 0 && ownership !== "copy" && ownership !== "transfer") {
|
|
253
|
+
throw new Error("Invalid worker output ownership");
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/create-worker.js
|
|
258
|
+
var requestId = 0;
|
|
259
|
+
var activeController = null;
|
|
260
|
+
var activeInputBatches = null;
|
|
261
|
+
var activeOutputAcknowledgements = null;
|
|
262
|
+
async function createWorker(process, processInBatches, preload) {
|
|
263
|
+
if (!await WorkerBody.inWorkerThread()) {
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const context = {
|
|
267
|
+
process: processOnMainThread
|
|
268
|
+
};
|
|
269
|
+
WorkerBody.onmessage = async (type, payload) => {
|
|
270
|
+
if (type === "cancel") {
|
|
271
|
+
activeController?.abort();
|
|
272
|
+
activeInputBatches?.close();
|
|
273
|
+
activeOutputAcknowledgements?.close();
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const controller = type === "process" || type === "process-in-batches" ? new AbortController() : void 0;
|
|
277
|
+
if (controller)
|
|
278
|
+
activeController = controller;
|
|
279
|
+
const startedAt = performance.now();
|
|
280
|
+
const reporter = type === "process" || type === "process-in-batches" ? createProgressReporter() : void 0;
|
|
281
|
+
let sharedState;
|
|
282
|
+
const throwIfAborted = () => {
|
|
283
|
+
controller?.signal.throwIfAborted();
|
|
284
|
+
sharedState?.throwIfCancelled();
|
|
285
|
+
};
|
|
286
|
+
const jobContext = {
|
|
287
|
+
...context,
|
|
288
|
+
signal: controller?.signal,
|
|
289
|
+
sharedState,
|
|
290
|
+
throwIfAborted,
|
|
291
|
+
reportProgress: (progress) => {
|
|
292
|
+
if (!controller?.signal.aborted && !sharedState?.snapshot.cancelled)
|
|
293
|
+
reporter?.report(progress);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
try {
|
|
297
|
+
if (controller && payload.options?.["sharedState"]) {
|
|
298
|
+
sharedState = new SharedWorkerState(payload.options["sharedState"]);
|
|
299
|
+
jobContext.sharedState = sharedState;
|
|
300
|
+
}
|
|
301
|
+
switch (type) {
|
|
302
|
+
case "preload":
|
|
303
|
+
await preload?.();
|
|
304
|
+
WorkerBody.postMessage("done", {});
|
|
305
|
+
break;
|
|
306
|
+
case "process":
|
|
307
|
+
throwIfAborted();
|
|
308
|
+
validateOutputOwnership(payload.options?.["outputOwnership"]);
|
|
309
|
+
if (!process) {
|
|
310
|
+
throw new Error("Worker does not support atomic processing");
|
|
311
|
+
}
|
|
312
|
+
const result = await process(payload.input, payload.options || {}, jobContext, payload.context || {});
|
|
313
|
+
throwIfAborted();
|
|
314
|
+
reporter?.finish();
|
|
315
|
+
await WorkerBody.postMessage("done", {
|
|
316
|
+
result,
|
|
317
|
+
executionMs: performance.now() - startedAt
|
|
318
|
+
}, payload.options?.["outputOwnership"] === "copy");
|
|
319
|
+
break;
|
|
320
|
+
case "process-in-batches":
|
|
321
|
+
throwIfAborted();
|
|
322
|
+
validateOutputOwnership(payload.options?.["outputOwnership"]);
|
|
323
|
+
if (!processInBatches) {
|
|
324
|
+
throw new Error("Worker does not support batched processing");
|
|
325
|
+
}
|
|
326
|
+
const inputBatches = new AsyncQueue();
|
|
327
|
+
const outputAcknowledgements = new AsyncQueue();
|
|
328
|
+
activeInputBatches = inputBatches;
|
|
329
|
+
activeOutputAcknowledgements = outputAcknowledgements;
|
|
330
|
+
try {
|
|
331
|
+
const resultIterator = processInBatches(createDemandDrivenIterator(inputBatches), payload.options || {}, jobContext, payload.context || {});
|
|
332
|
+
for await (const batch of resultIterator) {
|
|
333
|
+
throwIfAborted();
|
|
334
|
+
await WorkerBody.postMessage("output-batch", { result: batch }, payload.options?.["outputOwnership"] === "copy");
|
|
335
|
+
await outputAcknowledgements.next();
|
|
336
|
+
}
|
|
337
|
+
throwIfAborted();
|
|
338
|
+
reporter?.finish();
|
|
339
|
+
await WorkerBody.postMessage("done", { executionMs: performance.now() - startedAt });
|
|
340
|
+
} finally {
|
|
341
|
+
activeInputBatches = null;
|
|
342
|
+
activeOutputAcknowledgements = null;
|
|
343
|
+
}
|
|
344
|
+
break;
|
|
345
|
+
case "input-batch":
|
|
346
|
+
if (!activeInputBatches) {
|
|
347
|
+
throw new Error("Worker has no active batched processing session");
|
|
348
|
+
}
|
|
349
|
+
activeInputBatches.push(payload.input);
|
|
350
|
+
break;
|
|
351
|
+
case "input-done":
|
|
352
|
+
if (!activeInputBatches) {
|
|
353
|
+
throw new Error("Worker has no active batched processing session");
|
|
354
|
+
}
|
|
355
|
+
activeInputBatches.close();
|
|
356
|
+
break;
|
|
357
|
+
case "output-ack":
|
|
358
|
+
if (!activeOutputAcknowledgements) {
|
|
359
|
+
throw new Error("Worker has no active batched processing session");
|
|
360
|
+
}
|
|
361
|
+
activeOutputAcknowledgements.push(void 0);
|
|
362
|
+
break;
|
|
363
|
+
default:
|
|
364
|
+
}
|
|
365
|
+
} catch (error) {
|
|
366
|
+
reporter?.finish(controller?.signal.aborted || sharedState?.snapshot.cancelled);
|
|
367
|
+
const message = error instanceof Error ? error.message : "";
|
|
368
|
+
await WorkerBody.postMessage("error", {
|
|
369
|
+
error: message,
|
|
370
|
+
errorName: error instanceof Error ? error.name : "Error"
|
|
371
|
+
});
|
|
372
|
+
} finally {
|
|
373
|
+
if (controller && activeController === controller)
|
|
374
|
+
activeController = null;
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
await WorkerBody.postMessage("ready", {});
|
|
378
|
+
}
|
|
379
|
+
async function* createDemandDrivenIterator(inputBatches) {
|
|
380
|
+
while (true) {
|
|
381
|
+
await WorkerBody.postMessage("input-request", {});
|
|
382
|
+
const nextBatch = await inputBatches.next();
|
|
383
|
+
if (nextBatch.done) {
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
yield nextBatch.value;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
function processOnMainThread(arrayBuffer, options = {}, jobContext = {}) {
|
|
390
|
+
const signal = activeController?.signal;
|
|
391
|
+
signal?.throwIfAborted();
|
|
392
|
+
return new Promise((resolve, reject) => {
|
|
393
|
+
const id = requestId++;
|
|
394
|
+
const cleanup = () => {
|
|
395
|
+
signal?.removeEventListener("abort", abort);
|
|
396
|
+
void WorkerBody.removeEventListener(onMessage);
|
|
397
|
+
};
|
|
398
|
+
const abort = () => {
|
|
399
|
+
cleanup();
|
|
400
|
+
reject(signal?.reason);
|
|
401
|
+
};
|
|
402
|
+
const onMessage = (type, payload) => {
|
|
403
|
+
if (payload.id !== id)
|
|
404
|
+
return;
|
|
405
|
+
if (type === "done") {
|
|
406
|
+
cleanup();
|
|
407
|
+
resolve(payload.result);
|
|
408
|
+
} else if (type === "error") {
|
|
409
|
+
cleanup();
|
|
410
|
+
reject(payload.error);
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
void WorkerBody.addEventListener(onMessage).then(async () => {
|
|
414
|
+
if (signal?.aborted) {
|
|
415
|
+
abort();
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
419
|
+
await WorkerBody.postMessage("process", {
|
|
420
|
+
id,
|
|
421
|
+
input: arrayBuffer,
|
|
422
|
+
options,
|
|
423
|
+
context: jobContext
|
|
424
|
+
});
|
|
425
|
+
}).catch((error) => {
|
|
426
|
+
cleanup();
|
|
427
|
+
reject(error);
|
|
428
|
+
});
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
function createProgressReporter() {
|
|
432
|
+
let pending2;
|
|
433
|
+
let finished = false;
|
|
434
|
+
let scheduled = false;
|
|
435
|
+
const flush = () => {
|
|
436
|
+
scheduled = false;
|
|
437
|
+
if (pending2) {
|
|
438
|
+
WorkerBody.postMessage("progress", { progress: pending2 });
|
|
439
|
+
pending2 = void 0;
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
return {
|
|
443
|
+
/** Records progress while retaining phase transitions. */
|
|
444
|
+
report(progress) {
|
|
445
|
+
if (finished)
|
|
446
|
+
return;
|
|
447
|
+
if (pending2 && pending2.phase !== progress.phase)
|
|
448
|
+
flush();
|
|
449
|
+
pending2 = { ...progress };
|
|
450
|
+
if (!scheduled) {
|
|
451
|
+
scheduled = true;
|
|
452
|
+
setTimeout(flush, 0);
|
|
453
|
+
}
|
|
454
|
+
},
|
|
455
|
+
/** Flushes final progress and suppresses reports from stale callbacks. */
|
|
456
|
+
finish(discard = false) {
|
|
457
|
+
if (discard)
|
|
458
|
+
pending2 = void 0;
|
|
459
|
+
flush();
|
|
460
|
+
finished = true;
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// ../../node_modules/@math.gl/tasks/dist/worker-utils/index.js
|
|
466
|
+
var import_meta = {};
|
|
467
|
+
var path = typeof __filename === "string" ? __filename.replace(/\\/g, "/") : "";
|
|
468
|
+
var moduleUrl = path ? `file://${path.startsWith("/") ? "" : "/"}${encodeURI(path).replace(/#/g, "%23").replace(/\?/g, "%3F")}` : import_meta.url;
|
|
469
|
+
|
|
470
|
+
// ../../node_modules/@math.gl/tasks/dist/tasks/task-preload.js
|
|
471
|
+
var pending = /* @__PURE__ */ new WeakMap();
|
|
472
|
+
var loaded = /* @__PURE__ */ new WeakSet();
|
|
473
|
+
function preloadTaskCode(task, signal) {
|
|
474
|
+
if (!task.preload)
|
|
475
|
+
return Promise.resolve();
|
|
476
|
+
let promise = pending.get(task);
|
|
477
|
+
if (!promise) {
|
|
478
|
+
promise = Promise.resolve().then(() => task.preload()).then(() => {
|
|
479
|
+
loaded.add(task);
|
|
480
|
+
});
|
|
481
|
+
pending.set(task, promise);
|
|
482
|
+
void promise.catch(() => pending.delete(task));
|
|
483
|
+
}
|
|
484
|
+
return withSignal(promise, signal);
|
|
485
|
+
}
|
|
486
|
+
function withSignal(operation, signal) {
|
|
487
|
+
if (!signal)
|
|
488
|
+
return operation;
|
|
489
|
+
return new Promise((resolve, reject) => {
|
|
490
|
+
const abort = () => {
|
|
491
|
+
signal.removeEventListener("abort", abort);
|
|
492
|
+
reject(signal.reason);
|
|
493
|
+
};
|
|
494
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
495
|
+
if (signal.aborted)
|
|
496
|
+
abort();
|
|
497
|
+
operation.then((value) => {
|
|
498
|
+
signal.removeEventListener("abort", abort);
|
|
499
|
+
resolve(value);
|
|
500
|
+
}, (error) => {
|
|
501
|
+
signal.removeEventListener("abort", abort);
|
|
502
|
+
reject(error);
|
|
503
|
+
});
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// ../../node_modules/@math.gl/tasks/dist/tasks/task-channel.js
|
|
508
|
+
var TaskRequestError = class extends Error {
|
|
509
|
+
};
|
|
510
|
+
var TaskChannel = class {
|
|
511
|
+
constructor(options) {
|
|
512
|
+
this.options = options;
|
|
513
|
+
this.nextId = 1;
|
|
514
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
515
|
+
this.incoming = /* @__PURE__ */ new Map();
|
|
516
|
+
}
|
|
517
|
+
/** Send a request without serializing other in-flight requests. */
|
|
518
|
+
request(operation, value, signal, transfer = []) {
|
|
519
|
+
if (this.failure)
|
|
520
|
+
return Promise.reject(this.failure.reason);
|
|
521
|
+
if (signal?.aborted)
|
|
522
|
+
return Promise.reject(signal.reason);
|
|
523
|
+
const id = this.nextId++;
|
|
524
|
+
return new Promise((resolve, reject) => {
|
|
525
|
+
const abort = () => {
|
|
526
|
+
const pending2 = this.pending.get(id);
|
|
527
|
+
if (!pending2)
|
|
528
|
+
return;
|
|
529
|
+
this.pending.delete(id);
|
|
530
|
+
pending2.cleanup();
|
|
531
|
+
reject(signal?.reason);
|
|
532
|
+
this.send({ source: "math.gl/tasks", kind: "cancel", id });
|
|
533
|
+
};
|
|
534
|
+
this.pending.set(id, {
|
|
535
|
+
resolve,
|
|
536
|
+
reject,
|
|
537
|
+
cleanup: () => signal?.removeEventListener("abort", abort)
|
|
538
|
+
});
|
|
539
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
540
|
+
this.send({ source: "math.gl/tasks", kind: "request", id, operation, value }, transfer);
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
/** Send a one-way notification. */
|
|
544
|
+
emit(operation, value, transfer = []) {
|
|
545
|
+
if (this.failure)
|
|
546
|
+
throw this.failure.reason;
|
|
547
|
+
this.send({ source: "math.gl/tasks", kind: "event", id: 0, operation, value }, transfer);
|
|
548
|
+
}
|
|
549
|
+
/** Dispatch a transport message; unrelated protocols are ignored. */
|
|
550
|
+
receive(message) {
|
|
551
|
+
if (this.failure || message?.source !== "math.gl/tasks")
|
|
552
|
+
return;
|
|
553
|
+
if (message.kind === "failure") {
|
|
554
|
+
const reason = new Error(message.error?.message ?? "Task channel failed");
|
|
555
|
+
this.close(reason);
|
|
556
|
+
this.options.onFailure?.(reason);
|
|
557
|
+
} else if (message.kind === "result" || message.kind === "error") {
|
|
558
|
+
const pending2 = this.pending.get(message.id);
|
|
559
|
+
if (!pending2)
|
|
560
|
+
return;
|
|
561
|
+
this.pending.delete(message.id);
|
|
562
|
+
pending2.cleanup();
|
|
563
|
+
if (message.kind === "result")
|
|
564
|
+
pending2.resolve(message.value);
|
|
565
|
+
else {
|
|
566
|
+
const error = new TaskRequestError(message.error?.message ?? "Task request failed");
|
|
567
|
+
error.name = message.error?.name ?? "Error";
|
|
568
|
+
pending2.reject(error);
|
|
569
|
+
}
|
|
570
|
+
} else if (message.kind === "cancel") {
|
|
571
|
+
this.incoming.get(message.id)?.abort(new DOMException("Task request cancelled", "AbortError"));
|
|
572
|
+
} else if (message.kind === "event") {
|
|
573
|
+
try {
|
|
574
|
+
this.options.handleEvent?.(message.operation, message.value);
|
|
575
|
+
} catch (error) {
|
|
576
|
+
this.fail(error);
|
|
577
|
+
}
|
|
578
|
+
} else if (message.kind === "request") {
|
|
579
|
+
if (this.incoming.has(message.id)) {
|
|
580
|
+
this.fail(new Error("Duplicate task request identifier"));
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
const controller = new AbortController();
|
|
584
|
+
this.incoming.set(message.id, controller);
|
|
585
|
+
void Promise.resolve().then(() => {
|
|
586
|
+
controller.signal.throwIfAborted();
|
|
587
|
+
return this.options.handleRequest(message.operation, message.value, controller.signal);
|
|
588
|
+
}).then((value) => {
|
|
589
|
+
if (!controller.signal.aborted && !this.failure) {
|
|
590
|
+
this.send({ source: "math.gl/tasks", kind: "result", id: message.id, value }, this.options.getResultTransferList?.(value, message.value));
|
|
591
|
+
}
|
|
592
|
+
}).catch((reason) => {
|
|
593
|
+
if (!controller.signal.aborted && !this.failure) {
|
|
594
|
+
this.send({
|
|
595
|
+
source: "math.gl/tasks",
|
|
596
|
+
kind: "error",
|
|
597
|
+
id: message.id,
|
|
598
|
+
error: {
|
|
599
|
+
name: reason instanceof Error ? reason.name : "Error",
|
|
600
|
+
message: reason instanceof Error ? reason.message : String(reason)
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
}).finally(() => this.incoming.delete(message.id));
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
/** Reject all outstanding calls with a common cause and abort incoming callbacks. */
|
|
608
|
+
close(reason = new Error("Task channel closed")) {
|
|
609
|
+
if (this.failure)
|
|
610
|
+
return;
|
|
611
|
+
this.failure = { reason };
|
|
612
|
+
for (const pending2 of this.pending.values()) {
|
|
613
|
+
pending2.cleanup();
|
|
614
|
+
pending2.reject(reason);
|
|
615
|
+
}
|
|
616
|
+
this.pending.clear();
|
|
617
|
+
for (const controller of this.incoming.values())
|
|
618
|
+
controller.abort(reason);
|
|
619
|
+
this.incoming.clear();
|
|
620
|
+
}
|
|
621
|
+
send(message, transfer = []) {
|
|
622
|
+
if (this.failure)
|
|
623
|
+
return;
|
|
624
|
+
try {
|
|
625
|
+
this.options.send(message, transfer);
|
|
626
|
+
} catch (error) {
|
|
627
|
+
this.fail(error);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
/** Invalidate the channel and notify the peer when the transport still works. */
|
|
631
|
+
fail(reason) {
|
|
632
|
+
if (this.failure)
|
|
633
|
+
return;
|
|
634
|
+
this.close(reason);
|
|
635
|
+
try {
|
|
636
|
+
this.options.send({
|
|
637
|
+
source: "math.gl/tasks",
|
|
638
|
+
kind: "failure",
|
|
639
|
+
id: 0,
|
|
640
|
+
error: {
|
|
641
|
+
name: reason instanceof Error ? reason.name : "Error",
|
|
642
|
+
message: reason instanceof Error ? reason.message : String(reason)
|
|
643
|
+
}
|
|
644
|
+
}, []);
|
|
645
|
+
} catch {
|
|
646
|
+
}
|
|
647
|
+
this.options.onFailure?.(reason);
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
// ../../node_modules/@math.gl/tasks/dist/tasks/task-runtime.js
|
|
652
|
+
function assertPayload(value) {
|
|
653
|
+
if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) {
|
|
654
|
+
throw new TypeError("Task payloads must be plain objects with named fields");
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
function clonePayload(value, ownership = "copy") {
|
|
658
|
+
assertPayload(value);
|
|
659
|
+
if (!["copy", "transfer", "share"].includes(ownership))
|
|
660
|
+
throw new TypeError("Invalid input ownership");
|
|
661
|
+
const transfer = getTransferList(value);
|
|
662
|
+
if (ownership === "share" && transfer.length)
|
|
663
|
+
throw new TypeError("Share requires shared storage");
|
|
664
|
+
return structuredClone(value, {
|
|
665
|
+
transfer: ownership === "transfer" ? transfer : []
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
function taskContext(state, context = {}) {
|
|
669
|
+
const signal = context.signal ?? new AbortController().signal;
|
|
670
|
+
return {
|
|
671
|
+
state,
|
|
672
|
+
signal,
|
|
673
|
+
requestHost: async (operation, payload, controls) => {
|
|
674
|
+
signal.throwIfAborted();
|
|
675
|
+
if (!context.requestHost)
|
|
676
|
+
throw new Error("No host request handler configured");
|
|
677
|
+
return context.requestHost(operation, payload, controls);
|
|
678
|
+
},
|
|
679
|
+
emitHost: (operation, payload) => {
|
|
680
|
+
signal.throwIfAborted();
|
|
681
|
+
context.emitHost?.(operation, payload);
|
|
682
|
+
},
|
|
683
|
+
throwIfAborted: () => {
|
|
684
|
+
signal.throwIfAborted();
|
|
685
|
+
context.throwIfAborted?.();
|
|
686
|
+
},
|
|
687
|
+
reportProgress: (progress) => context.reportProgress?.({
|
|
688
|
+
...progress,
|
|
689
|
+
phase: progress.phase ?? "process",
|
|
690
|
+
unit: progress.unit ?? "items"
|
|
691
|
+
})
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
var TaskRuntime = class {
|
|
695
|
+
constructor(task) {
|
|
696
|
+
this.task = task;
|
|
697
|
+
this.initialized = false;
|
|
698
|
+
}
|
|
699
|
+
async initialize(input, context = {}) {
|
|
700
|
+
if (this.initialized)
|
|
701
|
+
throw new Error("Task is already initialized");
|
|
702
|
+
assertPayload(input);
|
|
703
|
+
await preloadTaskCode(this.task, context.signal);
|
|
704
|
+
context.signal?.throwIfAborted();
|
|
705
|
+
this.state = await this.task.initialize?.(input, taskContext(void 0, context));
|
|
706
|
+
this.initialized = true;
|
|
707
|
+
return {};
|
|
708
|
+
}
|
|
709
|
+
async destroy() {
|
|
710
|
+
if (this.initialized) {
|
|
711
|
+
this.initialized = false;
|
|
712
|
+
const state = this.state;
|
|
713
|
+
this.state = void 0;
|
|
714
|
+
if (this.task.initialize)
|
|
715
|
+
await this.task.destroy?.(state);
|
|
716
|
+
}
|
|
717
|
+
return {};
|
|
718
|
+
}
|
|
719
|
+
async process(input, options, context = {}) {
|
|
720
|
+
if (!this.initialized)
|
|
721
|
+
throw new Error("Task is not initialized");
|
|
722
|
+
if (!this.task.process)
|
|
723
|
+
throw new Error("Task has no atomic processor");
|
|
724
|
+
assertPayload(input);
|
|
725
|
+
const result = await this.task.process(input, options, taskContext(this.state, context));
|
|
726
|
+
assertPayload(result);
|
|
727
|
+
return result;
|
|
728
|
+
}
|
|
729
|
+
async *stream(inputs, options, context = {}) {
|
|
730
|
+
if (!this.initialized)
|
|
731
|
+
throw new Error("Task is not initialized");
|
|
732
|
+
if (!this.task.processInBatches)
|
|
733
|
+
throw new Error("Task has no streaming processor");
|
|
734
|
+
for await (const output of this.task.processInBatches(inputs, options, taskContext(this.state, context))) {
|
|
735
|
+
assertPayload(output);
|
|
736
|
+
yield output;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
async function initializeTaskWorker(task) {
|
|
741
|
+
if (!await WorkerBody.inWorkerThread())
|
|
742
|
+
throw new Error("initializeTaskWorker must run inside a worker");
|
|
743
|
+
if (installed)
|
|
744
|
+
throw new Error("A task is already installed in this worker");
|
|
745
|
+
installed = true;
|
|
746
|
+
const runtime = new TaskRuntime(task);
|
|
747
|
+
let channelStream;
|
|
748
|
+
const channel = new TaskChannel({
|
|
749
|
+
getResultTransferList: (value, request) => request.outputOwnership === "transfer" ? getTransferList(value) : [],
|
|
750
|
+
send: (message, transfer) => {
|
|
751
|
+
const snapshot = structuredClone(message, { transfer });
|
|
752
|
+
void WorkerBody.postMessage("task-channel", snapshot).catch((reason) => channel.fail(reason));
|
|
753
|
+
},
|
|
754
|
+
handleRequest: async (operation, value, signal) => {
|
|
755
|
+
const request = value;
|
|
756
|
+
const context = {
|
|
757
|
+
signal,
|
|
758
|
+
reportProgress: (progress) => channel.emit("task:progress", { id: request.progressId, progress }),
|
|
759
|
+
requestHost: (operation2, payload, controls = {}) => {
|
|
760
|
+
const request2 = {
|
|
761
|
+
operation: operation2,
|
|
762
|
+
payload: clonePayload(payload, controls.inputOwnership),
|
|
763
|
+
outputOwnership: controls.outputOwnership ?? "copy"
|
|
764
|
+
};
|
|
765
|
+
return channel.request("task:host-request", request2, signal, getTransferList(request2));
|
|
766
|
+
},
|
|
767
|
+
emitHost: (operation2, payload) => channel.emit("task:host-event", { operation: operation2, payload, id: request.progressId })
|
|
768
|
+
};
|
|
769
|
+
switch (operation) {
|
|
770
|
+
case "initialize":
|
|
771
|
+
return runtime.initialize(request.input, context);
|
|
772
|
+
case "process":
|
|
773
|
+
return runtime.process(request.input, request.options, context);
|
|
774
|
+
case "stream-open": {
|
|
775
|
+
if (channelStream)
|
|
776
|
+
throw new Error("A task stream is already open");
|
|
777
|
+
async function* inputs() {
|
|
778
|
+
while (true) {
|
|
779
|
+
const result = await channel.request("task:next-input", { outputOwnership: "transfer" }, signal);
|
|
780
|
+
if (result.done)
|
|
781
|
+
return;
|
|
782
|
+
yield result.value;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
channelStream = runtime.stream(inputs(), request.options, context)[Symbol.asyncIterator]();
|
|
786
|
+
return {};
|
|
787
|
+
}
|
|
788
|
+
case "stream-next":
|
|
789
|
+
if (!channelStream)
|
|
790
|
+
throw new Error("No active task stream");
|
|
791
|
+
return channelStream.next();
|
|
792
|
+
case "stream-close":
|
|
793
|
+
try {
|
|
794
|
+
await channelStream?.return?.();
|
|
795
|
+
} finally {
|
|
796
|
+
channelStream = void 0;
|
|
797
|
+
}
|
|
798
|
+
return {};
|
|
799
|
+
case "destroy":
|
|
800
|
+
return runtime.destroy();
|
|
801
|
+
default:
|
|
802
|
+
throw new Error("Unknown task channel operation");
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
});
|
|
806
|
+
await WorkerBody.addEventListener((type, payload) => {
|
|
807
|
+
if (type === "task-channel")
|
|
808
|
+
channel.receive(payload);
|
|
809
|
+
});
|
|
810
|
+
let streamOptions = {};
|
|
811
|
+
return createWorker(async (request, _options, context) => {
|
|
812
|
+
switch (request.operation) {
|
|
813
|
+
case "initialize":
|
|
814
|
+
return runtime.initialize(request.input, context);
|
|
815
|
+
case "destroy":
|
|
816
|
+
return runtime.destroy();
|
|
817
|
+
case "stream-options":
|
|
818
|
+
streamOptions = request.options;
|
|
819
|
+
return {};
|
|
820
|
+
case "process":
|
|
821
|
+
return runtime.process(request.input, request.options, context);
|
|
822
|
+
default:
|
|
823
|
+
throw new Error("Unknown task operation");
|
|
824
|
+
}
|
|
825
|
+
}, async function* (inputs, _options, context) {
|
|
826
|
+
async function* batches() {
|
|
827
|
+
for await (const input of inputs) {
|
|
828
|
+
assertPayload(input);
|
|
829
|
+
yield input;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
try {
|
|
833
|
+
yield* runtime.stream(batches(), streamOptions, context);
|
|
834
|
+
} finally {
|
|
835
|
+
streamOptions = {};
|
|
836
|
+
}
|
|
837
|
+
}, () => preloadTaskCode(task));
|
|
838
|
+
}
|
|
839
|
+
var installed = false;
|
|
840
|
+
|
|
841
|
+
// ../../node_modules/@maplibre/geojson-vt/dist/geojson-vt.mjs
|
|
842
|
+
function simplify(coords, first, last, sqTolerance) {
|
|
843
|
+
const stack = [first, last];
|
|
844
|
+
while (stack.length) {
|
|
845
|
+
last = stack.pop();
|
|
846
|
+
first = stack.pop();
|
|
847
|
+
simplifySegment(coords, first, last, sqTolerance, stack);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
function simplifySegment(coords, first, last, sqTolerance, stack) {
|
|
851
|
+
let maxSqDist = sqTolerance;
|
|
852
|
+
const mid = first + (last - first >> 1);
|
|
853
|
+
let minPosToMid = last - first;
|
|
854
|
+
let index;
|
|
855
|
+
const ax = coords[first];
|
|
856
|
+
const ay = coords[first + 1];
|
|
857
|
+
const bx = coords[last];
|
|
858
|
+
const by = coords[last + 1];
|
|
859
|
+
for (let i = first + 3; i < last; i += 3) {
|
|
860
|
+
const d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);
|
|
861
|
+
if (d > maxSqDist) {
|
|
862
|
+
index = i;
|
|
863
|
+
maxSqDist = d;
|
|
864
|
+
continue;
|
|
865
|
+
}
|
|
866
|
+
if (d === maxSqDist) {
|
|
867
|
+
const posToMid = Math.abs(i - mid);
|
|
868
|
+
if (posToMid < minPosToMid) {
|
|
869
|
+
index = i;
|
|
870
|
+
minPosToMid = posToMid;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
if (maxSqDist > sqTolerance) {
|
|
875
|
+
coords[index + 2] = maxSqDist;
|
|
876
|
+
if (index - first > 3) stack.push(first, index);
|
|
877
|
+
if (last - index > 3) stack.push(index, last);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
function getSqSegDist(px, py, x, y, bx, by) {
|
|
881
|
+
let dx = bx - x;
|
|
882
|
+
let dy = by - y;
|
|
883
|
+
if (dx !== 0 || dy !== 0) {
|
|
884
|
+
const t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
|
|
885
|
+
if (t > 1) {
|
|
886
|
+
x = bx;
|
|
887
|
+
y = by;
|
|
888
|
+
} else if (t > 0) {
|
|
889
|
+
x += dx * t;
|
|
890
|
+
y += dy * t;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
dx = px - x;
|
|
894
|
+
dy = py - y;
|
|
895
|
+
return dx * dx + dy * dy;
|
|
896
|
+
}
|
|
897
|
+
function createFeature(id, type, geom, tags) {
|
|
898
|
+
const data = {
|
|
899
|
+
type,
|
|
900
|
+
geom
|
|
901
|
+
};
|
|
902
|
+
const feature = {
|
|
903
|
+
id: id == null ? null : id,
|
|
904
|
+
type: data.type,
|
|
905
|
+
geometry: data.geom,
|
|
906
|
+
tags,
|
|
907
|
+
minX: Infinity,
|
|
908
|
+
minY: Infinity,
|
|
909
|
+
maxX: -Infinity,
|
|
910
|
+
maxY: -Infinity
|
|
911
|
+
};
|
|
912
|
+
switch (data.type) {
|
|
913
|
+
case "Point":
|
|
914
|
+
case "MultiPoint":
|
|
915
|
+
calcLineBBox(feature, data.geom);
|
|
916
|
+
break;
|
|
917
|
+
case "LineString":
|
|
918
|
+
calcLineBBox(feature, data.geom.points);
|
|
919
|
+
break;
|
|
920
|
+
case "Polygon":
|
|
921
|
+
calcLineBBox(feature, data.geom[0].points);
|
|
922
|
+
break;
|
|
923
|
+
case "MultiLineString":
|
|
924
|
+
for (const line of data.geom) calcLineBBox(feature, line.points);
|
|
925
|
+
break;
|
|
926
|
+
case "MultiPolygon":
|
|
927
|
+
for (const polygon of data.geom) calcLineBBox(feature, polygon[0].points);
|
|
928
|
+
}
|
|
929
|
+
return feature;
|
|
930
|
+
}
|
|
931
|
+
function optimizeLineMemory(line) {
|
|
932
|
+
const lineImmutable = line;
|
|
933
|
+
if (line.points.length > 64) lineImmutable.points = new Float64Array(line.points);
|
|
934
|
+
}
|
|
935
|
+
function calcLineBBox(feature, geom) {
|
|
936
|
+
for (let i = 0; i < geom.length; i += 3) {
|
|
937
|
+
feature.minX = Math.min(feature.minX, geom[i]);
|
|
938
|
+
feature.minY = Math.min(feature.minY, geom[i + 1]);
|
|
939
|
+
feature.maxX = Math.max(feature.maxX, geom[i]);
|
|
940
|
+
feature.maxY = Math.max(feature.maxY, geom[i + 1]);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
var MercatorWorldCoordinateHelper = class {
|
|
944
|
+
projectX(lng) {
|
|
945
|
+
return lng / 360 + 0.5;
|
|
946
|
+
}
|
|
947
|
+
projectY(lat) {
|
|
948
|
+
const sin = Math.sin(lat * Math.PI / 180);
|
|
949
|
+
const y = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
|
|
950
|
+
return y < 0 ? 0 : y > 1 ? 1 : y;
|
|
951
|
+
}
|
|
952
|
+
unprojectX(x) {
|
|
953
|
+
return (x - 0.5) * 360;
|
|
954
|
+
}
|
|
955
|
+
unprojectY(y) {
|
|
956
|
+
const y2 = (180 - y * 360) * Math.PI / 180;
|
|
957
|
+
return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;
|
|
958
|
+
}
|
|
959
|
+
};
|
|
960
|
+
var IdentityWorldCoordinateHelper = class {
|
|
961
|
+
projectX(x) {
|
|
962
|
+
return x;
|
|
963
|
+
}
|
|
964
|
+
projectY(y) {
|
|
965
|
+
return y;
|
|
966
|
+
}
|
|
967
|
+
unprojectX(x) {
|
|
968
|
+
return x;
|
|
969
|
+
}
|
|
970
|
+
unprojectY(y) {
|
|
971
|
+
return y;
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
var mercatorWorldCoordinateHelper = new MercatorWorldCoordinateHelper();
|
|
975
|
+
var identityWorldCoordinateHelper = new IdentityWorldCoordinateHelper();
|
|
976
|
+
function getWorldCoordinateHelper(coordinates) {
|
|
977
|
+
return coordinates === "unitSquare" ? identityWorldCoordinateHelper : mercatorWorldCoordinateHelper;
|
|
978
|
+
}
|
|
979
|
+
var MAX_GEOMETRY_COLLECTION_DEPTH = 1024;
|
|
980
|
+
function convertToInternal(data, options, unlocated) {
|
|
981
|
+
const features = [];
|
|
982
|
+
switch (data.type) {
|
|
983
|
+
case "FeatureCollection":
|
|
984
|
+
for (let i = 0; i < data.features.length; i++) convertFeature(features, data.features[i], options, unlocated, i);
|
|
985
|
+
break;
|
|
986
|
+
case "Feature":
|
|
987
|
+
convertFeature(features, data, options, unlocated);
|
|
988
|
+
break;
|
|
989
|
+
default:
|
|
990
|
+
convertFeature(features, {
|
|
991
|
+
type: "Feature",
|
|
992
|
+
geometry: data,
|
|
993
|
+
properties: void 0
|
|
994
|
+
}, options, unlocated);
|
|
995
|
+
}
|
|
996
|
+
return features;
|
|
997
|
+
}
|
|
998
|
+
function convertFeature(features, geojson, options, unlocated, index) {
|
|
999
|
+
const count = features.length;
|
|
1000
|
+
featureToInternal(features, geojson, options, index);
|
|
1001
|
+
if (!unlocated) return;
|
|
1002
|
+
const id = getFeatureId(geojson, options, index);
|
|
1003
|
+
if (id == null) return;
|
|
1004
|
+
if (features.length > count) unlocated.delete(id);
|
|
1005
|
+
else unlocated.set(id, {
|
|
1006
|
+
...geojson,
|
|
1007
|
+
id
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
function featureToInternal(features, geojson, options, index, depth = 0) {
|
|
1011
|
+
if (!geojson.geometry) return;
|
|
1012
|
+
if (depth > MAX_GEOMETRY_COLLECTION_DEPTH) throw new Error("GeometryCollection nesting exceeds supported depth: 1024");
|
|
1013
|
+
if (geojson.geometry.type === "GeometryCollection") {
|
|
1014
|
+
convertGeometryCollection(features, geojson, geojson.geometry, options, index, depth + 1);
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
if (!geojson.geometry.coordinates?.length) return;
|
|
1018
|
+
const id = getFeatureId(geojson, options, index);
|
|
1019
|
+
const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);
|
|
1020
|
+
const worldCoordinateHelper = getWorldCoordinateHelper(options.coordinates);
|
|
1021
|
+
switch (geojson.geometry.type) {
|
|
1022
|
+
case "Point":
|
|
1023
|
+
convertPointFeature(features, id, geojson.geometry, worldCoordinateHelper, geojson.properties);
|
|
1024
|
+
return;
|
|
1025
|
+
case "MultiPoint":
|
|
1026
|
+
convertMultiPointFeature(features, id, geojson.geometry, worldCoordinateHelper, geojson.properties);
|
|
1027
|
+
return;
|
|
1028
|
+
case "LineString":
|
|
1029
|
+
convertLineStringFeature(features, id, geojson.geometry, tolerance, worldCoordinateHelper, geojson.properties);
|
|
1030
|
+
return;
|
|
1031
|
+
case "MultiLineString":
|
|
1032
|
+
convertMultiLineStringFeature(features, id, geojson.geometry, tolerance, worldCoordinateHelper, options, geojson.properties);
|
|
1033
|
+
return;
|
|
1034
|
+
case "Polygon":
|
|
1035
|
+
convertPolygonFeature(features, id, geojson.geometry, tolerance, worldCoordinateHelper, geojson.properties);
|
|
1036
|
+
return;
|
|
1037
|
+
case "MultiPolygon":
|
|
1038
|
+
convertMultiPolygonFeature(features, id, geojson.geometry, tolerance, worldCoordinateHelper, geojson.properties);
|
|
1039
|
+
return;
|
|
1040
|
+
default:
|
|
1041
|
+
throw new Error("Input data is not a valid GeoJSON object.");
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
function getFeatureId(geojson, options, index) {
|
|
1045
|
+
if (options.promoteId) return geojson.properties?.[options.promoteId];
|
|
1046
|
+
if (options.generateId) return index || 0;
|
|
1047
|
+
return geojson.id;
|
|
1048
|
+
}
|
|
1049
|
+
function convertGeometryCollection(features, geojson, geometry, options, index, depth = 0) {
|
|
1050
|
+
for (const geom of geometry.geometries) featureToInternal(features, {
|
|
1051
|
+
id: geojson.id,
|
|
1052
|
+
type: "Feature",
|
|
1053
|
+
geometry: geom,
|
|
1054
|
+
properties: geojson.properties
|
|
1055
|
+
}, options, index, depth);
|
|
1056
|
+
}
|
|
1057
|
+
function convertPointFeature(features, id, geom, worldCoordinateHelper, properties) {
|
|
1058
|
+
const out = [];
|
|
1059
|
+
out.push(worldCoordinateHelper.projectX(geom.coordinates[0]), worldCoordinateHelper.projectY(geom.coordinates[1]), 0);
|
|
1060
|
+
features.push(createFeature(id, "Point", out, properties));
|
|
1061
|
+
}
|
|
1062
|
+
function convertMultiPointFeature(features, id, geom, worldCoordinateHelper, properties) {
|
|
1063
|
+
const out = [];
|
|
1064
|
+
for (const coords of geom.coordinates) out.push(worldCoordinateHelper.projectX(coords[0]), worldCoordinateHelper.projectY(coords[1]), 0);
|
|
1065
|
+
features.push(createFeature(id, "MultiPoint", out, properties));
|
|
1066
|
+
}
|
|
1067
|
+
function convertLineStringFeature(features, id, geom, tolerance, worldCoordinateHelper, properties) {
|
|
1068
|
+
const out = { points: [] };
|
|
1069
|
+
convertLine(geom.coordinates, out, tolerance, false, worldCoordinateHelper);
|
|
1070
|
+
features.push(createFeature(id, "LineString", out, properties));
|
|
1071
|
+
}
|
|
1072
|
+
function convertMultiLineStringFeature(features, id, geom, tolerance, worldCoordinateHelper, options, properties) {
|
|
1073
|
+
if (options.lineMetrics) for (const line of geom.coordinates) {
|
|
1074
|
+
const out = { points: [] };
|
|
1075
|
+
convertLine(line, out, tolerance, false, worldCoordinateHelper);
|
|
1076
|
+
features.push(createFeature(id, "LineString", out, properties));
|
|
1077
|
+
}
|
|
1078
|
+
else {
|
|
1079
|
+
const out = [];
|
|
1080
|
+
convertLines(geom.coordinates, out, tolerance, false, worldCoordinateHelper);
|
|
1081
|
+
features.push(createFeature(id, "MultiLineString", out, properties));
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
function convertPolygonFeature(features, id, geom, tolerance, worldCoordinateHelper, properties) {
|
|
1085
|
+
const out = [];
|
|
1086
|
+
convertLines(geom.coordinates, out, tolerance, true, worldCoordinateHelper);
|
|
1087
|
+
features.push(createFeature(id, "Polygon", out, properties));
|
|
1088
|
+
}
|
|
1089
|
+
function convertMultiPolygonFeature(features, id, geom, tolerance, worldCoordinateHelper, properties) {
|
|
1090
|
+
const out = [];
|
|
1091
|
+
for (const polygon of geom.coordinates) {
|
|
1092
|
+
const polygonOut = [];
|
|
1093
|
+
convertLines(polygon, polygonOut, tolerance, true, worldCoordinateHelper);
|
|
1094
|
+
if (!polygonOut.length) continue;
|
|
1095
|
+
out.push(polygonOut);
|
|
1096
|
+
}
|
|
1097
|
+
if (!out.length) return;
|
|
1098
|
+
features.push(createFeature(id, "MultiPolygon", out, properties));
|
|
1099
|
+
}
|
|
1100
|
+
function convertLine(ring, out, tolerance, isPolygon, worldCoordinateHelper) {
|
|
1101
|
+
let x0, y0;
|
|
1102
|
+
let size = 0;
|
|
1103
|
+
for (let j = 0; j < ring.length; j++) {
|
|
1104
|
+
const x = worldCoordinateHelper.projectX(ring[j][0]);
|
|
1105
|
+
const y = worldCoordinateHelper.projectY(ring[j][1]);
|
|
1106
|
+
out.points.push(x, y, 0);
|
|
1107
|
+
if (j > 0) {
|
|
1108
|
+
if (isPolygon) size += (x0 * y - x * y0) / 2;
|
|
1109
|
+
else size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2));
|
|
1110
|
+
}
|
|
1111
|
+
x0 = x;
|
|
1112
|
+
y0 = y;
|
|
1113
|
+
}
|
|
1114
|
+
const last = out.points.length - 3;
|
|
1115
|
+
out.points[2] = 1;
|
|
1116
|
+
if (tolerance > 0) simplify(out.points, 0, last, tolerance);
|
|
1117
|
+
out.points[last + 2] = 1;
|
|
1118
|
+
optimizeLineMemory(out);
|
|
1119
|
+
out.size = Math.abs(size);
|
|
1120
|
+
out.start = 0;
|
|
1121
|
+
out.end = out.size;
|
|
1122
|
+
}
|
|
1123
|
+
function convertLines(rings, out, tolerance, isPolygon, worldCoordinateHelper) {
|
|
1124
|
+
for (let i = 0; i < rings.length; i++) {
|
|
1125
|
+
const geom = { points: [] };
|
|
1126
|
+
convertLine(rings[i], geom, tolerance, isPolygon, worldCoordinateHelper);
|
|
1127
|
+
out.push(geom);
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
function convertToGeoJSON(source, worldCoordinateHelper = mercatorWorldCoordinateHelper) {
|
|
1131
|
+
return {
|
|
1132
|
+
type: "FeatureCollection",
|
|
1133
|
+
features: source.map((feature) => featureToGeoJSON(feature, worldCoordinateHelper))
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
function featureToGeoJSON(feature, worldCoordinateHelper = mercatorWorldCoordinateHelper) {
|
|
1137
|
+
const geojsonFeature = {
|
|
1138
|
+
type: "Feature",
|
|
1139
|
+
geometry: geometryToGeoJSON(feature, worldCoordinateHelper),
|
|
1140
|
+
properties: feature.tags
|
|
1141
|
+
};
|
|
1142
|
+
if (feature.id != null) geojsonFeature.id = feature.id;
|
|
1143
|
+
return geojsonFeature;
|
|
1144
|
+
}
|
|
1145
|
+
function geometryToGeoJSON(feature, worldCoordinateHelper) {
|
|
1146
|
+
const { type, geometry } = feature;
|
|
1147
|
+
switch (type) {
|
|
1148
|
+
case "Point":
|
|
1149
|
+
return {
|
|
1150
|
+
type,
|
|
1151
|
+
coordinates: unprojectPoint(geometry[0], geometry[1], worldCoordinateHelper)
|
|
1152
|
+
};
|
|
1153
|
+
case "MultiPoint":
|
|
1154
|
+
return {
|
|
1155
|
+
type,
|
|
1156
|
+
coordinates: unprojectPoints(geometry, worldCoordinateHelper)
|
|
1157
|
+
};
|
|
1158
|
+
case "LineString":
|
|
1159
|
+
return {
|
|
1160
|
+
type,
|
|
1161
|
+
coordinates: unprojectPoints(geometry.points, worldCoordinateHelper)
|
|
1162
|
+
};
|
|
1163
|
+
case "MultiLineString":
|
|
1164
|
+
case "Polygon":
|
|
1165
|
+
return {
|
|
1166
|
+
type,
|
|
1167
|
+
coordinates: geometry.map((ring) => unprojectPoints(ring.points, worldCoordinateHelper))
|
|
1168
|
+
};
|
|
1169
|
+
case "MultiPolygon":
|
|
1170
|
+
return {
|
|
1171
|
+
type,
|
|
1172
|
+
coordinates: geometry.map((polygon) => polygon.map((ring) => unprojectPoints(ring.points, worldCoordinateHelper)))
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
function unprojectPoints(coords, worldCoordinateHelper = mercatorWorldCoordinateHelper) {
|
|
1177
|
+
const result = [];
|
|
1178
|
+
for (let i = 0; i < coords.length; i += 3) result.push(unprojectPoint(coords[i], coords[i + 1], worldCoordinateHelper));
|
|
1179
|
+
return result;
|
|
1180
|
+
}
|
|
1181
|
+
function unprojectPoint(x, y, worldCoordinateHelper) {
|
|
1182
|
+
return [worldCoordinateHelper.unprojectX(x), worldCoordinateHelper.unprojectY(y)];
|
|
1183
|
+
}
|
|
1184
|
+
function clip(features, scale, start, end, axis, minAll, maxAll, options) {
|
|
1185
|
+
start /= scale;
|
|
1186
|
+
end /= scale;
|
|
1187
|
+
if (minAll >= start && maxAll < end) return features;
|
|
1188
|
+
if (maxAll < start || minAll >= end) return null;
|
|
1189
|
+
const clipped = [];
|
|
1190
|
+
for (const feature of features) {
|
|
1191
|
+
const min = axis === 0 ? feature.minX : feature.minY;
|
|
1192
|
+
const max = axis === 0 ? feature.maxX : feature.maxY;
|
|
1193
|
+
if (min >= start && max < end) {
|
|
1194
|
+
clipped.push(feature);
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
1197
|
+
if (max < start || min >= end) continue;
|
|
1198
|
+
switch (feature.type) {
|
|
1199
|
+
case "Point":
|
|
1200
|
+
case "MultiPoint":
|
|
1201
|
+
clipPointFeature(feature, clipped, start, end, axis);
|
|
1202
|
+
continue;
|
|
1203
|
+
case "LineString":
|
|
1204
|
+
clipLineStringFeature(feature, clipped, start, end, axis, options);
|
|
1205
|
+
continue;
|
|
1206
|
+
case "MultiLineString":
|
|
1207
|
+
clipMultiLineStringFeature(feature, clipped, start, end, axis);
|
|
1208
|
+
continue;
|
|
1209
|
+
case "Polygon":
|
|
1210
|
+
clipPolygonFeature(feature, clipped, start, end, axis);
|
|
1211
|
+
continue;
|
|
1212
|
+
case "MultiPolygon":
|
|
1213
|
+
clipMultiPolygonFeature(feature, clipped, start, end, axis);
|
|
1214
|
+
continue;
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
if (!clipped.length) return null;
|
|
1218
|
+
return clipped;
|
|
1219
|
+
}
|
|
1220
|
+
function clipPointFeature(feature, clipped, start, end, axis) {
|
|
1221
|
+
const geom = [];
|
|
1222
|
+
clipPoints(feature.geometry, geom, start, end, axis);
|
|
1223
|
+
if (!geom.length) return;
|
|
1224
|
+
const type = geom.length === 3 ? "Point" : "MultiPoint";
|
|
1225
|
+
clipped.push(createFeature(feature.id, type, geom, feature.tags));
|
|
1226
|
+
}
|
|
1227
|
+
function clipLineStringFeature(feature, clipped, start, end, axis, options) {
|
|
1228
|
+
const geom = [];
|
|
1229
|
+
clipLine(feature.geometry, geom, start, end, axis, false, options.lineMetrics);
|
|
1230
|
+
if (!geom.length) return;
|
|
1231
|
+
if (options.lineMetrics) {
|
|
1232
|
+
for (const line of geom) clipped.push(createFeature(feature.id, "LineString", line, feature.tags));
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
if (geom.length > 1) {
|
|
1236
|
+
clipped.push(createFeature(feature.id, "MultiLineString", geom, feature.tags));
|
|
1237
|
+
return;
|
|
1238
|
+
}
|
|
1239
|
+
clipped.push(createFeature(feature.id, "LineString", geom[0], feature.tags));
|
|
1240
|
+
}
|
|
1241
|
+
function clipMultiLineStringFeature(feature, clipped, start, end, axis) {
|
|
1242
|
+
const geom = [];
|
|
1243
|
+
clipLines(feature.geometry, geom, start, end, axis, false);
|
|
1244
|
+
if (!geom.length) return;
|
|
1245
|
+
if (geom.length === 1) {
|
|
1246
|
+
clipped.push(createFeature(feature.id, "LineString", geom[0], feature.tags));
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
clipped.push(createFeature(feature.id, "MultiLineString", geom, feature.tags));
|
|
1250
|
+
}
|
|
1251
|
+
function clipPolygonFeature(feature, clipped, start, end, axis) {
|
|
1252
|
+
const geom = [];
|
|
1253
|
+
clipLines(feature.geometry, geom, start, end, axis, true);
|
|
1254
|
+
if (!geom.length) return;
|
|
1255
|
+
clipped.push(createFeature(feature.id, "Polygon", geom, feature.tags));
|
|
1256
|
+
}
|
|
1257
|
+
function clipMultiPolygonFeature(feature, clipped, start, end, axis) {
|
|
1258
|
+
const geom = [];
|
|
1259
|
+
for (const polygon of feature.geometry) {
|
|
1260
|
+
const newPolygon = [];
|
|
1261
|
+
clipLines(polygon, newPolygon, start, end, axis, true);
|
|
1262
|
+
if (!newPolygon.length) continue;
|
|
1263
|
+
geom.push(newPolygon);
|
|
1264
|
+
}
|
|
1265
|
+
if (!geom.length) return;
|
|
1266
|
+
clipped.push(createFeature(feature.id, "MultiPolygon", geom, feature.tags));
|
|
1267
|
+
}
|
|
1268
|
+
function clipPoints(geom, newGeom, start, end, axis) {
|
|
1269
|
+
for (let i = 0; i < geom.length; i += 3) {
|
|
1270
|
+
const a = geom[i + axis];
|
|
1271
|
+
if (a >= start && a <= end) addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
function clipLine(geom, newGeom, start, end, axis, isPolygon, trackMetrics) {
|
|
1275
|
+
let slice = newSlice(geom);
|
|
1276
|
+
const intersect = axis === 0 ? intersectX : intersectY;
|
|
1277
|
+
let len = geom.start;
|
|
1278
|
+
let segLen, t;
|
|
1279
|
+
for (let i = 0; i < geom.points.length - 3; i += 3) {
|
|
1280
|
+
const ax2 = geom.points[i];
|
|
1281
|
+
const ay2 = geom.points[i + 1];
|
|
1282
|
+
const az2 = geom.points[i + 2];
|
|
1283
|
+
const bx = geom.points[i + 3];
|
|
1284
|
+
const by = geom.points[i + 4];
|
|
1285
|
+
const a2 = axis === 0 ? ax2 : ay2;
|
|
1286
|
+
const b = axis === 0 ? bx : by;
|
|
1287
|
+
let exited = false;
|
|
1288
|
+
if (trackMetrics) segLen = Math.sqrt(Math.pow(ax2 - bx, 2) + Math.pow(ay2 - by, 2));
|
|
1289
|
+
if (a2 < start) {
|
|
1290
|
+
if (b >= start) {
|
|
1291
|
+
t = intersect(slice, ax2, ay2, bx, by, start);
|
|
1292
|
+
if (trackMetrics) slice.start = len + segLen * t;
|
|
1293
|
+
}
|
|
1294
|
+
} else if (a2 > end) {
|
|
1295
|
+
if (b <= end) {
|
|
1296
|
+
t = intersect(slice, ax2, ay2, bx, by, end);
|
|
1297
|
+
if (trackMetrics) slice.start = len + segLen * t;
|
|
1298
|
+
}
|
|
1299
|
+
} else addPoint(slice.points, ax2, ay2, az2);
|
|
1300
|
+
if (b < start && a2 >= start) {
|
|
1301
|
+
t = intersect(slice, ax2, ay2, bx, by, start);
|
|
1302
|
+
exited = true;
|
|
1303
|
+
}
|
|
1304
|
+
if (b > end && a2 <= end) {
|
|
1305
|
+
t = intersect(slice, ax2, ay2, bx, by, end);
|
|
1306
|
+
exited = true;
|
|
1307
|
+
}
|
|
1308
|
+
if (!isPolygon && exited) {
|
|
1309
|
+
if (trackMetrics) slice.end = len + segLen * t;
|
|
1310
|
+
newGeom.push(slice);
|
|
1311
|
+
slice = newSlice(geom);
|
|
1312
|
+
}
|
|
1313
|
+
if (trackMetrics) len += segLen;
|
|
1314
|
+
}
|
|
1315
|
+
let last = geom.points.length - 3;
|
|
1316
|
+
const ax = geom.points[last];
|
|
1317
|
+
const ay = geom.points[last + 1];
|
|
1318
|
+
const az = geom.points[last + 2];
|
|
1319
|
+
const a = axis === 0 ? ax : ay;
|
|
1320
|
+
if (a >= start && a <= end) addPoint(slice.points, ax, ay, az);
|
|
1321
|
+
last = slice.points.length - 3;
|
|
1322
|
+
if (isPolygon && last >= 3 && (slice.points[last] !== slice.points[0] || slice.points[last + 1] !== slice.points[1])) addPoint(slice.points, slice.points[0], slice.points[1], slice.points[2]);
|
|
1323
|
+
if (slice.points.length) {
|
|
1324
|
+
optimizeLineMemory(slice);
|
|
1325
|
+
newGeom.push(slice);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
function newSlice(line) {
|
|
1329
|
+
return {
|
|
1330
|
+
points: [],
|
|
1331
|
+
size: line.size,
|
|
1332
|
+
start: line.start,
|
|
1333
|
+
end: line.end
|
|
1334
|
+
};
|
|
1335
|
+
}
|
|
1336
|
+
function clipLines(geom, newGeom, start, end, axis, isPolygon) {
|
|
1337
|
+
for (const line of geom) clipLine(line, newGeom, start, end, axis, isPolygon, false);
|
|
1338
|
+
}
|
|
1339
|
+
function addPoint(out, x, y, z) {
|
|
1340
|
+
out.push(x, y, z);
|
|
1341
|
+
}
|
|
1342
|
+
function intersectX(out, ax, ay, bx, by, x) {
|
|
1343
|
+
const t = (x - ax) / (bx - ax);
|
|
1344
|
+
addPoint(out.points, x, ay + (by - ay) * t, 1);
|
|
1345
|
+
return t;
|
|
1346
|
+
}
|
|
1347
|
+
function intersectY(out, ax, ay, bx, by, y) {
|
|
1348
|
+
const t = (y - ay) / (by - ay);
|
|
1349
|
+
addPoint(out.points, ax + (bx - ax) * t, y, 1);
|
|
1350
|
+
return t;
|
|
1351
|
+
}
|
|
1352
|
+
function wrap(features, options) {
|
|
1353
|
+
if (!options.wrap) return features;
|
|
1354
|
+
const buffer = options.buffer / options.extent;
|
|
1355
|
+
let merged = features;
|
|
1356
|
+
const left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options);
|
|
1357
|
+
const right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options);
|
|
1358
|
+
if (!left && !right) return merged;
|
|
1359
|
+
merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || [];
|
|
1360
|
+
if (left) merged = shiftFeatureCoords(left, 1).concat(merged);
|
|
1361
|
+
if (right) merged = merged.concat(shiftFeatureCoords(right, -1));
|
|
1362
|
+
return merged;
|
|
1363
|
+
}
|
|
1364
|
+
function shiftFeatureCoords(features, offset) {
|
|
1365
|
+
const newFeatures = [];
|
|
1366
|
+
for (const feature of features) switch (feature.type) {
|
|
1367
|
+
case "Point":
|
|
1368
|
+
case "MultiPoint": {
|
|
1369
|
+
const newGeometry = shiftPointCoords(feature.geometry, offset);
|
|
1370
|
+
newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
|
|
1371
|
+
continue;
|
|
1372
|
+
}
|
|
1373
|
+
case "LineString": {
|
|
1374
|
+
const newGeometry = shiftLineCoords(feature.geometry, offset);
|
|
1375
|
+
newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
|
|
1376
|
+
continue;
|
|
1377
|
+
}
|
|
1378
|
+
case "MultiLineString":
|
|
1379
|
+
case "Polygon": {
|
|
1380
|
+
const newGeometry = [];
|
|
1381
|
+
for (const line of feature.geometry) newGeometry.push(shiftLineCoords(line, offset));
|
|
1382
|
+
newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
|
|
1383
|
+
continue;
|
|
1384
|
+
}
|
|
1385
|
+
case "MultiPolygon": {
|
|
1386
|
+
const newGeometry = [];
|
|
1387
|
+
for (const polygon of feature.geometry) {
|
|
1388
|
+
const newPolygon = [];
|
|
1389
|
+
for (const line of polygon) newPolygon.push(shiftLineCoords(line, offset));
|
|
1390
|
+
newGeometry.push(newPolygon);
|
|
1391
|
+
}
|
|
1392
|
+
newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
|
|
1393
|
+
continue;
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
return newFeatures;
|
|
1397
|
+
}
|
|
1398
|
+
function shiftPointCoords(coords, offset) {
|
|
1399
|
+
const newCoords = [];
|
|
1400
|
+
for (let i = 0; i < coords.length; i += 3) newCoords.push(coords[i] + offset, coords[i + 1], coords[i + 2]);
|
|
1401
|
+
return newCoords;
|
|
1402
|
+
}
|
|
1403
|
+
function shiftLineCoords(line, offset) {
|
|
1404
|
+
const newLine = {
|
|
1405
|
+
points: [],
|
|
1406
|
+
size: line.size
|
|
1407
|
+
};
|
|
1408
|
+
if (line.start !== void 0) {
|
|
1409
|
+
newLine.start = line.start;
|
|
1410
|
+
newLine.end = line.end;
|
|
1411
|
+
}
|
|
1412
|
+
for (let i = 0; i < line.points.length; i += 3) newLine.points.push(line.points[i] + offset, line.points[i + 1], line.points[i + 2]);
|
|
1413
|
+
optimizeLineMemory(newLine);
|
|
1414
|
+
return newLine;
|
|
1415
|
+
}
|
|
1416
|
+
function applySourceDiff(source, dataDiff, options, unlocated) {
|
|
1417
|
+
const diff = diffToHashed(dataDiff, options);
|
|
1418
|
+
let affected = [];
|
|
1419
|
+
if (diff.removeAll) {
|
|
1420
|
+
affected = source;
|
|
1421
|
+
source = [];
|
|
1422
|
+
unlocated?.clear();
|
|
1423
|
+
}
|
|
1424
|
+
if (diff.remove.size || diff.add.size) {
|
|
1425
|
+
for (const id of diff.remove) unlocated?.delete(id);
|
|
1426
|
+
const removeFeatures = [];
|
|
1427
|
+
for (const feature of source) if (diff.remove.has(feature.id) || diff.add.has(feature.id)) removeFeatures.push(feature);
|
|
1428
|
+
if (removeFeatures.length) {
|
|
1429
|
+
affected = affected.concat(removeFeatures);
|
|
1430
|
+
const removeIds = new Set(removeFeatures.map((f) => f.id));
|
|
1431
|
+
source = source.filter((f) => !removeIds.has(f.id));
|
|
1432
|
+
}
|
|
1433
|
+
if (diff.add.size) {
|
|
1434
|
+
let addFeatures = convertToInternal({
|
|
1435
|
+
type: "FeatureCollection",
|
|
1436
|
+
features: Array.from(diff.add.values())
|
|
1437
|
+
}, options, unlocated);
|
|
1438
|
+
addFeatures = wrap(addFeatures, options);
|
|
1439
|
+
affected = affected.concat(addFeatures);
|
|
1440
|
+
source = source.concat(addFeatures);
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
if (diff.update.size) {
|
|
1444
|
+
const oldFeaturesMap = /* @__PURE__ */ new Map();
|
|
1445
|
+
let keepFeatures = [];
|
|
1446
|
+
for (const feature of source) if (diff.update.has(feature.id)) oldFeaturesMap.set(feature.id, [...oldFeaturesMap.get(feature.id) || [], feature]);
|
|
1447
|
+
else keepFeatures.push(feature);
|
|
1448
|
+
for (const [id, update] of diff.update) {
|
|
1449
|
+
const oldFeatures = oldFeaturesMap.get(id);
|
|
1450
|
+
if (!oldFeatures || oldFeatures.length === 0) {
|
|
1451
|
+
if (!unlocated?.has(id)) continue;
|
|
1452
|
+
const locatedFeatures = getUpdatedUnlocatedFeatures(id, update, options, unlocated);
|
|
1453
|
+
affected = affected.concat(locatedFeatures);
|
|
1454
|
+
keepFeatures = keepFeatures.concat(locatedFeatures);
|
|
1455
|
+
continue;
|
|
1456
|
+
}
|
|
1457
|
+
const updatedFeatures = getUpdatedFeatures(oldFeatures, update, options, unlocated);
|
|
1458
|
+
affected = affected.concat(oldFeatures, updatedFeatures);
|
|
1459
|
+
keepFeatures = keepFeatures.concat(updatedFeatures);
|
|
1460
|
+
}
|
|
1461
|
+
source = keepFeatures;
|
|
1462
|
+
}
|
|
1463
|
+
return {
|
|
1464
|
+
affected,
|
|
1465
|
+
source
|
|
1466
|
+
};
|
|
1467
|
+
}
|
|
1468
|
+
function getUpdatedFeatures(vtFeatures, update, options, unlocated) {
|
|
1469
|
+
const changeGeometry = !!update.newGeometry;
|
|
1470
|
+
const changeProps = hasPropertyChanges(update);
|
|
1471
|
+
if (changeGeometry) {
|
|
1472
|
+
const vtFeature = vtFeatures[0];
|
|
1473
|
+
const properties = changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags;
|
|
1474
|
+
return convertNewGeometry(vtFeature.id, update.newGeometry, properties, options, unlocated);
|
|
1475
|
+
}
|
|
1476
|
+
if (changeProps) {
|
|
1477
|
+
const updated = [];
|
|
1478
|
+
for (const vtFeature of vtFeatures) {
|
|
1479
|
+
const feature = { ...vtFeature };
|
|
1480
|
+
feature.tags = applyPropertyUpdates(feature.tags, update);
|
|
1481
|
+
updated.push(feature);
|
|
1482
|
+
}
|
|
1483
|
+
return updated;
|
|
1484
|
+
}
|
|
1485
|
+
return vtFeatures;
|
|
1486
|
+
}
|
|
1487
|
+
function getUpdatedUnlocatedFeatures(id, update, options, unlocated) {
|
|
1488
|
+
const feature = unlocated.get(id);
|
|
1489
|
+
const properties = hasPropertyChanges(update) ? applyPropertyUpdates(feature.properties, update) : feature.properties;
|
|
1490
|
+
if (!update.newGeometry) {
|
|
1491
|
+
unlocated.set(id, {
|
|
1492
|
+
...feature,
|
|
1493
|
+
properties
|
|
1494
|
+
});
|
|
1495
|
+
return [];
|
|
1496
|
+
}
|
|
1497
|
+
return convertNewGeometry(id, update.newGeometry, properties, options, unlocated);
|
|
1498
|
+
}
|
|
1499
|
+
function convertNewGeometry(id, geometry, properties, options, unlocated) {
|
|
1500
|
+
return wrap(convertToInternal({
|
|
1501
|
+
type: "FeatureCollection",
|
|
1502
|
+
features: [{
|
|
1503
|
+
type: "Feature",
|
|
1504
|
+
id,
|
|
1505
|
+
geometry,
|
|
1506
|
+
properties
|
|
1507
|
+
}]
|
|
1508
|
+
}, {
|
|
1509
|
+
...options,
|
|
1510
|
+
promoteId: void 0,
|
|
1511
|
+
generateId: false
|
|
1512
|
+
}, unlocated), options);
|
|
1513
|
+
}
|
|
1514
|
+
function hasPropertyChanges(update) {
|
|
1515
|
+
return update.removeAllProperties || update.removeProperties?.length > 0 || update.addOrUpdateProperties?.length > 0;
|
|
1516
|
+
}
|
|
1517
|
+
function applyPropertyUpdates(tags, update) {
|
|
1518
|
+
if (update.removeAllProperties) return {};
|
|
1519
|
+
const properties = { ...tags || {} };
|
|
1520
|
+
if (update.removeProperties) for (const key of update.removeProperties) delete properties[key];
|
|
1521
|
+
if (update.addOrUpdateProperties) for (const { key, value } of update.addOrUpdateProperties) properties[key] = value;
|
|
1522
|
+
return properties;
|
|
1523
|
+
}
|
|
1524
|
+
function diffToHashed(diff, options) {
|
|
1525
|
+
if (!diff) return {
|
|
1526
|
+
remove: /* @__PURE__ */ new Set(),
|
|
1527
|
+
add: /* @__PURE__ */ new Map(),
|
|
1528
|
+
update: /* @__PURE__ */ new Map()
|
|
1529
|
+
};
|
|
1530
|
+
return {
|
|
1531
|
+
removeAll: diff.removeAll,
|
|
1532
|
+
remove: new Set(diff.remove || []),
|
|
1533
|
+
add: new Map(diff.add?.map((feature) => [options.promoteId ? feature.properties?.[options.promoteId] : feature.id, feature])),
|
|
1534
|
+
update: new Map(diff.update?.map((update) => [update.id, update]))
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
var ARRAY_TYPES = [
|
|
1538
|
+
Int8Array,
|
|
1539
|
+
Uint8Array,
|
|
1540
|
+
Uint8ClampedArray,
|
|
1541
|
+
Int16Array,
|
|
1542
|
+
Uint16Array,
|
|
1543
|
+
Int32Array,
|
|
1544
|
+
Uint32Array,
|
|
1545
|
+
Float32Array,
|
|
1546
|
+
Float64Array
|
|
1547
|
+
];
|
|
1548
|
+
var VERSION = 1;
|
|
1549
|
+
var HEADER_SIZE = 8;
|
|
1550
|
+
var STACK = /* @__PURE__ */ new Uint32Array(96);
|
|
1551
|
+
var KDBush = class KDBush2 {
|
|
1552
|
+
/**
|
|
1553
|
+
* Creates an index from raw `ArrayBuffer` data.
|
|
1554
|
+
* @param {ArrayBufferLike} data
|
|
1555
|
+
*/
|
|
1556
|
+
static from(data) {
|
|
1557
|
+
if (!data || data.byteLength === void 0 || data.buffer) throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");
|
|
1558
|
+
const [magic, versionAndType] = new Uint8Array(data, 0, 2);
|
|
1559
|
+
if (magic !== 219) throw new Error("Data does not appear to be in a KDBush format.");
|
|
1560
|
+
const version = versionAndType >> 4;
|
|
1561
|
+
if (version !== VERSION) throw new Error(`Got v${version} data when expected v${VERSION}.`);
|
|
1562
|
+
const ArrayType = ARRAY_TYPES[versionAndType & 15];
|
|
1563
|
+
if (!ArrayType) throw new Error("Unrecognized array type.");
|
|
1564
|
+
const [nodeSize] = new Uint16Array(data, 2, 1);
|
|
1565
|
+
const [numItems] = new Uint32Array(data, 4, 1);
|
|
1566
|
+
return new KDBush2(numItems, nodeSize, ArrayType, void 0, data);
|
|
1567
|
+
}
|
|
1568
|
+
/**
|
|
1569
|
+
* Creates an index that will hold a given number of items.
|
|
1570
|
+
* @param {number} numItems
|
|
1571
|
+
* @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
|
|
1572
|
+
* @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
|
|
1573
|
+
* @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default).
|
|
1574
|
+
* @param {ArrayBufferLike} [data] (For internal use only)
|
|
1575
|
+
*/
|
|
1576
|
+
constructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) {
|
|
1577
|
+
if (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`);
|
|
1578
|
+
this.numItems = +numItems;
|
|
1579
|
+
this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
|
|
1580
|
+
this.ArrayType = ArrayType;
|
|
1581
|
+
this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
|
|
1582
|
+
const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
|
|
1583
|
+
const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
|
|
1584
|
+
const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
|
|
1585
|
+
const padCoords = (8 - idsByteSize % 8) % 8;
|
|
1586
|
+
if (arrayTypeIndex < 0) throw new Error(`Unexpected typed array class: ${ArrayType}.`);
|
|
1587
|
+
if (data) {
|
|
1588
|
+
this.data = data;
|
|
1589
|
+
this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);
|
|
1590
|
+
this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
|
|
1591
|
+
this._pos = numItems * 2;
|
|
1592
|
+
this._finished = true;
|
|
1593
|
+
} else {
|
|
1594
|
+
const data2 = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
|
|
1595
|
+
this.ids = new this.IndexArrayType(data2, HEADER_SIZE, numItems);
|
|
1596
|
+
this.coords = new ArrayType(data2, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
|
|
1597
|
+
this._pos = 0;
|
|
1598
|
+
this._finished = false;
|
|
1599
|
+
new Uint8Array(data2, 0, 2).set([219, 16 + arrayTypeIndex]);
|
|
1600
|
+
new Uint16Array(data2, 2, 1)[0] = nodeSize;
|
|
1601
|
+
new Uint32Array(data2, 4, 1)[0] = numItems;
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
/**
|
|
1605
|
+
* Add a point to the index.
|
|
1606
|
+
* @param {number} x
|
|
1607
|
+
* @param {number} y
|
|
1608
|
+
* @returns {number} An incremental index associated with the added item (starting from `0`).
|
|
1609
|
+
*/
|
|
1610
|
+
add(x, y) {
|
|
1611
|
+
const index = this._pos >> 1;
|
|
1612
|
+
this.ids[index] = index;
|
|
1613
|
+
this.coords[this._pos++] = x;
|
|
1614
|
+
this.coords[this._pos++] = y;
|
|
1615
|
+
return index;
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* Perform indexing of the added points.
|
|
1619
|
+
*/
|
|
1620
|
+
finish() {
|
|
1621
|
+
const numAdded = this._pos >> 1;
|
|
1622
|
+
if (numAdded !== this.numItems) throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
|
|
1623
|
+
sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
|
|
1624
|
+
this._finished = true;
|
|
1625
|
+
return this;
|
|
1626
|
+
}
|
|
1627
|
+
/**
|
|
1628
|
+
* Search the index for items within a given bounding box.
|
|
1629
|
+
* @param {number} minX
|
|
1630
|
+
* @param {number} minY
|
|
1631
|
+
* @param {number} maxX
|
|
1632
|
+
* @param {number} maxY
|
|
1633
|
+
* @returns {number[]} An array of indices correponding to the found items.
|
|
1634
|
+
*/
|
|
1635
|
+
range(minX, minY, maxX, maxY) {
|
|
1636
|
+
if (!this._finished) throw new Error("Data not yet indexed - call index.finish().");
|
|
1637
|
+
const { ids, coords, nodeSize } = this;
|
|
1638
|
+
STACK[0] = 0;
|
|
1639
|
+
STACK[1] = ids.length - 1;
|
|
1640
|
+
STACK[2] = 0;
|
|
1641
|
+
let sp = 3;
|
|
1642
|
+
const result = [];
|
|
1643
|
+
while (sp > 0) {
|
|
1644
|
+
const axis = STACK[--sp];
|
|
1645
|
+
const right = STACK[--sp];
|
|
1646
|
+
const left = STACK[--sp];
|
|
1647
|
+
if (right - left <= nodeSize) {
|
|
1648
|
+
for (let i = left; i <= right; i++) {
|
|
1649
|
+
const x2 = coords[2 * i];
|
|
1650
|
+
const y2 = coords[2 * i + 1];
|
|
1651
|
+
if (x2 >= minX && x2 <= maxX && y2 >= minY && y2 <= maxY) result.push(ids[i]);
|
|
1652
|
+
}
|
|
1653
|
+
continue;
|
|
1654
|
+
}
|
|
1655
|
+
const m = left + right >> 1;
|
|
1656
|
+
const x = coords[2 * m];
|
|
1657
|
+
const y = coords[2 * m + 1];
|
|
1658
|
+
if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
|
|
1659
|
+
if (axis === 0 ? minX <= x : minY <= y) {
|
|
1660
|
+
STACK[sp++] = left;
|
|
1661
|
+
STACK[sp++] = m - 1;
|
|
1662
|
+
STACK[sp++] = 1 - axis;
|
|
1663
|
+
}
|
|
1664
|
+
if (axis === 0 ? maxX >= x : maxY >= y) {
|
|
1665
|
+
STACK[sp++] = m + 1;
|
|
1666
|
+
STACK[sp++] = right;
|
|
1667
|
+
STACK[sp++] = 1 - axis;
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
return result;
|
|
1671
|
+
}
|
|
1672
|
+
/**
|
|
1673
|
+
* Search the index for items within a given radius.
|
|
1674
|
+
* @param {number} qx
|
|
1675
|
+
* @param {number} qy
|
|
1676
|
+
* @param {number} r Query radius.
|
|
1677
|
+
* @returns {number[]} An array of indices correponding to the found items.
|
|
1678
|
+
*/
|
|
1679
|
+
within(qx, qy, r) {
|
|
1680
|
+
const result = [];
|
|
1681
|
+
this.withinInto(qx, qy, r, result);
|
|
1682
|
+
return result;
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* Search the index for items within a given radius, writing matching ids into `out`
|
|
1686
|
+
* via indexed assignment (`out[i] = id`). Accepts any indexed-writable container —
|
|
1687
|
+
* a typed array sized to the expected upper bound (allocation-free, fast) or a plain
|
|
1688
|
+
* `Array` (which will grow as needed). Returns the number of matches written.
|
|
1689
|
+
* @param {number} qx
|
|
1690
|
+
* @param {number} qy
|
|
1691
|
+
* @param {number} r Query radius.
|
|
1692
|
+
* @param {number[] | TypedArray} out Container to write matching ids into.
|
|
1693
|
+
* @returns {number} The number of matches written to `out`.
|
|
1694
|
+
*/
|
|
1695
|
+
withinInto(qx, qy, r, out) {
|
|
1696
|
+
if (!this._finished) throw new Error("Data not yet indexed - call index.finish().");
|
|
1697
|
+
const { ids, coords, nodeSize } = this;
|
|
1698
|
+
STACK[0] = 0;
|
|
1699
|
+
STACK[1] = ids.length - 1;
|
|
1700
|
+
STACK[2] = 0;
|
|
1701
|
+
let sp = 3;
|
|
1702
|
+
let count = 0;
|
|
1703
|
+
const r2 = r * r;
|
|
1704
|
+
while (sp > 0) {
|
|
1705
|
+
const axis = STACK[--sp];
|
|
1706
|
+
const right = STACK[--sp];
|
|
1707
|
+
const left = STACK[--sp];
|
|
1708
|
+
if (right - left <= nodeSize) {
|
|
1709
|
+
for (let i = left; i <= right; i++) if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count++] = ids[i];
|
|
1710
|
+
continue;
|
|
1711
|
+
}
|
|
1712
|
+
const m = left + right >> 1;
|
|
1713
|
+
const x = coords[2 * m];
|
|
1714
|
+
const y = coords[2 * m + 1];
|
|
1715
|
+
if (sqDist(x, y, qx, qy) <= r2) out[count++] = ids[m];
|
|
1716
|
+
if (axis === 0 ? qx - r <= x : qy - r <= y) {
|
|
1717
|
+
STACK[sp++] = left;
|
|
1718
|
+
STACK[sp++] = m - 1;
|
|
1719
|
+
STACK[sp++] = 1 - axis;
|
|
1720
|
+
}
|
|
1721
|
+
if (axis === 0 ? qx + r >= x : qy + r >= y) {
|
|
1722
|
+
STACK[sp++] = m + 1;
|
|
1723
|
+
STACK[sp++] = right;
|
|
1724
|
+
STACK[sp++] = 1 - axis;
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
return count;
|
|
1728
|
+
}
|
|
1729
|
+
};
|
|
1730
|
+
function sort(ids, coords, nodeSize, left, right, axis) {
|
|
1731
|
+
if (right - left <= nodeSize) return;
|
|
1732
|
+
const m = left + right >> 1;
|
|
1733
|
+
select(ids, coords, m, left, right, axis);
|
|
1734
|
+
sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
|
|
1735
|
+
sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
|
|
1736
|
+
}
|
|
1737
|
+
function select(ids, coords, k, left, right, axis) {
|
|
1738
|
+
while (right > left) {
|
|
1739
|
+
if (right - left > 600) {
|
|
1740
|
+
const n = right - left + 1;
|
|
1741
|
+
const m = k - left + 1;
|
|
1742
|
+
const z = Math.log(n);
|
|
1743
|
+
const s = 0.5 * Math.exp(2 * z / 3);
|
|
1744
|
+
const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
|
|
1745
|
+
select(ids, coords, k, Math.max(left, Math.floor(k - m * s / n + sd)), Math.min(right, Math.floor(k + (n - m) * s / n + sd)), axis);
|
|
1746
|
+
}
|
|
1747
|
+
const t = coords[2 * k + axis];
|
|
1748
|
+
let i = left;
|
|
1749
|
+
let j = right;
|
|
1750
|
+
swapItem(ids, coords, left, k);
|
|
1751
|
+
if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);
|
|
1752
|
+
while (i < j) {
|
|
1753
|
+
swapItem(ids, coords, i, j);
|
|
1754
|
+
i++;
|
|
1755
|
+
j--;
|
|
1756
|
+
while (coords[2 * i + axis] < t) i++;
|
|
1757
|
+
while (coords[2 * j + axis] > t) j--;
|
|
1758
|
+
}
|
|
1759
|
+
if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
|
|
1760
|
+
else {
|
|
1761
|
+
j++;
|
|
1762
|
+
swapItem(ids, coords, j, right);
|
|
1763
|
+
}
|
|
1764
|
+
if (j <= k) left = j + 1;
|
|
1765
|
+
if (k <= j) right = j - 1;
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
function swapItem(ids, coords, i, j) {
|
|
1769
|
+
swap(ids, i, j);
|
|
1770
|
+
swap(coords, 2 * i, 2 * j);
|
|
1771
|
+
swap(coords, 2 * i + 1, 2 * j + 1);
|
|
1772
|
+
}
|
|
1773
|
+
function swap(arr, i, j) {
|
|
1774
|
+
const tmp = arr[i];
|
|
1775
|
+
arr[i] = arr[j];
|
|
1776
|
+
arr[j] = tmp;
|
|
1777
|
+
}
|
|
1778
|
+
function sqDist(ax, ay, bx, by) {
|
|
1779
|
+
const dx = ax - bx;
|
|
1780
|
+
const dy = ay - by;
|
|
1781
|
+
return dx * dx + dy * dy;
|
|
1782
|
+
}
|
|
1783
|
+
var defaultClusterOptions = {
|
|
1784
|
+
minZoom: 0,
|
|
1785
|
+
maxZoom: 16,
|
|
1786
|
+
minPoints: 2,
|
|
1787
|
+
radius: 40,
|
|
1788
|
+
extent: 512,
|
|
1789
|
+
nodeSize: 64,
|
|
1790
|
+
log: false,
|
|
1791
|
+
generateId: false,
|
|
1792
|
+
reduce: null,
|
|
1793
|
+
map: (props) => props,
|
|
1794
|
+
coordinates: "lngLat",
|
|
1795
|
+
wrap: true
|
|
1796
|
+
};
|
|
1797
|
+
var MAX_ZOOM = 30;
|
|
1798
|
+
var SCALE = 1073741824;
|
|
1799
|
+
var MAX_INTEGER = 2147483647;
|
|
1800
|
+
function encode(coord) {
|
|
1801
|
+
return (coord - 0.5) * SCALE;
|
|
1802
|
+
}
|
|
1803
|
+
function decode(value) {
|
|
1804
|
+
return value / SCALE + 0.5;
|
|
1805
|
+
}
|
|
1806
|
+
function fitsInteger(coord) {
|
|
1807
|
+
return Math.abs(encode(coord)) < MAX_INTEGER;
|
|
1808
|
+
}
|
|
1809
|
+
var OFFSET_ZOOM = 0;
|
|
1810
|
+
var OFFSET_ID = 1;
|
|
1811
|
+
var OFFSET_PARENT = 2;
|
|
1812
|
+
var OFFSET_NUM = 3;
|
|
1813
|
+
var OFFSET_PROP = 4;
|
|
1814
|
+
var ClusterTileIndex = class {
|
|
1815
|
+
constructor(options) {
|
|
1816
|
+
this.options = createOptions(options);
|
|
1817
|
+
this.worldCoordinateHelper = getWorldCoordinateHelper(this.options.coordinates);
|
|
1818
|
+
this.trees = new Array(this.options.maxZoom + 1);
|
|
1819
|
+
this.stride = this.options.reduce ? 5 : 4;
|
|
1820
|
+
this.clusterProps = [];
|
|
1821
|
+
this.points = [];
|
|
1822
|
+
}
|
|
1823
|
+
/**
|
|
1824
|
+
* Loads GeoJSON Point and MultiPoint features and builds the internal clustering index.
|
|
1825
|
+
* Each position of a MultiPoint is clustered as a point of its own, with the id and properties of its feature.
|
|
1826
|
+
* @param points - GeoJSON Point and MultiPoint features to cluster.
|
|
1827
|
+
*/
|
|
1828
|
+
load(points) {
|
|
1829
|
+
const features = [];
|
|
1830
|
+
for (const point of points) {
|
|
1831
|
+
if (!point.geometry) continue;
|
|
1832
|
+
const positions = point.geometry.type === "MultiPoint" ? point.geometry.coordinates : [point.geometry.coordinates];
|
|
1833
|
+
for (const [lng, lat] of positions) {
|
|
1834
|
+
const [x, y] = [this.worldCoordinateHelper.projectX(lng), this.worldCoordinateHelper.projectY(lat)];
|
|
1835
|
+
if (!this.options.wrap && !isInWorld([x, y])) continue;
|
|
1836
|
+
const feature = {
|
|
1837
|
+
id: point.id,
|
|
1838
|
+
type: "Point",
|
|
1839
|
+
geometry: [x, y],
|
|
1840
|
+
tags: point.properties
|
|
1841
|
+
};
|
|
1842
|
+
features.push(feature);
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
this.createIndex(features);
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* @internal
|
|
1849
|
+
* Loads internal GeoJSONVT point features from a data source and builds the clustering index.
|
|
1850
|
+
* Each position of a MultiPoint feature becomes a point of its own, with the id and properties of its feature.
|
|
1851
|
+
* @param features - {@link GeoJSONVTInternalFeature} data source features to filter and cluster.
|
|
1852
|
+
*/
|
|
1853
|
+
initialize(features) {
|
|
1854
|
+
const points = [];
|
|
1855
|
+
for (const feature of features) {
|
|
1856
|
+
if (feature.type === "Point") {
|
|
1857
|
+
if (!this.options.wrap && !isInWorld(feature.geometry)) continue;
|
|
1858
|
+
points.push(feature);
|
|
1859
|
+
continue;
|
|
1860
|
+
}
|
|
1861
|
+
if (feature.type !== "MultiPoint") continue;
|
|
1862
|
+
for (let i = 0; i < feature.geometry.length; i += 3) {
|
|
1863
|
+
const geometry = [feature.geometry[i], feature.geometry[i + 1]];
|
|
1864
|
+
if (!this.options.wrap && !isInWorld(geometry)) continue;
|
|
1865
|
+
points.push({
|
|
1866
|
+
id: feature.id,
|
|
1867
|
+
type: "Point",
|
|
1868
|
+
geometry,
|
|
1869
|
+
tags: feature.tags
|
|
1870
|
+
});
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
this.createIndex(points);
|
|
1874
|
+
}
|
|
1875
|
+
/**
|
|
1876
|
+
* @internal
|
|
1877
|
+
* Updates the cluster data by rebuilding.
|
|
1878
|
+
* @param features
|
|
1879
|
+
*/
|
|
1880
|
+
updateIndex(features, _affected, options) {
|
|
1881
|
+
this.options = createOptions({
|
|
1882
|
+
...options.clusterOptions,
|
|
1883
|
+
coordinates: this.options.coordinates,
|
|
1884
|
+
wrap: this.options.wrap
|
|
1885
|
+
});
|
|
1886
|
+
this.initialize(features);
|
|
1887
|
+
}
|
|
1888
|
+
/**
|
|
1889
|
+
* Builds a tree per zoom level from the points. A point whose position does not fit in an integer is left out,
|
|
1890
|
+
* see `fitsInteger`.
|
|
1891
|
+
*/
|
|
1892
|
+
createIndex(points) {
|
|
1893
|
+
const { log, minZoom, maxZoom } = this.options;
|
|
1894
|
+
this.trees = new Array(maxZoom + 1);
|
|
1895
|
+
this.stride = this.options.reduce ? 5 : 4;
|
|
1896
|
+
this.clusterProps = [];
|
|
1897
|
+
if (log) console.time("total time");
|
|
1898
|
+
const timerId = `prepare ${points.length} points`;
|
|
1899
|
+
if (log) console.time(timerId);
|
|
1900
|
+
this.points = points;
|
|
1901
|
+
const stride = this.stride;
|
|
1902
|
+
const notProcessed = maxZoom + 1;
|
|
1903
|
+
const coords = new Int32Array(points.length * 2);
|
|
1904
|
+
const data = new Int32Array(points.length * stride);
|
|
1905
|
+
let numItems = 0;
|
|
1906
|
+
for (let i = 0; i < points.length; i++) {
|
|
1907
|
+
const p = points[i];
|
|
1908
|
+
if (!p?.geometry || !fitsInteger(p.geometry[0]) || !fitsInteger(p.geometry[1])) continue;
|
|
1909
|
+
coords[numItems * 2] = Math.round(encode(p.geometry[0]));
|
|
1910
|
+
coords[numItems * 2 + 1] = Math.round(encode(p.geometry[1]));
|
|
1911
|
+
const k = numItems * stride;
|
|
1912
|
+
data[k + OFFSET_ZOOM] = notProcessed;
|
|
1913
|
+
data[k + OFFSET_ID] = i;
|
|
1914
|
+
data[k + OFFSET_PARENT] = -1;
|
|
1915
|
+
data[k + OFFSET_NUM] = 1;
|
|
1916
|
+
numItems++;
|
|
1917
|
+
}
|
|
1918
|
+
let tree = this.trees[maxZoom + 1] = this.createTree(coords, data, numItems);
|
|
1919
|
+
if (log) console.timeEnd(timerId);
|
|
1920
|
+
const nextCoords = new Int32Array(numItems * 2);
|
|
1921
|
+
const nextData = new Int32Array(numItems * stride);
|
|
1922
|
+
for (let z = maxZoom; z >= minZoom; z--) {
|
|
1923
|
+
const now = Date.now();
|
|
1924
|
+
const nextNumItems = this.cluster(tree, z, nextCoords, nextData);
|
|
1925
|
+
if (!this.isSameAsTree(tree, nextData, nextNumItems)) tree = this.createTree(nextCoords.slice(0, nextNumItems * 2), nextData.slice(0, nextNumItems * stride), nextNumItems);
|
|
1926
|
+
this.trees[z] = tree;
|
|
1927
|
+
if (log) console.log("z%d: %d clusters in %dms", z, tree.numItems, Date.now() - now);
|
|
1928
|
+
}
|
|
1929
|
+
if (log) console.timeEnd("total time");
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* Returns clusters and/or points within a bounding box at a given zoom level.
|
|
1933
|
+
* @param bbox - Bounding box in `[westLng, southLat, eastLng, northLat]` order, or `[minX, minY, maxX, maxY]` in the unit square with `coordinates: 'unitSquare'`.
|
|
1934
|
+
* In a world that wraps, the box can reach across the antimeridian. In one that doesn't, only its part inside the world counts.
|
|
1935
|
+
* @param zoom - Zoom level to query.
|
|
1936
|
+
*/
|
|
1937
|
+
getClusters(bbox, zoom) {
|
|
1938
|
+
return (!this.options.wrap ? this.getClustersInWorld(bbox, zoom) : this.options.coordinates === "unitSquare" ? this.getClustersAcrossEdge(bbox, zoom) : this.getClustersInternal(bbox, zoom)).map((f) => featureToGeoJSON(f, this.worldCoordinateHelper));
|
|
1939
|
+
}
|
|
1940
|
+
/**
|
|
1941
|
+
* The clusters and points in the part of a box inside a world that ends at its edges.
|
|
1942
|
+
*/
|
|
1943
|
+
getClustersInWorld(bbox, zoom) {
|
|
1944
|
+
const lngLat = this.options.coordinates !== "unitSquare";
|
|
1945
|
+
const y1 = this.worldCoordinateHelper.projectY(lngLat ? Math.max(-90, Math.min(90, bbox[1])) : bbox[1]);
|
|
1946
|
+
const y2 = this.worldCoordinateHelper.projectY(lngLat ? Math.max(-90, Math.min(90, bbox[3])) : bbox[3]);
|
|
1947
|
+
const minX = Math.max(0, this.worldCoordinateHelper.projectX(bbox[0]));
|
|
1948
|
+
const maxX = Math.min(1, this.worldCoordinateHelper.projectX(bbox[2]));
|
|
1949
|
+
if (minX > maxX) return [];
|
|
1950
|
+
return this.getClustersInRange([
|
|
1951
|
+
minX,
|
|
1952
|
+
Math.min(y1, y2),
|
|
1953
|
+
maxX,
|
|
1954
|
+
Math.max(y1, y2)
|
|
1955
|
+
], zoom);
|
|
1956
|
+
}
|
|
1957
|
+
/**
|
|
1958
|
+
* The clusters and points in a box of a unit square that wraps, where the box can reach across its left or right edge.
|
|
1959
|
+
*/
|
|
1960
|
+
getClustersAcrossEdge([minX, minY, maxX, maxY], zoom) {
|
|
1961
|
+
if (maxX < minX) maxX += 1;
|
|
1962
|
+
if (maxX - minX >= 1) return this.getClustersInRange([
|
|
1963
|
+
0,
|
|
1964
|
+
minY,
|
|
1965
|
+
1,
|
|
1966
|
+
maxY
|
|
1967
|
+
], zoom);
|
|
1968
|
+
const shift = Math.floor(minX);
|
|
1969
|
+
const west = minX - shift;
|
|
1970
|
+
const east = maxX - shift;
|
|
1971
|
+
if (east <= 1) return this.getClustersInRange([
|
|
1972
|
+
west,
|
|
1973
|
+
minY,
|
|
1974
|
+
east,
|
|
1975
|
+
maxY
|
|
1976
|
+
], zoom);
|
|
1977
|
+
return this.getClustersInRange([
|
|
1978
|
+
west,
|
|
1979
|
+
minY,
|
|
1980
|
+
1,
|
|
1981
|
+
maxY
|
|
1982
|
+
], zoom).concat(this.getClustersInRange([
|
|
1983
|
+
0,
|
|
1984
|
+
minY,
|
|
1985
|
+
east - 1,
|
|
1986
|
+
maxY
|
|
1987
|
+
], zoom));
|
|
1988
|
+
}
|
|
1989
|
+
getClustersInternal(bbox, zoom) {
|
|
1990
|
+
let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;
|
|
1991
|
+
const minLat = Math.max(-90, Math.min(90, bbox[1]));
|
|
1992
|
+
let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;
|
|
1993
|
+
const maxLat = Math.max(-90, Math.min(90, bbox[3]));
|
|
1994
|
+
if (bbox[2] - bbox[0] >= 360) {
|
|
1995
|
+
minLng = -180;
|
|
1996
|
+
maxLng = 180;
|
|
1997
|
+
} else if (minLng > maxLng) {
|
|
1998
|
+
const easternHem = this.getClustersInternal([
|
|
1999
|
+
minLng,
|
|
2000
|
+
minLat,
|
|
2001
|
+
180,
|
|
2002
|
+
maxLat
|
|
2003
|
+
], zoom);
|
|
2004
|
+
const westernHem = this.getClustersInternal([
|
|
2005
|
+
-180,
|
|
2006
|
+
minLat,
|
|
2007
|
+
maxLng,
|
|
2008
|
+
maxLat
|
|
2009
|
+
], zoom);
|
|
2010
|
+
return easternHem.concat(westernHem);
|
|
2011
|
+
}
|
|
2012
|
+
return this.getClustersInRange([
|
|
2013
|
+
this.worldCoordinateHelper.projectX(minLng),
|
|
2014
|
+
this.worldCoordinateHelper.projectY(maxLat),
|
|
2015
|
+
this.worldCoordinateHelper.projectX(maxLng),
|
|
2016
|
+
this.worldCoordinateHelper.projectY(minLat)
|
|
2017
|
+
], zoom);
|
|
2018
|
+
}
|
|
2019
|
+
/**
|
|
2020
|
+
* The clusters and points in a box of the internal coordinates, `[minX, minY, maxX, maxY]`.
|
|
2021
|
+
*/
|
|
2022
|
+
getClustersInRange([minX, minY, maxX, maxY], zoom) {
|
|
2023
|
+
const tree = this.trees[this.limitZoom(zoom)];
|
|
2024
|
+
const ids = tree.range(encode(minX), encode(minY), encode(maxX), encode(maxY));
|
|
2025
|
+
const coords = tree.flatCoords;
|
|
2026
|
+
const data = tree.flatData;
|
|
2027
|
+
const clusters = [];
|
|
2028
|
+
for (const id of ids) {
|
|
2029
|
+
const k = this.stride * id;
|
|
2030
|
+
clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterFeature(coords, id, data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);
|
|
2031
|
+
}
|
|
2032
|
+
return clusters;
|
|
2033
|
+
}
|
|
2034
|
+
/**
|
|
2035
|
+
* Returns the immediate children (clusters or points) of a cluster as GeoJSON.
|
|
2036
|
+
* @param clusterId - The target cluster id.
|
|
2037
|
+
*/
|
|
2038
|
+
getChildren(clusterId) {
|
|
2039
|
+
const originId = this.getOriginId(clusterId);
|
|
2040
|
+
const originZoom = this.getOriginZoom(clusterId);
|
|
2041
|
+
const clusterError = /* @__PURE__ */ new Error("No cluster with the specified id: " + clusterId);
|
|
2042
|
+
const tree = this.trees[originZoom];
|
|
2043
|
+
if (!tree) throw clusterError;
|
|
2044
|
+
const coords = tree.flatCoords;
|
|
2045
|
+
const data = tree.flatData;
|
|
2046
|
+
if (originId >= tree.numItems) throw clusterError;
|
|
2047
|
+
const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1)) * SCALE;
|
|
2048
|
+
const x = coords[originId * 2];
|
|
2049
|
+
const y = coords[originId * 2 + 1];
|
|
2050
|
+
const ids = tree.within(x, y, r);
|
|
2051
|
+
const children = [];
|
|
2052
|
+
for (const id of ids) {
|
|
2053
|
+
const k = id * this.stride;
|
|
2054
|
+
if (data[k + OFFSET_PARENT] === clusterId) children.push(data[k + OFFSET_NUM] > 1 ? getClusterGeoJSON(coords, id, data, k, this.clusterProps, this.worldCoordinateHelper) : featureToGeoJSON(this.points[data[k + OFFSET_ID]], this.worldCoordinateHelper));
|
|
2055
|
+
}
|
|
2056
|
+
if (children.length === 0) throw clusterError;
|
|
2057
|
+
return children;
|
|
2058
|
+
}
|
|
2059
|
+
/**
|
|
2060
|
+
* Returns leaf point features under a cluster, paginated by `limit` and `offset`.
|
|
2061
|
+
* @param clusterId - The target cluster id.
|
|
2062
|
+
* @param limit - Maximum number of points to return (defaults to `10`).
|
|
2063
|
+
* @param offset - Number of points to skip before collecting results (defaults to `0`).
|
|
2064
|
+
*/
|
|
2065
|
+
getLeaves(clusterId, limit, offset) {
|
|
2066
|
+
limit = limit || 10;
|
|
2067
|
+
offset = offset || 0;
|
|
2068
|
+
const leaves = [];
|
|
2069
|
+
this.appendLeaves(leaves, clusterId, limit, offset, 0);
|
|
2070
|
+
return leaves;
|
|
2071
|
+
}
|
|
2072
|
+
/**
|
|
2073
|
+
* Generates a vector-tile-like representation of a single tile.
|
|
2074
|
+
* @param z - Tile zoom.
|
|
2075
|
+
* @param x - Tile x coordinate.
|
|
2076
|
+
* @param y - Tile y coordinate.
|
|
2077
|
+
*/
|
|
2078
|
+
getTile(z, x, y) {
|
|
2079
|
+
const tree = this.trees[this.limitZoom(z)];
|
|
2080
|
+
if (!tree) return null;
|
|
2081
|
+
const z2 = Math.pow(2, z);
|
|
2082
|
+
if (!this.options.wrap && (x < 0 || x >= z2 || y < 0 || y >= z2)) return null;
|
|
2083
|
+
const { extent, radius } = this.options;
|
|
2084
|
+
const p = radius / extent;
|
|
2085
|
+
const top = encode((y - p) / z2);
|
|
2086
|
+
const bottom = encode((y + 1 + p) / z2);
|
|
2087
|
+
const tile = {
|
|
2088
|
+
transformed: true,
|
|
2089
|
+
features: [],
|
|
2090
|
+
source: null,
|
|
2091
|
+
x,
|
|
2092
|
+
y,
|
|
2093
|
+
z
|
|
2094
|
+
};
|
|
2095
|
+
this.addTileFeatures(tree.range(encode((x - p) / z2), top, encode((x + 1 + p) / z2), bottom), tree, x, y, z2, tile);
|
|
2096
|
+
if (this.options.wrap && x === 0) this.addTileFeatures(tree.range(encode(1 - p / z2), top, encode(1), bottom), tree, z2, y, z2, tile);
|
|
2097
|
+
if (this.options.wrap && x === z2 - 1) this.addTileFeatures(tree.range(encode(0), top, encode(p / z2), bottom), tree, -1, y, z2, tile);
|
|
2098
|
+
return tile;
|
|
2099
|
+
}
|
|
2100
|
+
/**
|
|
2101
|
+
* Returns the zoom level at which a cluster expands into multiple children.
|
|
2102
|
+
* @param clusterId - The target cluster id.
|
|
2103
|
+
*/
|
|
2104
|
+
getClusterExpansionZoom(clusterId) {
|
|
2105
|
+
return this.getOriginZoom(clusterId);
|
|
2106
|
+
}
|
|
2107
|
+
appendLeaves(result, clusterId, limit, offset, skipped) {
|
|
2108
|
+
const children = this.getChildren(clusterId);
|
|
2109
|
+
for (const child of children) {
|
|
2110
|
+
const props = child.properties;
|
|
2111
|
+
if (props?.cluster) {
|
|
2112
|
+
if (skipped + props.point_count <= offset) skipped += props.point_count;
|
|
2113
|
+
else skipped = this.appendLeaves(result, props.cluster_id, limit, offset, skipped);
|
|
2114
|
+
} else if (skipped < offset) skipped++;
|
|
2115
|
+
else result.push(child);
|
|
2116
|
+
if (result.length === limit) break;
|
|
2117
|
+
}
|
|
2118
|
+
return skipped;
|
|
2119
|
+
}
|
|
2120
|
+
createTree(coords, data, numItems) {
|
|
2121
|
+
const tree = new KDBush(numItems, this.options.nodeSize, Int32Array);
|
|
2122
|
+
for (let i = 0; i < numItems; i++) tree.add(coords[i * 2], coords[i * 2 + 1]);
|
|
2123
|
+
tree.finish();
|
|
2124
|
+
tree.flatCoords = coords;
|
|
2125
|
+
tree.flatData = data;
|
|
2126
|
+
tree.data = null;
|
|
2127
|
+
return tree;
|
|
2128
|
+
}
|
|
2129
|
+
/**
|
|
2130
|
+
* Whether clustering a tree left all its points and clusters as they were, in the same order.
|
|
2131
|
+
*/
|
|
2132
|
+
isSameAsTree(tree, nextData, nextNumItems) {
|
|
2133
|
+
if (nextNumItems !== tree.numItems) return false;
|
|
2134
|
+
const data = tree.flatData;
|
|
2135
|
+
for (let k = OFFSET_ID; k < nextNumItems * this.stride; k += this.stride) if (nextData[k] !== data[k]) return false;
|
|
2136
|
+
return true;
|
|
2137
|
+
}
|
|
2138
|
+
addTileFeatures(ids, tree, x, y, z2, tile) {
|
|
2139
|
+
const coords = tree.flatCoords;
|
|
2140
|
+
const data = tree.flatData;
|
|
2141
|
+
for (const i of ids) {
|
|
2142
|
+
const k = i * this.stride;
|
|
2143
|
+
const isCluster = data[k + OFFSET_NUM] > 1;
|
|
2144
|
+
let tags;
|
|
2145
|
+
let px;
|
|
2146
|
+
let py;
|
|
2147
|
+
if (isCluster) {
|
|
2148
|
+
tags = getClusterProperties(data, k, this.clusterProps);
|
|
2149
|
+
px = decode(coords[i * 2]);
|
|
2150
|
+
py = decode(coords[i * 2 + 1]);
|
|
2151
|
+
} else {
|
|
2152
|
+
const p = this.points[data[k + OFFSET_ID]];
|
|
2153
|
+
tags = p.tags;
|
|
2154
|
+
[px, py] = p.geometry;
|
|
2155
|
+
}
|
|
2156
|
+
const f = {
|
|
2157
|
+
type: 1,
|
|
2158
|
+
geometry: [[Math.round(this.options.extent * (px * z2 - x)), Math.round(this.options.extent * (py * z2 - y))]],
|
|
2159
|
+
tags
|
|
2160
|
+
};
|
|
2161
|
+
let id;
|
|
2162
|
+
if (isCluster || this.options.generateId) id = data[k + OFFSET_ID];
|
|
2163
|
+
else id = this.points[data[k + OFFSET_ID]].id;
|
|
2164
|
+
if (id !== void 0) f.id = id;
|
|
2165
|
+
tile.features.push(f);
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
limitZoom(z) {
|
|
2169
|
+
return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1));
|
|
2170
|
+
}
|
|
2171
|
+
/**
|
|
2172
|
+
* Clusters the points of a tree on a zoom level, writing the result to `nextCoords` and `nextData`.
|
|
2173
|
+
* @returns the number of points and clusters written
|
|
2174
|
+
*/
|
|
2175
|
+
cluster(tree, zoom, nextCoords, nextData) {
|
|
2176
|
+
const { radius, extent, reduce, minPoints, maxZoom } = this.options;
|
|
2177
|
+
const r = radius / (extent * Math.pow(2, zoom)) * SCALE;
|
|
2178
|
+
const notProcessed = maxZoom + 1;
|
|
2179
|
+
const coords = tree.flatCoords;
|
|
2180
|
+
const data = tree.flatData;
|
|
2181
|
+
const stride = this.stride;
|
|
2182
|
+
const neighborIds = new Uint32Array(tree.numItems);
|
|
2183
|
+
let nextNumItems = 0;
|
|
2184
|
+
for (let index = 0; index < tree.numItems; index++) {
|
|
2185
|
+
const i = index * stride;
|
|
2186
|
+
if (data[i + OFFSET_ZOOM] <= zoom) continue;
|
|
2187
|
+
data[i + OFFSET_ZOOM] = zoom;
|
|
2188
|
+
const x = coords[index * 2];
|
|
2189
|
+
const y = coords[index * 2 + 1];
|
|
2190
|
+
const numNeighbors = tree.withinInto(x, y, r, neighborIds);
|
|
2191
|
+
const numPointsOrigin = data[i + OFFSET_NUM];
|
|
2192
|
+
let numPoints = numPointsOrigin;
|
|
2193
|
+
for (let n = 0; n < numNeighbors; n++) {
|
|
2194
|
+
const k = neighborIds[n] * stride;
|
|
2195
|
+
if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM];
|
|
2196
|
+
}
|
|
2197
|
+
if (numPoints > numPointsOrigin && numPoints >= minPoints) {
|
|
2198
|
+
let wx = x * numPointsOrigin;
|
|
2199
|
+
let wy = y * numPointsOrigin;
|
|
2200
|
+
let clusterProperties;
|
|
2201
|
+
let clusterPropIndex = -1;
|
|
2202
|
+
const id = (index << 5) + (zoom + 1) + this.points.length;
|
|
2203
|
+
for (let n = 0; n < numNeighbors; n++) {
|
|
2204
|
+
const neighborIndex = neighborIds[n];
|
|
2205
|
+
const k = neighborIndex * stride;
|
|
2206
|
+
if (data[k + OFFSET_ZOOM] <= zoom) continue;
|
|
2207
|
+
data[k + OFFSET_ZOOM] = zoom;
|
|
2208
|
+
const numPoints2 = data[k + OFFSET_NUM];
|
|
2209
|
+
wx += coords[neighborIndex * 2] * numPoints2;
|
|
2210
|
+
wy += coords[neighborIndex * 2 + 1] * numPoints2;
|
|
2211
|
+
data[k + OFFSET_PARENT] = id;
|
|
2212
|
+
if (reduce) {
|
|
2213
|
+
if (!clusterProperties) {
|
|
2214
|
+
clusterProperties = this.map(data, i, true);
|
|
2215
|
+
clusterPropIndex = this.clusterProps.length;
|
|
2216
|
+
this.clusterProps.push(clusterProperties);
|
|
2217
|
+
}
|
|
2218
|
+
reduce(clusterProperties, this.map(data, k));
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
data[i + OFFSET_PARENT] = id;
|
|
2222
|
+
nextCoords[nextNumItems * 2] = Math.round(wx / numPoints);
|
|
2223
|
+
nextCoords[nextNumItems * 2 + 1] = Math.round(wy / numPoints);
|
|
2224
|
+
const next = nextNumItems * stride;
|
|
2225
|
+
nextData[next + OFFSET_ZOOM] = notProcessed;
|
|
2226
|
+
nextData[next + OFFSET_ID] = id;
|
|
2227
|
+
nextData[next + OFFSET_PARENT] = -1;
|
|
2228
|
+
nextData[next + OFFSET_NUM] = numPoints;
|
|
2229
|
+
if (reduce) nextData[next + OFFSET_PROP] = clusterPropIndex;
|
|
2230
|
+
nextNumItems++;
|
|
2231
|
+
} else {
|
|
2232
|
+
nextCoords[nextNumItems * 2] = x;
|
|
2233
|
+
nextCoords[nextNumItems * 2 + 1] = y;
|
|
2234
|
+
for (let j = 0; j < stride; j++) nextData[nextNumItems * stride + j] = data[i + j];
|
|
2235
|
+
nextNumItems++;
|
|
2236
|
+
if (numPoints > 1) for (let n = 0; n < numNeighbors; n++) {
|
|
2237
|
+
const neighborIndex = neighborIds[n];
|
|
2238
|
+
const k = neighborIndex * stride;
|
|
2239
|
+
if (data[k + OFFSET_ZOOM] <= zoom) continue;
|
|
2240
|
+
data[k + OFFSET_ZOOM] = zoom;
|
|
2241
|
+
nextCoords[nextNumItems * 2] = coords[neighborIndex * 2];
|
|
2242
|
+
nextCoords[nextNumItems * 2 + 1] = coords[neighborIndex * 2 + 1];
|
|
2243
|
+
for (let j = 0; j < stride; j++) nextData[nextNumItems * stride + j] = data[k + j];
|
|
2244
|
+
nextNumItems++;
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
return nextNumItems;
|
|
2249
|
+
}
|
|
2250
|
+
getOriginId(clusterId) {
|
|
2251
|
+
return clusterId - this.points.length >> 5;
|
|
2252
|
+
}
|
|
2253
|
+
getOriginZoom(clusterId) {
|
|
2254
|
+
return (clusterId - this.points.length) % 32;
|
|
2255
|
+
}
|
|
2256
|
+
map(data, i, clone) {
|
|
2257
|
+
if (data[i + OFFSET_NUM] > 1) {
|
|
2258
|
+
const props = this.clusterProps[data[i + OFFSET_PROP]];
|
|
2259
|
+
return clone ? Object.assign({}, props) : props;
|
|
2260
|
+
}
|
|
2261
|
+
const original = this.points[data[i + OFFSET_ID]].tags;
|
|
2262
|
+
const result = this.options.map(original);
|
|
2263
|
+
return clone && result === original ? Object.assign({}, result) : result;
|
|
2264
|
+
}
|
|
2265
|
+
};
|
|
2266
|
+
function createOptions(options) {
|
|
2267
|
+
const result = Object.assign(Object.create(defaultClusterOptions), options);
|
|
2268
|
+
result.minZoom = Math.min(result.minZoom, MAX_ZOOM);
|
|
2269
|
+
result.maxZoom = Math.min(result.maxZoom, MAX_ZOOM);
|
|
2270
|
+
return result;
|
|
2271
|
+
}
|
|
2272
|
+
function getClusterFeature(coords, index, data, i, clusterProps) {
|
|
2273
|
+
return {
|
|
2274
|
+
id: data[i + OFFSET_ID],
|
|
2275
|
+
type: "Point",
|
|
2276
|
+
tags: getClusterProperties(data, i, clusterProps),
|
|
2277
|
+
geometry: [decode(coords[index * 2]), decode(coords[index * 2 + 1])]
|
|
2278
|
+
};
|
|
2279
|
+
}
|
|
2280
|
+
function getClusterGeoJSON(coords, index, data, i, clusterProps, worldCoordinateHelper) {
|
|
2281
|
+
return {
|
|
2282
|
+
type: "Feature",
|
|
2283
|
+
id: data[i + OFFSET_ID],
|
|
2284
|
+
properties: getClusterProperties(data, i, clusterProps),
|
|
2285
|
+
geometry: {
|
|
2286
|
+
type: "Point",
|
|
2287
|
+
coordinates: [worldCoordinateHelper.unprojectX(decode(coords[index * 2])), worldCoordinateHelper.unprojectY(decode(coords[index * 2 + 1]))]
|
|
2288
|
+
}
|
|
2289
|
+
};
|
|
2290
|
+
}
|
|
2291
|
+
function getClusterProperties(data, i, clusterProps) {
|
|
2292
|
+
const count = data[i + OFFSET_NUM];
|
|
2293
|
+
const abbrev = count >= 1e4 ? `${Math.round(count / 1e3)}k` : count >= 1e3 ? `${Math.round(count / 100) / 10}k` : count;
|
|
2294
|
+
const propIndex = data[i + OFFSET_PROP];
|
|
2295
|
+
const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]);
|
|
2296
|
+
return Object.assign(properties, {
|
|
2297
|
+
cluster: true,
|
|
2298
|
+
cluster_id: data[i + OFFSET_ID],
|
|
2299
|
+
point_count: count,
|
|
2300
|
+
point_count_abbreviated: abbrev
|
|
2301
|
+
});
|
|
2302
|
+
}
|
|
2303
|
+
function isInWorld(geometry) {
|
|
2304
|
+
return geometry[0] >= 0 && geometry[0] <= 1 && geometry[1] >= 0 && geometry[1] <= 1;
|
|
2305
|
+
}
|
|
2306
|
+
var GEOJSONVT_CLIP_START = "geojsonvt_clip_start";
|
|
2307
|
+
var GEOJSONVT_CLIP_END = "geojsonvt_clip_end";
|
|
2308
|
+
function createTile(features, z, tx, ty, options) {
|
|
2309
|
+
const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
|
|
2310
|
+
const tile = {
|
|
2311
|
+
transformed: false,
|
|
2312
|
+
features: [],
|
|
2313
|
+
source: null,
|
|
2314
|
+
x: tx,
|
|
2315
|
+
y: ty,
|
|
2316
|
+
z,
|
|
2317
|
+
minX: 2,
|
|
2318
|
+
minY: 1,
|
|
2319
|
+
maxX: -1,
|
|
2320
|
+
maxY: 0,
|
|
2321
|
+
numPoints: 0,
|
|
2322
|
+
numSimplified: 0,
|
|
2323
|
+
numFeatures: features.length
|
|
2324
|
+
};
|
|
2325
|
+
for (const feature of features) addFeature(tile, feature, tolerance, options);
|
|
2326
|
+
return tile;
|
|
2327
|
+
}
|
|
2328
|
+
function addFeature(tile, feature, tolerance, options) {
|
|
2329
|
+
tile.minX = Math.min(tile.minX, feature.minX);
|
|
2330
|
+
tile.minY = Math.min(tile.minY, feature.minY);
|
|
2331
|
+
tile.maxX = Math.max(tile.maxX, feature.maxX);
|
|
2332
|
+
tile.maxY = Math.max(tile.maxY, feature.maxY);
|
|
2333
|
+
switch (feature.type) {
|
|
2334
|
+
case "Point":
|
|
2335
|
+
case "MultiPoint":
|
|
2336
|
+
addPointsTileFeature(tile, feature);
|
|
2337
|
+
return;
|
|
2338
|
+
case "LineString":
|
|
2339
|
+
addLineTileFeautre(tile, feature, tolerance, options);
|
|
2340
|
+
return;
|
|
2341
|
+
case "MultiLineString":
|
|
2342
|
+
case "Polygon":
|
|
2343
|
+
addLinesTileFeature(tile, feature, tolerance);
|
|
2344
|
+
return;
|
|
2345
|
+
case "MultiPolygon":
|
|
2346
|
+
addMultiPolygonTileFeature(tile, feature, tolerance);
|
|
2347
|
+
return;
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
function addPointsTileFeature(tile, feature) {
|
|
2351
|
+
const geometry = [];
|
|
2352
|
+
for (let i = 0; i < feature.geometry.length; i += 3) {
|
|
2353
|
+
geometry.push(feature.geometry[i], feature.geometry[i + 1]);
|
|
2354
|
+
tile.numPoints++;
|
|
2355
|
+
tile.numSimplified++;
|
|
2356
|
+
}
|
|
2357
|
+
if (!geometry.length) return;
|
|
2358
|
+
const tileFeature = {
|
|
2359
|
+
type: 1,
|
|
2360
|
+
tags: feature.tags || null,
|
|
2361
|
+
geometry
|
|
2362
|
+
};
|
|
2363
|
+
if (feature.id !== null) tileFeature.id = feature.id;
|
|
2364
|
+
tile.features.push(tileFeature);
|
|
2365
|
+
}
|
|
2366
|
+
function addLineTileFeautre(tile, feature, tolerance, options) {
|
|
2367
|
+
const geometry = [];
|
|
2368
|
+
addLine(geometry, feature.geometry, tile, tolerance, false, false);
|
|
2369
|
+
if (!geometry.length) return;
|
|
2370
|
+
let tags = feature.tags || null;
|
|
2371
|
+
if (options.lineMetrics) {
|
|
2372
|
+
tags = {};
|
|
2373
|
+
for (const key in feature.tags) tags[key] = feature.tags[key];
|
|
2374
|
+
tags[GEOJSONVT_CLIP_START] = feature.geometry.start / feature.geometry.size;
|
|
2375
|
+
tags[GEOJSONVT_CLIP_END] = feature.geometry.end / feature.geometry.size;
|
|
2376
|
+
}
|
|
2377
|
+
const tileFeature = {
|
|
2378
|
+
type: 2,
|
|
2379
|
+
tags,
|
|
2380
|
+
geometry
|
|
2381
|
+
};
|
|
2382
|
+
if (feature.id !== null) tileFeature.id = feature.id;
|
|
2383
|
+
tile.features.push(tileFeature);
|
|
2384
|
+
}
|
|
2385
|
+
function addLinesTileFeature(tile, feature, tolerance) {
|
|
2386
|
+
const geometry = [];
|
|
2387
|
+
for (let i = 0; i < feature.geometry.length; i++) addLine(geometry, feature.geometry[i], tile, tolerance, feature.type === "Polygon", i === 0);
|
|
2388
|
+
if (!geometry.length) return;
|
|
2389
|
+
const tileFeature = {
|
|
2390
|
+
type: feature.type === "Polygon" ? 3 : 2,
|
|
2391
|
+
tags: feature.tags || null,
|
|
2392
|
+
geometry
|
|
2393
|
+
};
|
|
2394
|
+
if (feature.id !== null) tileFeature.id = feature.id;
|
|
2395
|
+
tile.features.push(tileFeature);
|
|
2396
|
+
}
|
|
2397
|
+
function addMultiPolygonTileFeature(tile, feature, tolerance) {
|
|
2398
|
+
const geometry = [];
|
|
2399
|
+
for (let k = 0; k < feature.geometry.length; k++) {
|
|
2400
|
+
const polygon = feature.geometry[k];
|
|
2401
|
+
for (let i = 0; i < polygon.length; i++) addLine(geometry, polygon[i], tile, tolerance, true, i === 0);
|
|
2402
|
+
}
|
|
2403
|
+
if (!geometry.length) return;
|
|
2404
|
+
const tileFeature = {
|
|
2405
|
+
type: 3,
|
|
2406
|
+
tags: feature.tags || null,
|
|
2407
|
+
geometry
|
|
2408
|
+
};
|
|
2409
|
+
if (feature.id !== null) tileFeature.id = feature.id;
|
|
2410
|
+
tile.features.push(tileFeature);
|
|
2411
|
+
}
|
|
2412
|
+
function addLine(result, geom, tile, tolerance, isPolygon, isOuter) {
|
|
2413
|
+
const sqTolerance = tolerance * tolerance;
|
|
2414
|
+
if (tolerance > 0 && geom.size < (isPolygon ? sqTolerance : tolerance)) {
|
|
2415
|
+
tile.numPoints += geom.points.length / 3;
|
|
2416
|
+
return;
|
|
2417
|
+
}
|
|
2418
|
+
const ring = [];
|
|
2419
|
+
for (let i = 0; i < geom.points.length; i += 3) {
|
|
2420
|
+
if (tolerance === 0 || geom.points[i + 2] > sqTolerance) {
|
|
2421
|
+
tile.numSimplified++;
|
|
2422
|
+
ring.push(geom.points[i], geom.points[i + 1]);
|
|
2423
|
+
}
|
|
2424
|
+
tile.numPoints++;
|
|
2425
|
+
}
|
|
2426
|
+
if (isPolygon) rewind(ring, isOuter);
|
|
2427
|
+
result.push(ring);
|
|
2428
|
+
}
|
|
2429
|
+
function rewind(ring, clockwise) {
|
|
2430
|
+
let area = 0;
|
|
2431
|
+
for (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);
|
|
2432
|
+
if (area > 0 !== clockwise) return;
|
|
2433
|
+
for (let i = 0, len = ring.length; i < len / 2; i += 2) {
|
|
2434
|
+
const x = ring[i];
|
|
2435
|
+
const y = ring[i + 1];
|
|
2436
|
+
ring[i] = ring[len - 2 - i];
|
|
2437
|
+
ring[i + 1] = ring[len - 1 - i];
|
|
2438
|
+
ring[len - 2 - i] = x;
|
|
2439
|
+
ring[len - 1 - i] = y;
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
function transformTile(tile, extent) {
|
|
2443
|
+
if (tile.transformed) return tile;
|
|
2444
|
+
const z2 = 1 << tile.z;
|
|
2445
|
+
const tx = tile.x;
|
|
2446
|
+
const ty = tile.y;
|
|
2447
|
+
for (const feature of tile.features) if (feature.type === 1) transformPointFeature(feature, extent, z2, tx, ty);
|
|
2448
|
+
else transformNonPointFeature(feature, extent, z2, tx, ty);
|
|
2449
|
+
tile.transformed = true;
|
|
2450
|
+
return tile;
|
|
2451
|
+
}
|
|
2452
|
+
function transformPointFeature(feature, extent, z2, tx, ty) {
|
|
2453
|
+
const transformed = feature;
|
|
2454
|
+
const geometry = feature.geometry;
|
|
2455
|
+
const point = [];
|
|
2456
|
+
for (let i = 0; i < geometry.length; i += 2) point.push(transformPoint(geometry[i], geometry[i + 1], extent, z2, tx, ty));
|
|
2457
|
+
transformed.geometry = point;
|
|
2458
|
+
return transformed;
|
|
2459
|
+
}
|
|
2460
|
+
function transformNonPointFeature(feature, extent, z2, tx, ty) {
|
|
2461
|
+
const transformed = feature;
|
|
2462
|
+
const geometry = feature.geometry;
|
|
2463
|
+
const nonPoint = [];
|
|
2464
|
+
for (const geom of geometry) {
|
|
2465
|
+
const ring = [];
|
|
2466
|
+
for (let i = 0; i < geom.length; i += 2) ring.push(transformPoint(geom[i], geom[i + 1], extent, z2, tx, ty));
|
|
2467
|
+
nonPoint.push(ring);
|
|
2468
|
+
}
|
|
2469
|
+
transformed.geometry = nonPoint;
|
|
2470
|
+
return transformed;
|
|
2471
|
+
}
|
|
2472
|
+
function transformPoint(x, y, extent, z2, tx, ty) {
|
|
2473
|
+
return [Math.round(extent * (x * z2 - tx)), Math.round(extent * (y * z2 - ty))];
|
|
2474
|
+
}
|
|
2475
|
+
var TileIndex = class {
|
|
2476
|
+
constructor(options) {
|
|
2477
|
+
this.options = options;
|
|
2478
|
+
this.total = 0;
|
|
2479
|
+
this.stats = {};
|
|
2480
|
+
this.tiles = {};
|
|
2481
|
+
this.tileCoords = [];
|
|
2482
|
+
this.stats = {};
|
|
2483
|
+
this.total = 0;
|
|
2484
|
+
}
|
|
2485
|
+
initialize(features) {
|
|
2486
|
+
this.splitTile(this.clipToWorld(features), 0, 0, 0);
|
|
2487
|
+
if (this.options.debug) {
|
|
2488
|
+
if (features.length) console.log("features: %d, points: %d", this.tiles[0].numFeatures, this.tiles[0].numPoints);
|
|
2489
|
+
console.timeEnd("generate tiles");
|
|
2490
|
+
console.log("tiles generated:", this.total, JSON.stringify(this.stats));
|
|
2491
|
+
}
|
|
2492
|
+
}
|
|
2493
|
+
/** {@inheritdoc} */
|
|
2494
|
+
updateIndex(source, affected, options) {
|
|
2495
|
+
if (options.debug > 1) {
|
|
2496
|
+
console.log("invalidating tiles");
|
|
2497
|
+
console.time("invalidating");
|
|
2498
|
+
}
|
|
2499
|
+
this.invalidateTiles(affected);
|
|
2500
|
+
if (options.debug > 1) console.timeEnd("invalidating");
|
|
2501
|
+
const [z, x, y] = [
|
|
2502
|
+
0,
|
|
2503
|
+
0,
|
|
2504
|
+
0
|
|
2505
|
+
];
|
|
2506
|
+
const rootSource = this.clipToWorld(source);
|
|
2507
|
+
const rootTile = createTile(rootSource, z, x, y, options);
|
|
2508
|
+
rootTile.source = rootSource;
|
|
2509
|
+
const id = toID(z, x, y);
|
|
2510
|
+
this.tiles[id] = rootTile;
|
|
2511
|
+
this.tileCoords.push({
|
|
2512
|
+
z,
|
|
2513
|
+
x,
|
|
2514
|
+
y,
|
|
2515
|
+
id
|
|
2516
|
+
});
|
|
2517
|
+
if (options.debug) {
|
|
2518
|
+
const key = `z${z}`;
|
|
2519
|
+
this.stats[key] = (this.stats[key] || 0) + 1;
|
|
2520
|
+
this.total++;
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
/** {@inheritdoc} */
|
|
2524
|
+
getClusterExpansionZoom(_clusterId) {
|
|
2525
|
+
return null;
|
|
2526
|
+
}
|
|
2527
|
+
/** {@inheritdoc} */
|
|
2528
|
+
getChildren(_clusterId) {
|
|
2529
|
+
return null;
|
|
2530
|
+
}
|
|
2531
|
+
/** {@inheritdoc} */
|
|
2532
|
+
getLeaves(_clusterId, _limit, _offset) {
|
|
2533
|
+
return null;
|
|
2534
|
+
}
|
|
2535
|
+
/** {@inheritdoc} */
|
|
2536
|
+
getTile(z, x, y) {
|
|
2537
|
+
const { extent, debug } = this.options;
|
|
2538
|
+
const z2 = 1 << z;
|
|
2539
|
+
if (!this.options.wrap && (x < 0 || x >= z2)) return null;
|
|
2540
|
+
x = x + z2 & z2 - 1;
|
|
2541
|
+
const id = toID(z, x, y);
|
|
2542
|
+
if (this.tiles[id]) return transformTile(this.tiles[id], extent);
|
|
2543
|
+
if (debug > 1) console.log("drilling down to z%d-%d-%d", z, x, y);
|
|
2544
|
+
let z0 = z;
|
|
2545
|
+
let x0 = x;
|
|
2546
|
+
let y0 = y;
|
|
2547
|
+
let parent;
|
|
2548
|
+
while (!parent && z0 > 0) {
|
|
2549
|
+
z0--;
|
|
2550
|
+
x0 = x0 >> 1;
|
|
2551
|
+
y0 = y0 >> 1;
|
|
2552
|
+
parent = this.tiles[toID(z0, x0, y0)];
|
|
2553
|
+
}
|
|
2554
|
+
if (!parent?.source) return null;
|
|
2555
|
+
if (debug > 1) {
|
|
2556
|
+
console.log("found parent tile z%d-%d-%d", z0, x0, y0);
|
|
2557
|
+
console.time("drilling down");
|
|
2558
|
+
}
|
|
2559
|
+
this.splitTile(parent.source, z0, x0, y0, z, x, y);
|
|
2560
|
+
if (debug > 1) console.timeEnd("drilling down");
|
|
2561
|
+
if (!this.tiles[id]) return null;
|
|
2562
|
+
return transformTile(this.tiles[id], extent);
|
|
2563
|
+
}
|
|
2564
|
+
/**
|
|
2565
|
+
* The features the top tile starts from. A world that wraps keeps them all left and right, where wrapping already
|
|
2566
|
+
* put them inside, and one that doesn't only what lies inside the world square and its buffer. Positions in the
|
|
2567
|
+
* unit square are also cut above and below in a world that wraps, where lng/lat is clamped already. The index keeps
|
|
2568
|
+
* the rest, so an update can still move a feature in from outside.
|
|
2569
|
+
*/
|
|
2570
|
+
clipToWorld(features) {
|
|
2571
|
+
const { wrap: wrap2, coordinates } = this.options;
|
|
2572
|
+
if (wrap2 && coordinates !== "unitSquare") return features;
|
|
2573
|
+
const buffer = this.options.buffer / this.options.extent;
|
|
2574
|
+
return clip(wrap2 ? features : clip(features, 1, -buffer, 1 + buffer, 0, -Infinity, Infinity, this.options) || [], 1, -buffer, 1 + buffer, 1, -Infinity, Infinity, this.options) || [];
|
|
2575
|
+
}
|
|
2576
|
+
/**
|
|
2577
|
+
* splits features from a parent tile to sub-tiles.
|
|
2578
|
+
* z, x, and y are the coordinates of the parent tile
|
|
2579
|
+
* cz, cx, and cy are the coordinates of the target tile
|
|
2580
|
+
*
|
|
2581
|
+
* If no target tile is specified, splitting stops when we reach the maximum
|
|
2582
|
+
* zoom or the number of points is low as specified in the options.
|
|
2583
|
+
* @internal
|
|
2584
|
+
* @param features - features to split
|
|
2585
|
+
* @param z - tile zoom level
|
|
2586
|
+
* @param x - tile x coordinate
|
|
2587
|
+
* @param y - tile y coordinate
|
|
2588
|
+
* @param cz - target tile zoom level
|
|
2589
|
+
* @param cx - target tile x coordinate
|
|
2590
|
+
* @param cy - target tile y coordinate
|
|
2591
|
+
*/
|
|
2592
|
+
splitTile(features, z, x, y, cz, cx, cy) {
|
|
2593
|
+
const stack = [
|
|
2594
|
+
features,
|
|
2595
|
+
z,
|
|
2596
|
+
x,
|
|
2597
|
+
y
|
|
2598
|
+
];
|
|
2599
|
+
const options = this.options;
|
|
2600
|
+
const debug = options.debug;
|
|
2601
|
+
while (stack.length) {
|
|
2602
|
+
y = stack.pop();
|
|
2603
|
+
x = stack.pop();
|
|
2604
|
+
z = stack.pop();
|
|
2605
|
+
features = stack.pop();
|
|
2606
|
+
const z2 = 1 << z;
|
|
2607
|
+
const id = toID(z, x, y);
|
|
2608
|
+
let tile = this.tiles[id];
|
|
2609
|
+
if (!tile) {
|
|
2610
|
+
if (debug > 1) console.time("creation");
|
|
2611
|
+
tile = this.tiles[id] = createTile(features, z, x, y, options);
|
|
2612
|
+
this.tileCoords.push({
|
|
2613
|
+
z,
|
|
2614
|
+
x,
|
|
2615
|
+
y,
|
|
2616
|
+
id
|
|
2617
|
+
});
|
|
2618
|
+
if (debug) {
|
|
2619
|
+
if (debug > 1) {
|
|
2620
|
+
console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)", z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
|
|
2621
|
+
console.timeEnd("creation");
|
|
2622
|
+
}
|
|
2623
|
+
const key = `z${z}`;
|
|
2624
|
+
this.stats[key] = (this.stats[key] || 0) + 1;
|
|
2625
|
+
this.total++;
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2628
|
+
tile.source = features;
|
|
2629
|
+
if (cz == null) {
|
|
2630
|
+
if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue;
|
|
2631
|
+
} else if (z === options.maxZoom || z === cz) continue;
|
|
2632
|
+
else if (cz != null) {
|
|
2633
|
+
const zoomSteps = cz - z;
|
|
2634
|
+
if (x !== cx >> zoomSteps || y !== cy >> zoomSteps) continue;
|
|
2635
|
+
}
|
|
2636
|
+
tile.source = null;
|
|
2637
|
+
if (!features.length) continue;
|
|
2638
|
+
if (debug > 1) console.time("clipping");
|
|
2639
|
+
const k1 = 0.5 * options.buffer / options.extent;
|
|
2640
|
+
const k2 = 0.5 - k1;
|
|
2641
|
+
const k3 = 0.5 + k1;
|
|
2642
|
+
const k4 = 1 + k1;
|
|
2643
|
+
let tl = null;
|
|
2644
|
+
let bl = null;
|
|
2645
|
+
let tr = null;
|
|
2646
|
+
let br = null;
|
|
2647
|
+
const left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);
|
|
2648
|
+
const right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options);
|
|
2649
|
+
if (left) {
|
|
2650
|
+
tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
|
|
2651
|
+
bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
|
|
2652
|
+
}
|
|
2653
|
+
if (right) {
|
|
2654
|
+
tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
|
|
2655
|
+
br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
|
|
2656
|
+
}
|
|
2657
|
+
if (debug > 1) console.timeEnd("clipping");
|
|
2658
|
+
stack.push(tl || [], z + 1, x * 2, y * 2);
|
|
2659
|
+
stack.push(bl || [], z + 1, x * 2, y * 2 + 1);
|
|
2660
|
+
stack.push(tr || [], z + 1, x * 2 + 1, y * 2);
|
|
2661
|
+
stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
/**
|
|
2665
|
+
* Invalidates (removes) tiles affected by the provided features
|
|
2666
|
+
* @internal
|
|
2667
|
+
* @param features
|
|
2668
|
+
*/
|
|
2669
|
+
invalidateTiles(features) {
|
|
2670
|
+
if (!features.length) return;
|
|
2671
|
+
const options = this.options;
|
|
2672
|
+
const { debug } = options;
|
|
2673
|
+
let minX = Infinity;
|
|
2674
|
+
let maxX = -Infinity;
|
|
2675
|
+
let minY = Infinity;
|
|
2676
|
+
let maxY = -Infinity;
|
|
2677
|
+
for (const feature of features) {
|
|
2678
|
+
minX = Math.min(minX, feature.minX);
|
|
2679
|
+
maxX = Math.max(maxX, feature.maxX);
|
|
2680
|
+
minY = Math.min(minY, feature.minY);
|
|
2681
|
+
maxY = Math.max(maxY, feature.maxY);
|
|
2682
|
+
}
|
|
2683
|
+
const k1 = options.buffer / options.extent;
|
|
2684
|
+
const removedLookup = /* @__PURE__ */ new Set();
|
|
2685
|
+
for (const id in this.tiles) {
|
|
2686
|
+
const tile = this.tiles[id];
|
|
2687
|
+
const z2 = 1 << tile.z;
|
|
2688
|
+
const tileMinX = (tile.x - k1) / z2;
|
|
2689
|
+
const tileMaxX = (tile.x + 1 + k1) / z2;
|
|
2690
|
+
const tileMinY = (tile.y - k1) / z2;
|
|
2691
|
+
const tileMaxY = (tile.y + 1 + k1) / z2;
|
|
2692
|
+
if (maxX < tileMinX || minX >= tileMaxX || maxY < tileMinY || minY >= tileMaxY) continue;
|
|
2693
|
+
let intersects = false;
|
|
2694
|
+
for (const feature of features) if (feature.maxX >= tileMinX && feature.minX < tileMaxX && feature.maxY >= tileMinY && feature.minY < tileMaxY) {
|
|
2695
|
+
intersects = true;
|
|
2696
|
+
break;
|
|
2697
|
+
}
|
|
2698
|
+
if (!intersects) continue;
|
|
2699
|
+
if (debug) {
|
|
2700
|
+
if (debug > 1) 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);
|
|
2701
|
+
const key = `z${tile.z}`;
|
|
2702
|
+
this.stats[key] = (this.stats[key] || 0) - 1;
|
|
2703
|
+
this.total--;
|
|
2704
|
+
}
|
|
2705
|
+
delete this.tiles[id];
|
|
2706
|
+
removedLookup.add(id);
|
|
2707
|
+
}
|
|
2708
|
+
if (removedLookup.size) this.tileCoords = this.tileCoords.filter((c) => !removedLookup.has(c.id));
|
|
2709
|
+
}
|
|
2710
|
+
};
|
|
2711
|
+
function toID(z, x, y) {
|
|
2712
|
+
return ((1 << z) * y + x) * 32 + z;
|
|
2713
|
+
}
|
|
2714
|
+
var defaultOptions = {
|
|
2715
|
+
maxZoom: 14,
|
|
2716
|
+
indexMaxZoom: 5,
|
|
2717
|
+
indexMaxPoints: 1e5,
|
|
2718
|
+
tolerance: 3,
|
|
2719
|
+
extent: 4096,
|
|
2720
|
+
buffer: 64,
|
|
2721
|
+
lineMetrics: false,
|
|
2722
|
+
promoteId: null,
|
|
2723
|
+
generateId: false,
|
|
2724
|
+
updateable: false,
|
|
2725
|
+
cluster: false,
|
|
2726
|
+
clusterOptions: defaultClusterOptions,
|
|
2727
|
+
debug: 0,
|
|
2728
|
+
coordinates: "lngLat",
|
|
2729
|
+
wrap: true
|
|
2730
|
+
};
|
|
2731
|
+
var GeoJSONVT = class {
|
|
2732
|
+
constructor(data, options) {
|
|
2733
|
+
options = this.options = Object.assign({}, defaultOptions, options);
|
|
2734
|
+
this.worldCoordinateHelper = getWorldCoordinateHelper(options.coordinates);
|
|
2735
|
+
const debug = options.debug;
|
|
2736
|
+
if (debug) console.time("preprocess data");
|
|
2737
|
+
if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error("maxZoom should be in the 0-24 range");
|
|
2738
|
+
if (options.promoteId && options.generateId) throw new Error("promoteId and generateId cannot be used together.");
|
|
2739
|
+
if (options.updateable) this.unlocated = /* @__PURE__ */ new Map();
|
|
2740
|
+
let features = convertToInternal(data, options, this.unlocated);
|
|
2741
|
+
if (debug) {
|
|
2742
|
+
console.timeEnd("preprocess data");
|
|
2743
|
+
console.log("index: maxZoom: %d, maxPoints: %d", options.indexMaxZoom, options.indexMaxPoints);
|
|
2744
|
+
console.time("generate tiles");
|
|
2745
|
+
}
|
|
2746
|
+
features = wrap(features, options);
|
|
2747
|
+
if (options.updateable) this.source = features;
|
|
2748
|
+
this.initializeIndex(features, options);
|
|
2749
|
+
}
|
|
2750
|
+
initializeIndex(features, options) {
|
|
2751
|
+
this.tileIndex = options.cluster ? new ClusterTileIndex({
|
|
2752
|
+
...options.clusterOptions,
|
|
2753
|
+
coordinates: options.coordinates,
|
|
2754
|
+
wrap: options.wrap
|
|
2755
|
+
}) : new TileIndex(options);
|
|
2756
|
+
if (!features.length) return;
|
|
2757
|
+
this.tileIndex.initialize(features);
|
|
2758
|
+
}
|
|
2759
|
+
/**
|
|
2760
|
+
* Given z, x, and y tile coordinates, returns the corresponding tile with geometries in tile coordinates, much like MVT data is stored.
|
|
2761
|
+
* @param z - tile zoom level
|
|
2762
|
+
* @param x - tile x coordinate
|
|
2763
|
+
* @param y - tile y coordinate
|
|
2764
|
+
* @returns the transformed tile or null if not found
|
|
2765
|
+
*/
|
|
2766
|
+
getTile(z, x, y) {
|
|
2767
|
+
z = +z;
|
|
2768
|
+
x = +x;
|
|
2769
|
+
y = +y;
|
|
2770
|
+
if (z < 0 || z > 24) return null;
|
|
2771
|
+
return this.tileIndex.getTile(z, x, y);
|
|
2772
|
+
}
|
|
2773
|
+
/**
|
|
2774
|
+
* Updates the source data feature set using a {@link GeoJSONVTSourceDiff}
|
|
2775
|
+
* @param diff - the source diff object
|
|
2776
|
+
*/
|
|
2777
|
+
updateData(diff, filter) {
|
|
2778
|
+
const options = this.options;
|
|
2779
|
+
if (!options.updateable) throw new Error("to update tile geojson `updateable` option must be set to true");
|
|
2780
|
+
let { affected, source } = applySourceDiff(this.source, diff, options, this.unlocated);
|
|
2781
|
+
if (filter) ({ affected, source } = this.filterUpdate(source, affected, filter));
|
|
2782
|
+
if (!affected.length) return;
|
|
2783
|
+
this.source = source;
|
|
2784
|
+
this.tileIndex.updateIndex(source, affected, options);
|
|
2785
|
+
}
|
|
2786
|
+
/**
|
|
2787
|
+
* Filter an update using a predicate function, the features an update emptied included, so that one the filter
|
|
2788
|
+
* rejects can't come back with a later update. A feature without a geometry at all isn't passed to the predicate.
|
|
2789
|
+
* Returns the affected and updated source features.
|
|
2790
|
+
*/
|
|
2791
|
+
filterUpdate(source, affected, predicate) {
|
|
2792
|
+
const removeIds = /* @__PURE__ */ new Set();
|
|
2793
|
+
for (const feature of source) {
|
|
2794
|
+
if (feature.id == void 0) continue;
|
|
2795
|
+
if (predicate(featureToGeoJSON(feature, this.worldCoordinateHelper))) continue;
|
|
2796
|
+
affected.push(feature);
|
|
2797
|
+
removeIds.add(feature.id);
|
|
2798
|
+
}
|
|
2799
|
+
source = source.filter((feature) => !removeIds.has(feature.id));
|
|
2800
|
+
for (const [id, feature] of this.unlocated ?? []) if (feature.geometry && !predicate(feature)) this.unlocated.delete(id);
|
|
2801
|
+
return {
|
|
2802
|
+
affected,
|
|
2803
|
+
source
|
|
2804
|
+
};
|
|
2805
|
+
}
|
|
2806
|
+
/**
|
|
2807
|
+
* Returns source data as GeoJSON - only available when `updateable` option is set to true.
|
|
2808
|
+
*/
|
|
2809
|
+
getData() {
|
|
2810
|
+
if (!this.options.updateable) throw new Error("to retrieve data the `updateable` option must be set to true");
|
|
2811
|
+
return convertToGeoJSON(this.source, this.worldCoordinateHelper);
|
|
2812
|
+
}
|
|
2813
|
+
/**
|
|
2814
|
+
* Update supercluster options and regenerate the index.
|
|
2815
|
+
* @param cluster - whether to enable clustering
|
|
2816
|
+
* @param clusterOptions - {@link SuperclusterOptions} without `coordinates` and `wrap`, which come from the index options
|
|
2817
|
+
*/
|
|
2818
|
+
updateClusterOptions(cluster, clusterOptions) {
|
|
2819
|
+
const wasCluster = this.options.cluster;
|
|
2820
|
+
this.options.cluster = cluster;
|
|
2821
|
+
this.options.clusterOptions = clusterOptions;
|
|
2822
|
+
if (wasCluster == cluster) {
|
|
2823
|
+
this.tileIndex.updateIndex(this.source, [], this.options);
|
|
2824
|
+
return;
|
|
2825
|
+
}
|
|
2826
|
+
this.initializeIndex(this.source, this.options);
|
|
2827
|
+
}
|
|
2828
|
+
/**
|
|
2829
|
+
* Returns the zoom level at which a cluster expands into multiple children.
|
|
2830
|
+
* @param clusterId - The target cluster id.
|
|
2831
|
+
* @returns the expansion zoom or null in case of non-clustered source
|
|
2832
|
+
*/
|
|
2833
|
+
getClusterExpansionZoom(clusterId) {
|
|
2834
|
+
return this.tileIndex.getClusterExpansionZoom(clusterId);
|
|
2835
|
+
}
|
|
2836
|
+
/**
|
|
2837
|
+
* Returns the immediate children (clusters or points) of a cluster as GeoJSON.
|
|
2838
|
+
* @param clusterId - The target cluster id.
|
|
2839
|
+
* @returns the immediate children or null in case of non-clustered source
|
|
2840
|
+
*/
|
|
2841
|
+
getClusterChildren(clusterId) {
|
|
2842
|
+
return this.tileIndex.getChildren(clusterId);
|
|
2843
|
+
}
|
|
2844
|
+
/**
|
|
2845
|
+
* Returns leaf point features under a cluster, paginated by `limit` and `offset`.
|
|
2846
|
+
* @param clusterId - The target cluster id.
|
|
2847
|
+
* @param limit - Maximum number of points to return (defaults to `10`).
|
|
2848
|
+
* @param offset - Number of points to skip before collecting results (defaults to `0`).
|
|
2849
|
+
* @returns leaf point features under a cluster or null in case of non-clustered source
|
|
2850
|
+
*/
|
|
2851
|
+
getClusterLeaves(clusterId, limit, offset) {
|
|
2852
|
+
return this.tileIndex.getLeaves(clusterId, limit, offset);
|
|
2853
|
+
}
|
|
2854
|
+
};
|
|
2855
|
+
|
|
2856
|
+
// src/geojson-tiler.ts
|
|
2857
|
+
var GEOMETRY_DEPTHS = {
|
|
2858
|
+
Point: 0,
|
|
2859
|
+
MultiPoint: 1,
|
|
2860
|
+
LineString: 1,
|
|
2861
|
+
MultiLineString: 2,
|
|
2862
|
+
Polygon: 2,
|
|
2863
|
+
MultiPolygon: 3
|
|
2864
|
+
};
|
|
2865
|
+
function createTileIndex(data, options, clipToMercatorRange = false) {
|
|
2866
|
+
const clipped = clipToMercatorRange ? clipFeaturesToMercatorRange(data, options) : { data, outside: 0 };
|
|
2867
|
+
const indexOptions = clipped.data !== data && options.generateId ? { ...options, generateId: false } : options;
|
|
2868
|
+
return { index: new GeoJSONVT(clipped.data, indexOptions), outside: clipped.outside };
|
|
2869
|
+
}
|
|
2870
|
+
var MERCATOR_LATITUDE = Math.atan(Math.sinh(Math.PI)) * 180 / Math.PI;
|
|
2871
|
+
function getMercatorY(latitude) {
|
|
2872
|
+
const sin = Math.sin(Math.max(-89.9999, Math.min(89.9999, latitude)) * Math.PI / 180);
|
|
2873
|
+
return 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
|
|
2874
|
+
}
|
|
2875
|
+
var EDGE_TOLERANCE = 1e-12;
|
|
2876
|
+
var isInsideY = (y) => y >= -EDGE_TOLERANCE && y <= 1 + EDGE_TOLERANCE;
|
|
2877
|
+
function isInside(position) {
|
|
2878
|
+
return Math.abs(position[1]) <= MERCATOR_LATITUDE;
|
|
2879
|
+
}
|
|
2880
|
+
function interpolate(a, b, t, edge) {
|
|
2881
|
+
return [a[0] + t * (b[0] - a[0]), edge === 0 ? MERCATOR_LATITUDE : -MERCATOR_LATITUDE];
|
|
2882
|
+
}
|
|
2883
|
+
function clipLine2(line) {
|
|
2884
|
+
const points = [];
|
|
2885
|
+
for (let i = 0; i < line.length; i++) {
|
|
2886
|
+
if (i > 0) {
|
|
2887
|
+
const a = line[i - 1];
|
|
2888
|
+
const ya = getMercatorY(a[1]);
|
|
2889
|
+
const dy = getMercatorY(line[i][1]) - ya;
|
|
2890
|
+
const crossings = [0, 1].map((edge) => ({ edge, t: (edge - ya) / dy })).filter(({ t }) => t > 0 && t < 1).sort((p, q) => p.t - q.t);
|
|
2891
|
+
for (const { edge, t } of crossings) points.push(interpolate(a, line[i], t, edge));
|
|
2892
|
+
}
|
|
2893
|
+
points.push(line[i]);
|
|
2894
|
+
}
|
|
2895
|
+
const ys = points.map((point) => getMercatorY(point[1]));
|
|
2896
|
+
const distances = [0];
|
|
2897
|
+
for (let i = 1; i < points.length; i++) {
|
|
2898
|
+
const dx = (points[i][0] - points[i - 1][0]) / 360;
|
|
2899
|
+
const dy = Math.min(1, Math.max(0, ys[i])) - Math.min(1, Math.max(0, ys[i - 1]));
|
|
2900
|
+
distances.push(distances[i - 1] + Math.hypot(dx, dy));
|
|
2901
|
+
}
|
|
2902
|
+
const length = distances[distances.length - 1] || 1;
|
|
2903
|
+
const parts = [];
|
|
2904
|
+
let first = -1;
|
|
2905
|
+
for (let i = 0; i < points.length; i++) {
|
|
2906
|
+
const middle = i < points.length - 1 ? (ys[i] + ys[i + 1]) / 2 : NaN;
|
|
2907
|
+
const inside = isInsideY(middle);
|
|
2908
|
+
if (inside && first < 0) {
|
|
2909
|
+
first = i;
|
|
2910
|
+
} else if (!inside && first >= 0) {
|
|
2911
|
+
parts.push({ line: points.slice(first, i + 1), start: distances[first] / length, end: distances[i] / length });
|
|
2912
|
+
first = -1;
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
return parts;
|
|
2916
|
+
}
|
|
2917
|
+
function clipRing(ring) {
|
|
2918
|
+
let points = ring;
|
|
2919
|
+
for (const edge of [0, 1]) {
|
|
2920
|
+
const inside = (y) => edge === 0 ? y >= -EDGE_TOLERANCE : y <= 1 + EDGE_TOLERANCE;
|
|
2921
|
+
const clipped = [];
|
|
2922
|
+
for (let i = 0; i < points.length; i++) {
|
|
2923
|
+
const a = points[i];
|
|
2924
|
+
const b = points[(i + 1) % points.length];
|
|
2925
|
+
const ya = getMercatorY(a[1]);
|
|
2926
|
+
const yb = getMercatorY(b[1]);
|
|
2927
|
+
if (inside(ya)) clipped.push(a);
|
|
2928
|
+
if (inside(ya) !== inside(yb)) {
|
|
2929
|
+
clipped.push(interpolate(a, b, (edge - ya) / (yb - ya), edge));
|
|
2930
|
+
}
|
|
2931
|
+
}
|
|
2932
|
+
points = clipped;
|
|
2933
|
+
}
|
|
2934
|
+
const [first] = points;
|
|
2935
|
+
const last = points[points.length - 1];
|
|
2936
|
+
if (first && (first[0] !== last[0] || first[1] !== last[1])) {
|
|
2937
|
+
points.push(first);
|
|
2938
|
+
}
|
|
2939
|
+
return points.length >= 4 ? points : null;
|
|
2940
|
+
}
|
|
2941
|
+
function clipPolygon(rings) {
|
|
2942
|
+
const [outer, ...holes] = rings.map((ring) => ring.every(isInside) ? ring : clipRing(ring));
|
|
2943
|
+
return outer ? [outer, ...holes.filter((hole) => hole !== null)] : null;
|
|
2944
|
+
}
|
|
2945
|
+
function isGeometryInside(geometry) {
|
|
2946
|
+
if (geometry.type === "GeometryCollection") {
|
|
2947
|
+
return (geometry.geometries || []).every(isGeometryInside);
|
|
2948
|
+
}
|
|
2949
|
+
const visit = (value) => !Array.isArray(value) || (typeof value[0] === "number" ? isInside(value) : value.every(visit));
|
|
2950
|
+
return visit(geometry.coordinates);
|
|
2951
|
+
}
|
|
2952
|
+
var getLines = (parts) => parts.map((part) => part.line);
|
|
2953
|
+
var LINE_PART_START = "tangram_line_part_start";
|
|
2954
|
+
var LINE_PART_END = "tangram_line_part_end";
|
|
2955
|
+
var LINE_CLIP_START = "geojsonvt_clip_start";
|
|
2956
|
+
var LINE_CLIP_END = "geojsonvt_clip_end";
|
|
2957
|
+
function clipGeometry(geometry) {
|
|
2958
|
+
const { type, coordinates } = geometry;
|
|
2959
|
+
const multi = (multiType, parts, singleType) => parts.length === 0 ? null : parts.length === 1 ? { type: singleType, coordinates: parts[0] } : { type: multiType, coordinates: parts };
|
|
2960
|
+
switch (type) {
|
|
2961
|
+
case "Point":
|
|
2962
|
+
return isInside(coordinates) ? geometry : null;
|
|
2963
|
+
case "MultiPoint":
|
|
2964
|
+
return multi("MultiPoint", coordinates.filter(isInside), "Point");
|
|
2965
|
+
case "LineString":
|
|
2966
|
+
return multi("MultiLineString", getLines(clipLine2(coordinates)), "LineString");
|
|
2967
|
+
case "MultiLineString":
|
|
2968
|
+
return multi("MultiLineString", getLines(coordinates.flatMap(clipLine2)), "LineString");
|
|
2969
|
+
case "Polygon":
|
|
2970
|
+
return multi("MultiPolygon", [clipPolygon(coordinates)].filter(Boolean), "Polygon");
|
|
2971
|
+
case "MultiPolygon":
|
|
2972
|
+
return multi("MultiPolygon", coordinates.map(clipPolygon).filter(Boolean), "Polygon");
|
|
2973
|
+
case "GeometryCollection": {
|
|
2974
|
+
const geometries = (geometry.geometries || []).map((child) => isGeometryInside(child) ? child : clipGeometry(child)).filter((child) => child !== null);
|
|
2975
|
+
return geometries.length ? { type, geometries } : null;
|
|
2976
|
+
}
|
|
2977
|
+
default:
|
|
2978
|
+
return geometry;
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
function clipFeaturesToMercatorRange(data, { generateId = false, lineMetrics = false } = {}) {
|
|
2982
|
+
let outside = 0;
|
|
2983
|
+
const clipFeature = (feature) => {
|
|
2984
|
+
const geometry = feature?.geometry;
|
|
2985
|
+
if (!geometry || isGeometryInside(geometry)) {
|
|
2986
|
+
return [feature];
|
|
2987
|
+
}
|
|
2988
|
+
outside++;
|
|
2989
|
+
const isLine = geometry.type === "LineString" || geometry.type === "MultiLineString";
|
|
2990
|
+
if (lineMetrics && isLine) {
|
|
2991
|
+
const lines = geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates;
|
|
2992
|
+
return lines.flatMap(clipLine2).map(({ line, start, end }) => ({
|
|
2993
|
+
...feature,
|
|
2994
|
+
geometry: { type: "LineString", coordinates: line },
|
|
2995
|
+
properties: { ...feature.properties, [LINE_PART_START]: start, [LINE_PART_END]: end }
|
|
2996
|
+
}));
|
|
2997
|
+
}
|
|
2998
|
+
const clipped = clipGeometry(geometry);
|
|
2999
|
+
return clipped ? [{ ...feature, geometry: clipped }] : [];
|
|
3000
|
+
};
|
|
3001
|
+
const withIds = (features, index) => generateId ? features.map((feature) => feature && { ...feature, id: index }) : features;
|
|
3002
|
+
const value = data;
|
|
3003
|
+
if (value?.type === "FeatureCollection" && Array.isArray(value.features)) {
|
|
3004
|
+
const features = value.features.map(clipFeature);
|
|
3005
|
+
return outside ? { data: { ...value, features: features.flatMap(withIds) }, outside } : { data, outside };
|
|
3006
|
+
}
|
|
3007
|
+
if (value?.type === "Feature") {
|
|
3008
|
+
const features = clipFeature(value);
|
|
3009
|
+
return outside ? { data: { type: "FeatureCollection", features: withIds(features, 0) }, outside } : { data, outside };
|
|
3010
|
+
}
|
|
3011
|
+
if (value && typeof value === "object" && "type" in value) {
|
|
3012
|
+
const geometry = value;
|
|
3013
|
+
if (isGeometryInside(geometry)) {
|
|
3014
|
+
return { data, outside };
|
|
3015
|
+
}
|
|
3016
|
+
const features = clipFeature({ type: "Feature", properties: {}, geometry });
|
|
3017
|
+
return { data: { type: "FeatureCollection", features: withIds(features, 0) }, outside };
|
|
3018
|
+
}
|
|
3019
|
+
return { data, outside };
|
|
3020
|
+
}
|
|
3021
|
+
function getSignedArea(ring) {
|
|
3022
|
+
let sum = 0;
|
|
3023
|
+
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
|
|
3024
|
+
sum += (ring[j][0] - ring[i][0]) * (ring[i][1] + ring[j][1]);
|
|
3025
|
+
}
|
|
3026
|
+
return sum;
|
|
3027
|
+
}
|
|
3028
|
+
function classifyRings(rings) {
|
|
3029
|
+
const polygons = [];
|
|
3030
|
+
let polygon;
|
|
3031
|
+
let clockwise;
|
|
3032
|
+
for (const ring of rings) {
|
|
3033
|
+
const area = getSignedArea(ring);
|
|
3034
|
+
if (area === 0) {
|
|
3035
|
+
continue;
|
|
3036
|
+
}
|
|
3037
|
+
clockwise ??= area < 0;
|
|
3038
|
+
if (clockwise === area < 0) {
|
|
3039
|
+
polygon = [ring];
|
|
3040
|
+
polygons.push(polygon);
|
|
3041
|
+
} else {
|
|
3042
|
+
polygon?.push(ring);
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
return polygons;
|
|
3046
|
+
}
|
|
3047
|
+
function getGeometry(feature) {
|
|
3048
|
+
if (feature.type === 1) {
|
|
3049
|
+
const points = feature.geometry;
|
|
3050
|
+
return points.length === 1 ? { type: "Point", coordinates: points[0] } : { type: "MultiPoint", coordinates: points };
|
|
3051
|
+
}
|
|
3052
|
+
if (feature.type === 2) {
|
|
3053
|
+
const lines = feature.geometry;
|
|
3054
|
+
return lines.length === 1 ? { type: "LineString", coordinates: lines[0] } : { type: "MultiLineString", coordinates: lines };
|
|
3055
|
+
}
|
|
3056
|
+
const polygons = classifyRings(feature.geometry);
|
|
3057
|
+
if (polygons.length === 0) {
|
|
3058
|
+
return null;
|
|
3059
|
+
}
|
|
3060
|
+
return polygons.length === 1 ? { type: "Polygon", coordinates: polygons[0] } : { type: "MultiPolygon", coordinates: polygons };
|
|
3061
|
+
}
|
|
3062
|
+
function getProperties(tags) {
|
|
3063
|
+
if (!tags || !(LINE_PART_START in tags)) {
|
|
3064
|
+
return tags || {};
|
|
3065
|
+
}
|
|
3066
|
+
const { [LINE_PART_START]: start, [LINE_PART_END]: end, ...properties } = tags;
|
|
3067
|
+
if (LINE_CLIP_START in properties) {
|
|
3068
|
+
properties[LINE_CLIP_START] = start + properties[LINE_CLIP_START] * (end - start);
|
|
3069
|
+
properties[LINE_CLIP_END] = start + properties[LINE_CLIP_END] * (end - start);
|
|
3070
|
+
}
|
|
3071
|
+
return properties;
|
|
3072
|
+
}
|
|
3073
|
+
function cutTile(index, z, x, y) {
|
|
3074
|
+
const features = [];
|
|
3075
|
+
const positions = [];
|
|
3076
|
+
const lengths = [];
|
|
3077
|
+
const writeCoordinates = (coordinates, depth) => {
|
|
3078
|
+
if (depth === 0) {
|
|
3079
|
+
positions.push(coordinates[0], coordinates[1]);
|
|
3080
|
+
return;
|
|
3081
|
+
}
|
|
3082
|
+
lengths.push(coordinates.length);
|
|
3083
|
+
for (const child of coordinates) {
|
|
3084
|
+
writeCoordinates(child, depth - 1);
|
|
3085
|
+
}
|
|
3086
|
+
};
|
|
3087
|
+
for (const feature of index.getTile(z, x, y)?.features || []) {
|
|
3088
|
+
const geometry = getGeometry(feature);
|
|
3089
|
+
if (!geometry) {
|
|
3090
|
+
continue;
|
|
3091
|
+
}
|
|
3092
|
+
writeCoordinates(geometry.coordinates, GEOMETRY_DEPTHS[geometry.type]);
|
|
3093
|
+
const encoded = { type: geometry.type, properties: getProperties(feature.tags) };
|
|
3094
|
+
if (feature.id !== void 0) {
|
|
3095
|
+
encoded.id = feature.id;
|
|
3096
|
+
}
|
|
3097
|
+
features.push(encoded);
|
|
3098
|
+
}
|
|
3099
|
+
return { features, positions: Int32Array.from(positions), lengths: Uint32Array.from(lengths) };
|
|
3100
|
+
}
|
|
3101
|
+
|
|
3102
|
+
// src/geojson-resource.ts
|
|
3103
|
+
function createGeoJsonResourceState() {
|
|
3104
|
+
return { pendingFeatures: /* @__PURE__ */ new Map(), indexes: /* @__PURE__ */ new Map() };
|
|
3105
|
+
}
|
|
3106
|
+
function runGeoJsonResource(state, message) {
|
|
3107
|
+
switch (message.type) {
|
|
3108
|
+
case "features": {
|
|
3109
|
+
const features = state.pendingFeatures.get(message.source);
|
|
3110
|
+
if (features) for (const feature of message.features) features.push(feature);
|
|
3111
|
+
else state.pendingFeatures.set(message.source, message.features);
|
|
3112
|
+
return null;
|
|
3113
|
+
}
|
|
3114
|
+
case "index": {
|
|
3115
|
+
const data = message.data ?? { type: "FeatureCollection", features: state.pendingFeatures.get(message.source) || [] };
|
|
3116
|
+
state.pendingFeatures.delete(message.source);
|
|
3117
|
+
try {
|
|
3118
|
+
const { index, outside } = createTileIndex(data, message.options, message.clipToMercatorRange);
|
|
3119
|
+
state.indexes.set(message.source, index);
|
|
3120
|
+
return outside;
|
|
3121
|
+
} catch (error) {
|
|
3122
|
+
state.indexes.set(message.source, error instanceof Error ? error : new Error(String(error)));
|
|
3123
|
+
return 0;
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
case "tile": {
|
|
3127
|
+
const index = state.indexes.get(message.source);
|
|
3128
|
+
if (!index) throw new Error("GeoJSON source has no index");
|
|
3129
|
+
if (index instanceof Error) throw index;
|
|
3130
|
+
return cutTile(index, message.z, message.x, message.y);
|
|
3131
|
+
}
|
|
3132
|
+
case "remove":
|
|
3133
|
+
state.pendingFeatures.delete(message.source);
|
|
3134
|
+
state.indexes.delete(message.source);
|
|
3135
|
+
return null;
|
|
3136
|
+
}
|
|
3137
|
+
}
|
|
3138
|
+
|
|
3139
|
+
// src/geojson-task.ts
|
|
3140
|
+
var import_meta2 = {};
|
|
3141
|
+
var GeoJsonTask = {
|
|
3142
|
+
id: "tangram-geojson",
|
|
3143
|
+
worker: {
|
|
3144
|
+
create: () => new Worker(new URL("./geojson-task-worker.js", import_meta2.url), { type: "module" }),
|
|
3145
|
+
capabilities: { atomic: true, streaming: false }
|
|
3146
|
+
},
|
|
3147
|
+
initialize: (_input) => createGeoJsonResourceState(),
|
|
3148
|
+
process: (input, _options, { state }) => {
|
|
3149
|
+
try {
|
|
3150
|
+
const output = runGeoJsonResource(state, input);
|
|
3151
|
+
return typeof output === "number" ? { tile: null, outside: output } : { tile: output };
|
|
3152
|
+
} catch (error) {
|
|
3153
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
};
|
|
3157
|
+
|
|
3158
|
+
// src/geojson-task-handler.ts
|
|
3159
|
+
function installGeoJsonTaskHandler() {
|
|
3160
|
+
return initializeTaskWorker(GeoJsonTask);
|
|
3161
|
+
}
|
|
3162
|
+
|
|
3163
|
+
// src/geojson-task-worker.ts
|
|
3164
|
+
void installGeoJsonTaskHandler();
|
|
3165
|
+
})();
|
|
3166
|
+
//# sourceMappingURL=geojson-task-worker.js.map
|