@metagl/smartearth-base 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +78 -0
- package/README.md +320 -3
- package/dist/chunk-24R3PPPA.js +2116 -0
- package/dist/chunk-POH7K3F4.js +705 -0
- package/dist/chunk-UENQT22J.js +885 -0
- package/dist/createEarth-BY0dtgQQ.d.ts +647 -0
- package/dist/errors-cB7IQlHy.d.ts +15 -0
- package/dist/index.d.ts +345 -0
- package/dist/index.js +2 -0
- package/dist/presets.d.ts +312 -0
- package/dist/presets.js +2 -0
- package/dist/vite.d.ts +20 -0
- package/dist/vite.js +89 -0
- package/dist/vue.d.ts +108 -0
- package/dist/vue.js +291 -0
- package/package.json +75 -6
|
@@ -0,0 +1,2116 @@
|
|
|
1
|
+
import { SmartEarthError, Emitter, readSdkRenderVersion, createEarthEnvironment, describeCause, MAP_TOKEN_APPLY_URL, describeLayerCause, syncEnabledFlags, requirePresetDocument, ALL_EFFECTS } from './chunk-UENQT22J.js';
|
|
2
|
+
import * as CesiumNS from 'cesium';
|
|
3
|
+
import * as SdkRender from '@metagl/sdk-render';
|
|
4
|
+
|
|
5
|
+
// src/quality/profiles.ts
|
|
6
|
+
var LOW_QUALITY_OVERRIDES = {
|
|
7
|
+
ssgi: { enabled: false },
|
|
8
|
+
ssrt: { enabled: false },
|
|
9
|
+
ssr: { enabled: false },
|
|
10
|
+
volumetricClouds: { nubis: { maxSteps: 56, noiseEnabled: false } },
|
|
11
|
+
heightFog: { quality: "low" },
|
|
12
|
+
postProcessing: { msaaEnabled: false, hdrEnabled: false, fxaaEnabled: true },
|
|
13
|
+
shadow: { size: 2048, numBlurSamples: 8, softShadows: false }
|
|
14
|
+
};
|
|
15
|
+
function isPlainObject(value) {
|
|
16
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
function deepMerge(base, patch) {
|
|
19
|
+
const out = { ...base };
|
|
20
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
21
|
+
const current = out[key];
|
|
22
|
+
out[key] = isPlainObject(current) && isPlainObject(value) ? deepMerge(current, value) : value;
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
function withoutClock(config) {
|
|
27
|
+
const { clockIsoTime: _top, ...rest } = config;
|
|
28
|
+
const settings = rest.settings;
|
|
29
|
+
if (!isPlainObject(settings)) return rest;
|
|
30
|
+
const { clockIsoTime: _nested, ...restSettings } = settings;
|
|
31
|
+
return { ...rest, settings: restSettings };
|
|
32
|
+
}
|
|
33
|
+
function buildHighConfig(baseline) {
|
|
34
|
+
if (!isPlainObject(baseline)) throw new Error("baseline \u7F3A\u5931");
|
|
35
|
+
return withoutClock(structuredClone(baseline));
|
|
36
|
+
}
|
|
37
|
+
function buildLowConfig(baseline) {
|
|
38
|
+
const high = buildHighConfig(baseline);
|
|
39
|
+
const systems = isPlainObject(high.systems) ? high.systems : {};
|
|
40
|
+
return { ...high, systems: deepMerge(systems, LOW_QUALITY_OVERRIDES) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/layers/shared.ts
|
|
44
|
+
function isRecord(value) {
|
|
45
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
46
|
+
}
|
|
47
|
+
function cssColor(Cesium, css, fallback) {
|
|
48
|
+
if (!css) return fallback;
|
|
49
|
+
return Cesium.Color.fromCssColorString(css) ?? fallback;
|
|
50
|
+
}
|
|
51
|
+
function fieldColorResolver(Cesium, colorBy, fallback) {
|
|
52
|
+
if (!colorBy) return () => fallback;
|
|
53
|
+
const palette = new Map(
|
|
54
|
+
Object.entries(colorBy.colors).map(([value, css]) => [value, cssColor(Cesium, css, fallback)])
|
|
55
|
+
);
|
|
56
|
+
return (properties) => palette.get(String(properties[colorBy.field])) ?? fallback;
|
|
57
|
+
}
|
|
58
|
+
async function loadJson(source, layerId) {
|
|
59
|
+
if (typeof source !== "string") return source;
|
|
60
|
+
try {
|
|
61
|
+
const response = await fetch(source);
|
|
62
|
+
if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
|
|
63
|
+
return await response.json();
|
|
64
|
+
} catch (error) {
|
|
65
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u56FE\u5C42 ${layerId} \u6570\u636E\u8BFB\u53D6\u5931\u8D25\uFF1A${describeLayerCause(error)}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function requireLayerSpec(condition, layerId, message) {
|
|
69
|
+
if (!condition) throw new SmartEarthError("INVALID_OPTIONS", `\u56FE\u5C42 ${layerId}\uFF1A${message}`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/layers/popup.ts
|
|
73
|
+
var DEFAULT_OFFSET = { x: 0, y: -14 };
|
|
74
|
+
var BASE_STYLE = {
|
|
75
|
+
position: "absolute",
|
|
76
|
+
left: "0",
|
|
77
|
+
top: "0",
|
|
78
|
+
zIndex: "10",
|
|
79
|
+
maxWidth: "320px",
|
|
80
|
+
padding: "10px 12px",
|
|
81
|
+
borderRadius: "8px",
|
|
82
|
+
background: "rgba(255,255,255,0.96)",
|
|
83
|
+
color: "#111827",
|
|
84
|
+
font: "13px/1.5 system-ui, sans-serif",
|
|
85
|
+
boxShadow: "0 6px 24px rgba(0,0,0,0.25)",
|
|
86
|
+
pointerEvents: "auto",
|
|
87
|
+
display: "none"
|
|
88
|
+
};
|
|
89
|
+
var HTML_ESCAPES = {
|
|
90
|
+
"&": "&",
|
|
91
|
+
"<": "<",
|
|
92
|
+
">": ">",
|
|
93
|
+
'"': """,
|
|
94
|
+
"'": "'"
|
|
95
|
+
};
|
|
96
|
+
function escapeHtml(value) {
|
|
97
|
+
return String(value ?? "").replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char);
|
|
98
|
+
}
|
|
99
|
+
function setContent(element, content) {
|
|
100
|
+
if (typeof content === "string") {
|
|
101
|
+
element.innerHTML = content;
|
|
102
|
+
} else {
|
|
103
|
+
element.replaceChildren(content);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
var popupLayerFactory = (context, spec) => {
|
|
107
|
+
requireLayerSpec(typeof spec.render === "function", spec.id, "render \u5FC5\u987B\u662F\u51FD\u6570\u3002");
|
|
108
|
+
const { Cesium, viewer } = context;
|
|
109
|
+
const offset = spec.offset ?? DEFAULT_OFFSET;
|
|
110
|
+
const element = document.createElement("div");
|
|
111
|
+
Object.assign(element.style, BASE_STYLE);
|
|
112
|
+
element.className = ["smartearth-popup", spec.className].filter(Boolean).join(" ");
|
|
113
|
+
element.setAttribute("role", "dialog");
|
|
114
|
+
viewer.container.appendChild(element);
|
|
115
|
+
let anchor;
|
|
116
|
+
let visible = true;
|
|
117
|
+
const scratch = new Cesium.Cartesian2();
|
|
118
|
+
const place = () => {
|
|
119
|
+
if (!anchor || !visible) return;
|
|
120
|
+
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(viewer.scene, anchor, scratch);
|
|
121
|
+
if (!screen) {
|
|
122
|
+
element.style.display = "none";
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
element.style.display = "block";
|
|
126
|
+
const x = screen.x + offset.x - element.offsetWidth / 2;
|
|
127
|
+
const y = screen.y + offset.y - element.offsetHeight;
|
|
128
|
+
element.style.transform = `translate(${Math.round(x)}px, ${Math.round(y)}px)`;
|
|
129
|
+
};
|
|
130
|
+
const removePostRender = viewer.scene.postRender.addEventListener(place);
|
|
131
|
+
const show = (position, content) => {
|
|
132
|
+
setContent(element, content);
|
|
133
|
+
anchor = position;
|
|
134
|
+
place();
|
|
135
|
+
viewer.scene.requestRender();
|
|
136
|
+
};
|
|
137
|
+
const close = () => {
|
|
138
|
+
anchor = void 0;
|
|
139
|
+
element.style.display = "none";
|
|
140
|
+
};
|
|
141
|
+
const accepts = (feature) => !spec.layers || spec.layers.includes(feature.layerId);
|
|
142
|
+
const onClick = (event) => {
|
|
143
|
+
if (event.feature && accepts(event.feature) && event.worldPosition) {
|
|
144
|
+
const content = spec.render(event.feature, event.position);
|
|
145
|
+
if (content !== null) {
|
|
146
|
+
show(event.worldPosition, content);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (spec.closeOnEmptyClick ?? true) close();
|
|
151
|
+
};
|
|
152
|
+
const unsubscribe = context.onClick(onClick);
|
|
153
|
+
const api = {
|
|
154
|
+
get isOpen() {
|
|
155
|
+
return anchor !== void 0;
|
|
156
|
+
},
|
|
157
|
+
open(position, content) {
|
|
158
|
+
if (typeof position?.lon !== "number" || typeof position.lat !== "number") {
|
|
159
|
+
throw new SmartEarthError("INVALID_OPTIONS", "popup.open \u9700\u8981 { lon, lat, height? }\u3002");
|
|
160
|
+
}
|
|
161
|
+
show(Cesium.Cartesian3.fromDegrees(position.lon, position.lat, position.height ?? 0), content);
|
|
162
|
+
},
|
|
163
|
+
close
|
|
164
|
+
};
|
|
165
|
+
return {
|
|
166
|
+
api,
|
|
167
|
+
setVisible(next) {
|
|
168
|
+
visible = next;
|
|
169
|
+
if (!next) element.style.display = "none";
|
|
170
|
+
else place();
|
|
171
|
+
},
|
|
172
|
+
destroy() {
|
|
173
|
+
unsubscribe();
|
|
174
|
+
removePostRender();
|
|
175
|
+
element.remove();
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
var CESIUM_MIN_VERSION = "1.132.0";
|
|
180
|
+
var CESIUM_MAX_VERSION_EXCLUSIVE = "1.137.0";
|
|
181
|
+
function cesiumGlobals() {
|
|
182
|
+
return window;
|
|
183
|
+
}
|
|
184
|
+
function makeExtensible(obj) {
|
|
185
|
+
const out = Object.create(Object.getPrototypeOf(obj));
|
|
186
|
+
for (const key of Object.getOwnPropertyNames(obj)) {
|
|
187
|
+
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
|
|
188
|
+
if (!descriptor) continue;
|
|
189
|
+
Object.defineProperty(out, key, {
|
|
190
|
+
value: "value" in descriptor ? descriptor.value : obj[key],
|
|
191
|
+
enumerable: descriptor.enumerable ?? true,
|
|
192
|
+
configurable: true,
|
|
193
|
+
writable: true
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
function parseVersion(version) {
|
|
199
|
+
return version.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
|
200
|
+
}
|
|
201
|
+
function compareVersions(a, b) {
|
|
202
|
+
const left = parseVersion(a);
|
|
203
|
+
const right = parseVersion(b);
|
|
204
|
+
for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
|
|
205
|
+
const diff = (left[i] ?? 0) - (right[i] ?? 0);
|
|
206
|
+
if (diff !== 0) return diff;
|
|
207
|
+
}
|
|
208
|
+
return 0;
|
|
209
|
+
}
|
|
210
|
+
function assertCesiumVersion(version) {
|
|
211
|
+
const ok = typeof version === "string" && compareVersions(version, CESIUM_MIN_VERSION) >= 0 && compareVersions(version, CESIUM_MAX_VERSION_EXCLUSIVE) < 0;
|
|
212
|
+
if (!ok) {
|
|
213
|
+
throw new SmartEarthError(
|
|
214
|
+
"CESIUM_VERSION",
|
|
215
|
+
`Cesium \u7248\u672C\u4E0D\u53D7\u652F\u6301\uFF08\u5F53\u524D ${String(version)}\uFF09\uFF0C\u9700\u8981 >=${CESIUM_MIN_VERSION} \u4E14 <${CESIUM_MAX_VERSION_EXCLUSIVE}\u3002`
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
function installGlobalCesium() {
|
|
220
|
+
const globals = cesiumGlobals();
|
|
221
|
+
const existing = globals.Cesium;
|
|
222
|
+
const runtime = existing ?? makeExtensible(
|
|
223
|
+
CesiumNS.default ?? CesiumNS
|
|
224
|
+
);
|
|
225
|
+
assertCesiumVersion(runtime.VERSION);
|
|
226
|
+
if (!existing) globals.Cesium = runtime;
|
|
227
|
+
return runtime;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// src/pbr/index.ts
|
|
231
|
+
var MATERIAL_SYSTEM = "material";
|
|
232
|
+
function supportsPbr(render) {
|
|
233
|
+
const candidate = render;
|
|
234
|
+
return typeof candidate?.setTilesetMaterial === "function" && typeof candidate.getTilesetMaterial === "function" && typeof candidate.clearTilesetMaterial === "function" && typeof candidate.updateSystemConfig === "function" && typeof candidate.getSystemConfig === "function";
|
|
235
|
+
}
|
|
236
|
+
function isRecord2(value) {
|
|
237
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
238
|
+
}
|
|
239
|
+
function call(action, run) {
|
|
240
|
+
try {
|
|
241
|
+
return run();
|
|
242
|
+
} catch (error) {
|
|
243
|
+
throw new SmartEarthError("RENDER_INIT_FAILED", `PBR ${action}\u5931\u8D25\uFF1A${describeCause(error)}`, error);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function readConfig(render) {
|
|
247
|
+
const config = render.getSystemConfig(MATERIAL_SYSTEM);
|
|
248
|
+
return isRecord2(config) ? structuredClone(config) : {};
|
|
249
|
+
}
|
|
250
|
+
function createEarthPbr(render) {
|
|
251
|
+
if (!supportsPbr(render)) return void 0;
|
|
252
|
+
const requireParams = (params) => {
|
|
253
|
+
if (!isRecord2(params)) throw new SmartEarthError("INVALID_OPTIONS", "PBR \u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
|
|
254
|
+
};
|
|
255
|
+
const requireTarget = (target) => {
|
|
256
|
+
const ok = typeof target === "string" && target.length > 0 || typeof target === "object" && target !== null;
|
|
257
|
+
if (!ok) throw new SmartEarthError("INVALID_OPTIONS", "PBR \u76EE\u6807\u5FC5\u987B\u662F tileset \u5B9E\u4F8B\u6216\u975E\u7A7A URL\u3002");
|
|
258
|
+
};
|
|
259
|
+
const initialGlobal = { ...readConfig(render).pbr ?? {} };
|
|
260
|
+
return {
|
|
261
|
+
setTilesetMaterial(target, params) {
|
|
262
|
+
requireTarget(target);
|
|
263
|
+
requireParams(params);
|
|
264
|
+
return call("\u8BBE\u7F6E tileset \u6750\u8D28", () => render.setTilesetMaterial(target, { ...params }));
|
|
265
|
+
},
|
|
266
|
+
getTilesetMaterial(target) {
|
|
267
|
+
requireTarget(target);
|
|
268
|
+
return call("\u8BFB\u53D6 tileset \u6750\u8D28", () => render.getTilesetMaterial(target));
|
|
269
|
+
},
|
|
270
|
+
clearTilesetMaterial(target) {
|
|
271
|
+
requireTarget(target);
|
|
272
|
+
call("\u6E05\u9664 tileset \u6750\u8D28", () => render.clearTilesetMaterial(target));
|
|
273
|
+
},
|
|
274
|
+
getGlobal() {
|
|
275
|
+
return { ...readConfig(render).pbr ?? {} };
|
|
276
|
+
},
|
|
277
|
+
setGlobal(params) {
|
|
278
|
+
requireParams(params);
|
|
279
|
+
call("\u8BBE\u7F6E\u5168\u5C40\u53C2\u6570", () => render.updateSystemConfig(MATERIAL_SYSTEM, { pbr: { ...params } }));
|
|
280
|
+
},
|
|
281
|
+
exportConfig() {
|
|
282
|
+
return call("\u5BFC\u51FA\u914D\u7F6E", () => readConfig(render));
|
|
283
|
+
},
|
|
284
|
+
importConfig(config) {
|
|
285
|
+
requireParams(config);
|
|
286
|
+
call("\u5BFC\u5165\u914D\u7F6E", () => render.updateSystemConfig(MATERIAL_SYSTEM, structuredClone(config)));
|
|
287
|
+
},
|
|
288
|
+
setAutoManageTilesets(on) {
|
|
289
|
+
if (typeof on !== "boolean") throw new SmartEarthError("INVALID_OPTIONS", "\u81EA\u52A8\u7EB3\u7BA1\u5F00\u5173\u5FC5\u987B\u662F true / false\u3002");
|
|
290
|
+
call("\u8BBE\u7F6E\u81EA\u52A8\u7EB3\u7BA1", () => render.updateSystemConfig(MATERIAL_SYSTEM, { autoManageTilesets: on }));
|
|
291
|
+
},
|
|
292
|
+
getAutoManageTilesets() {
|
|
293
|
+
return readConfig(render).autoManageTilesets !== false;
|
|
294
|
+
},
|
|
295
|
+
resetGlobal() {
|
|
296
|
+
call("\u6062\u590D\u9ED8\u8BA4\u6750\u8D28", () => render.updateSystemConfig(MATERIAL_SYSTEM, { pbr: { ...initialGlobal } }));
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// src/quality/applyQuality.ts
|
|
302
|
+
var ALL_QUALITIES = Object.freeze(["high", "medium", "low"]);
|
|
303
|
+
var LEGACY_QUALITIES = Object.freeze(["high", "low"]);
|
|
304
|
+
var HIGH_ONLY = Object.freeze(["high"]);
|
|
305
|
+
function qualitiesFor(render, baseline) {
|
|
306
|
+
if (typeof render?.setQuality === "function") return ALL_QUALITIES;
|
|
307
|
+
return baseline === void 0 ? HIGH_ONLY : LEGACY_QUALITIES;
|
|
308
|
+
}
|
|
309
|
+
async function applyQuality(render, quality, baseline) {
|
|
310
|
+
if (typeof render.setQuality === "function") {
|
|
311
|
+
try {
|
|
312
|
+
await render.setQuality(quality);
|
|
313
|
+
} catch (error) {
|
|
314
|
+
throw new SmartEarthError("RENDER_INIT_FAILED", `\u5207\u6362\u5230 ${quality} \u753B\u8D28\u5931\u8D25\uFF1A${describeCause(error)}`, error);
|
|
315
|
+
}
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (quality === "medium") {
|
|
319
|
+
throw new SmartEarthError(
|
|
320
|
+
"QUALITY_UNSUPPORTED",
|
|
321
|
+
"\u5F53\u524D @metagl/sdk-render \u7248\u672C\u4E0D\u652F\u6301 medium \u753B\u8D28\uFF0C\u53EA\u80FD\u7528 high \u6216 low\uFF08\u5347\u7EA7\u5230 4.x \u540E\u53EF\u7528 medium\uFF09\u3002"
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
if (baseline === void 0) {
|
|
325
|
+
throw new SmartEarthError(
|
|
326
|
+
"QUALITY_UNSUPPORTED",
|
|
327
|
+
"\u5F53\u524D @metagl/sdk-render \u65E2\u6CA1\u6709 setQuality \u4E5F\u6CA1\u6709\u5BFC\u51FA DEMO_ENVIRONMENT_BASELINE\uFF0C\u65E0\u6CD5\u5207\u6362\u753B\u8D28\u3002"
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
const config = quality === "low" ? buildLowConfig(baseline) : buildHighConfig(baseline);
|
|
331
|
+
try {
|
|
332
|
+
await render.loadConfig(config);
|
|
333
|
+
render.ensureFullPipelineOrder?.();
|
|
334
|
+
} catch (error) {
|
|
335
|
+
throw new SmartEarthError(
|
|
336
|
+
"RENDER_INIT_FAILED",
|
|
337
|
+
`\u5207\u6362\u5230 ${quality} \u753B\u8D28\u5931\u8D25\uFF1A${describeCause(error)}`,
|
|
338
|
+
error
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// src/layers/registry.ts
|
|
344
|
+
function toInfo(entry) {
|
|
345
|
+
return { id: entry.id, kind: entry.kind, visible: entry.visible };
|
|
346
|
+
}
|
|
347
|
+
function createLayerRegistry(context, isAlive = () => true) {
|
|
348
|
+
const factories = /* @__PURE__ */ new Map();
|
|
349
|
+
const layers = /* @__PURE__ */ new Map();
|
|
350
|
+
const pending = /* @__PURE__ */ new Set();
|
|
351
|
+
function requireLayer(id) {
|
|
352
|
+
const entry = layers.get(id);
|
|
353
|
+
if (!entry) throw new SmartEarthError("LAYER_NOT_FOUND", `\u56FE\u5C42\u4E0D\u5B58\u5728\uFF1A${id}`);
|
|
354
|
+
return entry;
|
|
355
|
+
}
|
|
356
|
+
return {
|
|
357
|
+
register(kind, factory) {
|
|
358
|
+
if (typeof kind !== "string" || kind.length === 0 || typeof factory !== "function") {
|
|
359
|
+
throw new SmartEarthError("INVALID_OPTIONS", "layers.register \u9700\u8981\u975E\u7A7A kind \u4E0E\u5DE5\u5382\u51FD\u6570\u3002");
|
|
360
|
+
}
|
|
361
|
+
factories.set(kind, factory);
|
|
362
|
+
},
|
|
363
|
+
async add(spec) {
|
|
364
|
+
if (!spec || typeof spec.id !== "string" || spec.id.length === 0) {
|
|
365
|
+
throw new SmartEarthError("INVALID_OPTIONS", "\u56FE\u5C42\u9700\u8981\u975E\u7A7A id\u3002");
|
|
366
|
+
}
|
|
367
|
+
const factory = factories.get(spec.kind);
|
|
368
|
+
if (!factory) {
|
|
369
|
+
throw new SmartEarthError("LAYER_KIND_UNKNOWN", `\u672A\u6CE8\u518C\u7684\u56FE\u5C42\u79CD\u7C7B\uFF1A${String(spec.kind)}`);
|
|
370
|
+
}
|
|
371
|
+
if (layers.has(spec.id) || pending.has(spec.id)) {
|
|
372
|
+
throw new SmartEarthError("LAYER_DUPLICATE", `\u56FE\u5C42 id \u5DF2\u5B58\u5728\uFF1A${spec.id}`);
|
|
373
|
+
}
|
|
374
|
+
pending.add(spec.id);
|
|
375
|
+
try {
|
|
376
|
+
let handle;
|
|
377
|
+
try {
|
|
378
|
+
handle = await factory(context, spec);
|
|
379
|
+
} catch (error) {
|
|
380
|
+
if (!isAlive()) throw new SmartEarthError("DESTROYED", "\u5730\u7403\u5DF2\u9500\u6BC1\u3002");
|
|
381
|
+
if (error instanceof SmartEarthError) throw error;
|
|
382
|
+
throw new SmartEarthError("INVALID_OPTIONS", `\u56FE\u5C42 ${spec.id} \u521B\u5EFA\u5931\u8D25\uFF1A${describeLayerCause(error)}`);
|
|
383
|
+
}
|
|
384
|
+
if (!isAlive()) {
|
|
385
|
+
handle.destroy();
|
|
386
|
+
throw new SmartEarthError("DESTROYED", "\u5730\u7403\u5DF2\u9500\u6BC1\u3002");
|
|
387
|
+
}
|
|
388
|
+
const visible = spec.visible ?? true;
|
|
389
|
+
if (!visible) handle.setVisible(false);
|
|
390
|
+
const entry = { id: spec.id, kind: spec.kind, handle, visible };
|
|
391
|
+
layers.set(spec.id, entry);
|
|
392
|
+
return toInfo(entry);
|
|
393
|
+
} finally {
|
|
394
|
+
pending.delete(spec.id);
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
remove(id) {
|
|
398
|
+
const entry = layers.get(id);
|
|
399
|
+
if (!entry) return false;
|
|
400
|
+
layers.delete(id);
|
|
401
|
+
entry.handle.destroy();
|
|
402
|
+
return true;
|
|
403
|
+
},
|
|
404
|
+
setVisible(id, visible) {
|
|
405
|
+
const entry = requireLayer(id);
|
|
406
|
+
entry.handle.setVisible(visible);
|
|
407
|
+
entry.visible = visible;
|
|
408
|
+
},
|
|
409
|
+
list() {
|
|
410
|
+
return [...layers.values()].map(toInfo);
|
|
411
|
+
},
|
|
412
|
+
get(id) {
|
|
413
|
+
return requireLayer(id).handle.api;
|
|
414
|
+
},
|
|
415
|
+
flyTarget(id) {
|
|
416
|
+
const target = requireLayer(id).handle.flyTarget?.();
|
|
417
|
+
if (target === void 0) {
|
|
418
|
+
throw new SmartEarthError("INVALID_OPTIONS", `\u56FE\u5C42 ${id} \u4E0D\u652F\u6301 flyTo\u3002`);
|
|
419
|
+
}
|
|
420
|
+
return target;
|
|
421
|
+
},
|
|
422
|
+
destroyAll() {
|
|
423
|
+
const entries = [...layers.values()];
|
|
424
|
+
layers.clear();
|
|
425
|
+
for (const entry of entries) {
|
|
426
|
+
try {
|
|
427
|
+
entry.handle.destroy();
|
|
428
|
+
} catch {
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// src/layers/points.ts
|
|
436
|
+
var DEFAULT_PIXEL_SIZE = 12;
|
|
437
|
+
var LABEL_OFFSET_Y = -18;
|
|
438
|
+
function validate(spec) {
|
|
439
|
+
if (!Array.isArray(spec.data)) {
|
|
440
|
+
throw new SmartEarthError("INVALID_OPTIONS", `points \u56FE\u5C42 ${spec.id} \u9700\u8981 data \u6570\u7EC4\u3002`);
|
|
441
|
+
}
|
|
442
|
+
spec.data.forEach((datum, index) => {
|
|
443
|
+
const ok = typeof datum?.lon === "number" && Number.isFinite(datum.lon) && typeof datum?.lat === "number" && Number.isFinite(datum.lat);
|
|
444
|
+
if (!ok) {
|
|
445
|
+
throw new SmartEarthError(
|
|
446
|
+
"INVALID_OPTIONS",
|
|
447
|
+
`points \u56FE\u5C42 ${spec.id} \u7B2C ${String(index)} \u4E2A\u70B9\u7F3A\u5C11\u6709\u6548\u7684 lon/lat\u3002`
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
var pointsLayerFactory = async (context, spec) => {
|
|
453
|
+
validate(spec);
|
|
454
|
+
const { Cesium, viewer } = context;
|
|
455
|
+
const fallback = Cesium.Color.fromCssColorString(spec.defaultColor ?? "#ffffff");
|
|
456
|
+
const palette = new Map(
|
|
457
|
+
Object.entries(spec.colors ?? {}).map(([value, css]) => [
|
|
458
|
+
value,
|
|
459
|
+
Cesium.Color.fromCssColorString(css) ?? fallback
|
|
460
|
+
])
|
|
461
|
+
);
|
|
462
|
+
const colorOf = (datum) => {
|
|
463
|
+
if (!spec.colorBy) return fallback;
|
|
464
|
+
return palette.get(String(datum[spec.colorBy])) ?? fallback;
|
|
465
|
+
};
|
|
466
|
+
const source = new Cesium.CustomDataSource(spec.id);
|
|
467
|
+
const entities = [];
|
|
468
|
+
spec.data.forEach((datum, index) => {
|
|
469
|
+
const featureId = String(datum.id ?? index);
|
|
470
|
+
const clamp = datum.height === void 0;
|
|
471
|
+
const heightReference = clamp ? Cesium.HeightReference.CLAMP_TO_GROUND : Cesium.HeightReference.NONE;
|
|
472
|
+
const labelText = spec.labelField ? datum[spec.labelField] : void 0;
|
|
473
|
+
const entity = source.entities.add({
|
|
474
|
+
id: `${spec.id}:${featureId}`,
|
|
475
|
+
position: Cesium.Cartesian3.fromDegrees(datum.lon, datum.lat, datum.height ?? 0),
|
|
476
|
+
point: {
|
|
477
|
+
pixelSize: spec.pixelSize ?? DEFAULT_PIXEL_SIZE,
|
|
478
|
+
color: colorOf(datum),
|
|
479
|
+
outlineColor: Cesium.Color.BLACK,
|
|
480
|
+
outlineWidth: 1,
|
|
481
|
+
heightReference,
|
|
482
|
+
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
|
483
|
+
},
|
|
484
|
+
...labelText === void 0 || labelText === null ? {} : {
|
|
485
|
+
label: {
|
|
486
|
+
text: String(labelText),
|
|
487
|
+
font: "13px sans-serif",
|
|
488
|
+
pixelOffset: new Cesium.Cartesian2(0, LABEL_OFFSET_Y),
|
|
489
|
+
heightReference,
|
|
490
|
+
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
entities.push(entity);
|
|
495
|
+
context.registerPickable(entity, { layerId: spec.id, featureId, properties: { ...datum } });
|
|
496
|
+
});
|
|
497
|
+
await viewer.dataSources.add(source);
|
|
498
|
+
return {
|
|
499
|
+
setVisible(visible) {
|
|
500
|
+
source.show = visible;
|
|
501
|
+
viewer.scene.requestRender();
|
|
502
|
+
},
|
|
503
|
+
flyTarget() {
|
|
504
|
+
return source;
|
|
505
|
+
},
|
|
506
|
+
destroy() {
|
|
507
|
+
for (const entity of entities) context.unregisterPickable(entity);
|
|
508
|
+
viewer.dataSources.remove(source, true);
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
// src/layers/geojson.ts
|
|
514
|
+
var DEFAULTS = {
|
|
515
|
+
fill: "#3b82f6",
|
|
516
|
+
fillOpacity: 0.35,
|
|
517
|
+
stroke: "#1d4ed8",
|
|
518
|
+
strokeWidth: 2,
|
|
519
|
+
pointColor: "#ffffff",
|
|
520
|
+
pointSize: 10
|
|
521
|
+
};
|
|
522
|
+
var LABEL_OFFSET_Y2 = -16;
|
|
523
|
+
function validate2(spec) {
|
|
524
|
+
requireLayerSpec(isRecord(spec.data) || typeof spec.data === "string", spec.id, "data \u9700\u8981 GeoJSON \u5BF9\u8C61\u6216 URL\u3002");
|
|
525
|
+
if (spec.colorBy !== void 0) {
|
|
526
|
+
requireLayerSpec(
|
|
527
|
+
isRecord(spec.colorBy) && typeof spec.colorBy.field === "string" && isRecord(spec.colorBy.colors),
|
|
528
|
+
spec.id,
|
|
529
|
+
"colorBy \u9700\u8981 { field, colors }\u3002"
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
function readProperties(entity, time) {
|
|
534
|
+
const bag = entity.properties;
|
|
535
|
+
const value = bag?.getValue?.(time);
|
|
536
|
+
return isRecord(value) ? value : {};
|
|
537
|
+
}
|
|
538
|
+
function geometryAnchor(Cesium, entity, time) {
|
|
539
|
+
const hierarchy = entity.polygon?.hierarchy?.getValue(time);
|
|
540
|
+
const linePositions = entity.polyline?.positions?.getValue(time);
|
|
541
|
+
const positions = hierarchy?.positions ?? linePositions;
|
|
542
|
+
if (!positions || positions.length === 0) return void 0;
|
|
543
|
+
if (linePositions && !hierarchy) return linePositions[Math.floor(linePositions.length / 2)];
|
|
544
|
+
return Cesium.BoundingSphere.fromPoints(positions).center;
|
|
545
|
+
}
|
|
546
|
+
var geojsonLayerFactory = async (context, spec) => {
|
|
547
|
+
validate2(spec);
|
|
548
|
+
const { Cesium, viewer } = context;
|
|
549
|
+
const data = await loadJson(spec.data, spec.id);
|
|
550
|
+
const definedStyle = Object.fromEntries(Object.entries(spec.style ?? {}).filter(([, value]) => value !== void 0));
|
|
551
|
+
const style = { ...DEFAULTS, ...definedStyle };
|
|
552
|
+
const clampToGround = spec.clampToGround ?? true;
|
|
553
|
+
let source;
|
|
554
|
+
try {
|
|
555
|
+
source = await Cesium.GeoJsonDataSource.load(data, { clampToGround });
|
|
556
|
+
} catch (error) {
|
|
557
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u56FE\u5C42 ${spec.id} GeoJSON \u89E3\u6790\u5931\u8D25\uFF1A${describeLayerCause(error)}`);
|
|
558
|
+
}
|
|
559
|
+
source.name = spec.id;
|
|
560
|
+
const colorFor = fieldColorResolver(Cesium, spec.colorBy, cssColor(Cesium, style.stroke, Cesium.Color.BLUE));
|
|
561
|
+
const fillFallback = cssColor(Cesium, style.fill, Cesium.Color.BLUE);
|
|
562
|
+
const fillFor = fieldColorResolver(Cesium, spec.colorBy, fillFallback);
|
|
563
|
+
const pointFor = fieldColorResolver(Cesium, spec.colorBy, cssColor(Cesium, style.pointColor, Cesium.Color.WHITE));
|
|
564
|
+
const now = viewer.clock.currentTime;
|
|
565
|
+
const heightReference = clampToGround ? Cesium.HeightReference.CLAMP_TO_GROUND : Cesium.HeightReference.NONE;
|
|
566
|
+
const entities = [...source.entities.values];
|
|
567
|
+
entities.forEach((entity, index) => {
|
|
568
|
+
const properties = readProperties(entity, now);
|
|
569
|
+
if (entity.polygon) {
|
|
570
|
+
entity.polygon.material = new Cesium.ColorMaterialProperty(fillFor(properties).withAlpha(style.fillOpacity));
|
|
571
|
+
entity.polygon.outline = new Cesium.ConstantProperty(!clampToGround);
|
|
572
|
+
entity.polygon.outlineColor = new Cesium.ConstantProperty(colorFor(properties));
|
|
573
|
+
}
|
|
574
|
+
if (entity.polyline) {
|
|
575
|
+
entity.polyline.material = new Cesium.ColorMaterialProperty(colorFor(properties));
|
|
576
|
+
entity.polyline.width = new Cesium.ConstantProperty(style.strokeWidth);
|
|
577
|
+
}
|
|
578
|
+
if (entity.billboard) {
|
|
579
|
+
entity.billboard = void 0;
|
|
580
|
+
entity.point = new Cesium.PointGraphics({
|
|
581
|
+
pixelSize: style.pointSize,
|
|
582
|
+
color: pointFor(properties),
|
|
583
|
+
outlineColor: Cesium.Color.BLACK,
|
|
584
|
+
outlineWidth: 1,
|
|
585
|
+
heightReference,
|
|
586
|
+
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
const labelText = spec.labelField ? properties[spec.labelField] : void 0;
|
|
590
|
+
if (labelText !== void 0 && labelText !== null && !entity.position) {
|
|
591
|
+
const anchor = geometryAnchor(Cesium, entity, now);
|
|
592
|
+
if (anchor) entity.position = new Cesium.ConstantPositionProperty(anchor);
|
|
593
|
+
}
|
|
594
|
+
if (labelText !== void 0 && labelText !== null && entity.position) {
|
|
595
|
+
entity.label = new Cesium.LabelGraphics({
|
|
596
|
+
text: String(labelText),
|
|
597
|
+
font: "13px sans-serif",
|
|
598
|
+
pixelOffset: new Cesium.Cartesian2(0, LABEL_OFFSET_Y2),
|
|
599
|
+
heightReference,
|
|
600
|
+
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
const featureId = String(properties.id ?? entity.id ?? index);
|
|
604
|
+
context.registerPickable(entity, { layerId: spec.id, featureId, properties });
|
|
605
|
+
});
|
|
606
|
+
await viewer.dataSources.add(source);
|
|
607
|
+
return {
|
|
608
|
+
setVisible(visible) {
|
|
609
|
+
source.show = visible;
|
|
610
|
+
viewer.scene.requestRender();
|
|
611
|
+
},
|
|
612
|
+
flyTarget: () => source,
|
|
613
|
+
destroy() {
|
|
614
|
+
for (const entity of entities) context.unregisterPickable(entity);
|
|
615
|
+
viewer.dataSources.remove(source, true);
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
};
|
|
619
|
+
|
|
620
|
+
// src/layers/tileset3d.ts
|
|
621
|
+
function featureProperties(feature) {
|
|
622
|
+
const ids = feature.getPropertyIds?.() ?? [];
|
|
623
|
+
return Object.fromEntries(ids.map((id) => [id, feature.getProperty?.(id)]));
|
|
624
|
+
}
|
|
625
|
+
var tileset3dLayerFactory = async (context, spec) => {
|
|
626
|
+
requireLayerSpec(typeof spec.url === "string" && spec.url.length > 0, spec.id, "url \u5FC5\u586B\u3002");
|
|
627
|
+
if (spec.pbr !== void 0) {
|
|
628
|
+
requireLayerSpec(isRecord(spec.pbr), spec.id, "pbr \u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
|
|
629
|
+
if (!context.pbr) {
|
|
630
|
+
throw new SmartEarthError("PBR_UNSUPPORTED", `\u5F53\u524D sdk-render \u7248\u672C\u4E0D\u652F\u6301 PBR \u63A7\u5236\uFF08\u9700\u8981 4.x\uFF09\uFF0C\u56FE\u5C42 ${spec.id} \u4E0D\u80FD\u5E26 pbr\u3002`);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
const { Cesium, viewer, pbr } = context;
|
|
634
|
+
let tileset;
|
|
635
|
+
try {
|
|
636
|
+
tileset = await Cesium.Cesium3DTileset.fromUrl(spec.url, {
|
|
637
|
+
...spec.maximumScreenSpaceError !== void 0 ? { maximumScreenSpaceError: spec.maximumScreenSpaceError } : {}
|
|
638
|
+
});
|
|
639
|
+
} catch (error) {
|
|
640
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u56FE\u5C42 ${spec.id} 3D Tiles \u52A0\u8F7D\u5931\u8D25\uFF1A${describeLayerCause(error)}`);
|
|
641
|
+
}
|
|
642
|
+
viewer.scene.primitives.add(tileset);
|
|
643
|
+
if (spec.pbr) {
|
|
644
|
+
try {
|
|
645
|
+
pbr?.setTilesetMaterial(tileset, spec.pbr);
|
|
646
|
+
} catch (error) {
|
|
647
|
+
viewer.scene.primitives.remove(tileset);
|
|
648
|
+
throw error;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
const resolvePick = (picked) => {
|
|
652
|
+
const feature = picked;
|
|
653
|
+
if (!feature || feature.tileset !== tileset) return void 0;
|
|
654
|
+
return {
|
|
655
|
+
layerId: spec.id,
|
|
656
|
+
featureId: String(feature.featureId ?? ""),
|
|
657
|
+
properties: featureProperties(feature)
|
|
658
|
+
};
|
|
659
|
+
};
|
|
660
|
+
const unregisterPick = context.registerPickResolver(resolvePick);
|
|
661
|
+
let hasMaterial = Boolean(spec.pbr);
|
|
662
|
+
const requirePbr = () => {
|
|
663
|
+
if (!pbr) throw new SmartEarthError("PBR_UNSUPPORTED", "\u5F53\u524D sdk-render \u7248\u672C\u4E0D\u652F\u6301 PBR \u63A7\u5236\uFF08\u9700\u8981 4.x\uFF09\u3002");
|
|
664
|
+
return pbr;
|
|
665
|
+
};
|
|
666
|
+
const api = {
|
|
667
|
+
tileset,
|
|
668
|
+
setMaterial(params) {
|
|
669
|
+
requirePbr().setTilesetMaterial(tileset, params);
|
|
670
|
+
hasMaterial = true;
|
|
671
|
+
},
|
|
672
|
+
clearMaterial() {
|
|
673
|
+
requirePbr().clearTilesetMaterial(tileset);
|
|
674
|
+
hasMaterial = false;
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
return {
|
|
678
|
+
api,
|
|
679
|
+
setVisible(visible) {
|
|
680
|
+
tileset.show = visible;
|
|
681
|
+
viewer.scene.requestRender();
|
|
682
|
+
},
|
|
683
|
+
flyTarget: () => tileset,
|
|
684
|
+
destroy() {
|
|
685
|
+
unregisterPick();
|
|
686
|
+
try {
|
|
687
|
+
if (hasMaterial) pbr?.clearTilesetMaterial(tileset);
|
|
688
|
+
} finally {
|
|
689
|
+
viewer.scene.primitives.remove(tileset);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
};
|
|
694
|
+
|
|
695
|
+
// src/layers/routePath.ts
|
|
696
|
+
function fail(layerId, message) {
|
|
697
|
+
throw new SmartEarthError("INVALID_OPTIONS", `\u822A\u7EBF\u56FE\u5C42 ${layerId}\uFF1A${message}`);
|
|
698
|
+
}
|
|
699
|
+
function toPoint(raw) {
|
|
700
|
+
if (Array.isArray(raw)) {
|
|
701
|
+
const [lon, lat, height] = raw;
|
|
702
|
+
if (typeof lon === "number" && typeof lat === "number") {
|
|
703
|
+
return typeof height === "number" ? { lon, lat, height } : { lon, lat };
|
|
704
|
+
}
|
|
705
|
+
return void 0;
|
|
706
|
+
}
|
|
707
|
+
if (isRecord(raw) && typeof raw.lon === "number" && typeof raw.lat === "number") {
|
|
708
|
+
return typeof raw.height === "number" ? { lon: raw.lon, lat: raw.lat, height: raw.height } : { lon: raw.lon, lat: raw.lat };
|
|
709
|
+
}
|
|
710
|
+
return void 0;
|
|
711
|
+
}
|
|
712
|
+
function lineStringCoordinates(geojson) {
|
|
713
|
+
if (geojson.type === "LineString" && Array.isArray(geojson.coordinates)) return geojson.coordinates;
|
|
714
|
+
if (geojson.type === "Feature" && isRecord(geojson.geometry)) return lineStringCoordinates(geojson.geometry);
|
|
715
|
+
if (geojson.type === "FeatureCollection" && Array.isArray(geojson.features)) {
|
|
716
|
+
for (const feature of geojson.features) {
|
|
717
|
+
const found = isRecord(feature) ? lineStringCoordinates(feature) : void 0;
|
|
718
|
+
if (found) return found;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
return void 0;
|
|
722
|
+
}
|
|
723
|
+
function parseKmlCoordinates(kml) {
|
|
724
|
+
const match = /<LineString[\s\S]*?<coordinates>([\s\S]*?)<\/coordinates>/i.exec(kml);
|
|
725
|
+
if (!match?.[1]) return void 0;
|
|
726
|
+
return match[1].trim().split(/\s+/).map((tuple) => tuple.split(",").map(Number)).filter((values) => values.length >= 2 && values.every(Number.isFinite));
|
|
727
|
+
}
|
|
728
|
+
function parseRouteSource(source, layerId) {
|
|
729
|
+
let raw;
|
|
730
|
+
if (typeof source === "string") {
|
|
731
|
+
raw = parseKmlCoordinates(source);
|
|
732
|
+
if (!raw) fail(layerId, "KML \u91CC\u6CA1\u6709\u627E\u5230 LineString \u5750\u6807\u3002");
|
|
733
|
+
} else if (Array.isArray(source)) {
|
|
734
|
+
raw = source;
|
|
735
|
+
} else if (isRecord(source)) {
|
|
736
|
+
raw = lineStringCoordinates(source);
|
|
737
|
+
if (!raw) fail(layerId, "GeoJSON \u91CC\u6CA1\u6709\u627E\u5230 LineString\u3002");
|
|
738
|
+
} else {
|
|
739
|
+
fail(layerId, "path \u9700\u8981\u5750\u6807\u6570\u7EC4\u3001GeoJSON LineString \u6216 KML \u6587\u672C\u3002");
|
|
740
|
+
}
|
|
741
|
+
const points = raw.map(toPoint);
|
|
742
|
+
if (points.some((point) => point === void 0)) fail(layerId, "\u5750\u6807\u683C\u5F0F\u4E0D\u5BF9\uFF0C\u9700\u8981 [lon, lat, height?] \u6216 { lon, lat }\u3002");
|
|
743
|
+
if (points.length < 2) fail(layerId, "\u822A\u7EBF\u81F3\u5C11\u8981 2 \u4E2A\u70B9\u3002");
|
|
744
|
+
return points;
|
|
745
|
+
}
|
|
746
|
+
function cumulativeLengths(segmentLengths) {
|
|
747
|
+
const out = [0];
|
|
748
|
+
for (const length of segmentLengths) out.push((out[out.length - 1] ?? 0) + length);
|
|
749
|
+
return out;
|
|
750
|
+
}
|
|
751
|
+
function locate(cumulative, progress) {
|
|
752
|
+
const total = cumulative[cumulative.length - 1] ?? 0;
|
|
753
|
+
const lastSegment = Math.max(0, cumulative.length - 2);
|
|
754
|
+
if (total <= 0) return { index: 0, fraction: 0 };
|
|
755
|
+
const target = Math.min(1, Math.max(0, progress)) * total;
|
|
756
|
+
for (let i = 0; i <= lastSegment; i += 1) {
|
|
757
|
+
const start = cumulative[i] ?? 0;
|
|
758
|
+
const end = cumulative[i + 1] ?? start;
|
|
759
|
+
if (target <= end || i === lastSegment) {
|
|
760
|
+
const span = end - start;
|
|
761
|
+
return { index: i, fraction: span > 0 ? (target - start) / span : 0 };
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
return { index: lastSegment, fraction: 1 };
|
|
765
|
+
}
|
|
766
|
+
function advance(progress, deltaSeconds, durationSeconds, speed, loop) {
|
|
767
|
+
const next = progress + deltaSeconds * speed / durationSeconds;
|
|
768
|
+
if (next < 1) return { progress: next, ended: false };
|
|
769
|
+
return loop ? { progress: next % 1, ended: false } : { progress: 1, ended: true };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/layers/route.ts
|
|
773
|
+
var DEFAULT_DURATION = 60;
|
|
774
|
+
var DEFAULT_FOLLOW_RANGE = 2e3;
|
|
775
|
+
var FOLLOW_HEIGHT_RATIO = 0.6;
|
|
776
|
+
var MS_PER_SECOND = 1e3;
|
|
777
|
+
async function resolveSource(path, layerId) {
|
|
778
|
+
const isKmlUrl = typeof path === "string" && !path.includes("<") && /^(https?:\/\/|\/)/.test(path.trim());
|
|
779
|
+
if (!isKmlUrl) return path;
|
|
780
|
+
try {
|
|
781
|
+
const response = await fetch(path);
|
|
782
|
+
if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
|
|
783
|
+
const text = await response.text();
|
|
784
|
+
return /^\s*[[{]/.test(text) ? JSON.parse(text) : text;
|
|
785
|
+
} catch (error) {
|
|
786
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u822A\u7EBF\u56FE\u5C42 ${layerId} \u6570\u636E\u8BFB\u53D6\u5931\u8D25\uFF1A${describeLayerCause(error)}`);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
function validate3(spec) {
|
|
790
|
+
const positive = (value) => value === void 0 || typeof value === "number" && value > 0;
|
|
791
|
+
requireLayerSpec(positive(spec.durationSeconds), spec.id, "durationSeconds \u5FC5\u987B > 0\u3002");
|
|
792
|
+
requireLayerSpec(positive(spec.pathWidth) && positive(spec.markerSize), spec.id, "pathWidth / markerSize \u5FC5\u987B > 0\u3002");
|
|
793
|
+
requireLayerSpec(positive(spec.followRange), spec.id, "followRange \u5FC5\u987B > 0\u3002");
|
|
794
|
+
}
|
|
795
|
+
var routeLayerFactory = async (context, spec) => {
|
|
796
|
+
validate3(spec);
|
|
797
|
+
const { Cesium, viewer } = context;
|
|
798
|
+
const points = parseRouteSource(await resolveSource(spec.path, spec.id), spec.id);
|
|
799
|
+
const clamp = points.every((point) => point.height === void 0);
|
|
800
|
+
const cartesians = points.map((p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height ?? 0));
|
|
801
|
+
const cumulative = cumulativeLengths(
|
|
802
|
+
cartesians.slice(1).map((point, i) => Cesium.Cartesian3.distance(cartesians[i], point))
|
|
803
|
+
);
|
|
804
|
+
const duration = spec.durationSeconds ?? DEFAULT_DURATION;
|
|
805
|
+
const heightReference = clamp ? Cesium.HeightReference.CLAMP_TO_GROUND : Cesium.HeightReference.NONE;
|
|
806
|
+
const events = new Emitter((error) => console.error("[smartearth-base] \u822A\u7EBF\u76D1\u542C\u5668\u51FA\u9519", error));
|
|
807
|
+
let progress = 0;
|
|
808
|
+
let playing = false;
|
|
809
|
+
let speed = 1;
|
|
810
|
+
let lastTick;
|
|
811
|
+
const current = Cesium.Cartesian3.clone(cartesians[0]);
|
|
812
|
+
const updatePosition = () => {
|
|
813
|
+
const { index, fraction } = locate(cumulative, progress);
|
|
814
|
+
Cesium.Cartesian3.lerp(cartesians[index], cartesians[index + 1], fraction, current);
|
|
815
|
+
};
|
|
816
|
+
const emitProgress = () => {
|
|
817
|
+
const carto = Cesium.Cartographic.fromCartesian(current);
|
|
818
|
+
events.emit("progress", {
|
|
819
|
+
progress,
|
|
820
|
+
lon: Cesium.Math.toDegrees(carto.longitude),
|
|
821
|
+
lat: Cesium.Math.toDegrees(carto.latitude),
|
|
822
|
+
height: carto.height
|
|
823
|
+
});
|
|
824
|
+
};
|
|
825
|
+
const PositionProperty = Cesium.CallbackPositionProperty ?? Cesium.CallbackProperty;
|
|
826
|
+
const source = new Cesium.CustomDataSource(spec.id);
|
|
827
|
+
if (spec.showPath ?? true) {
|
|
828
|
+
source.entities.add({
|
|
829
|
+
id: `${spec.id}:path`,
|
|
830
|
+
polyline: {
|
|
831
|
+
positions: cartesians,
|
|
832
|
+
width: spec.pathWidth ?? 3,
|
|
833
|
+
clampToGround: clamp,
|
|
834
|
+
material: cssColor(Cesium, spec.pathColor, Cesium.Color.CYAN)
|
|
835
|
+
}
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
const followRange = spec.followRange ?? DEFAULT_FOLLOW_RANGE;
|
|
839
|
+
const marker = source.entities.add({
|
|
840
|
+
id: `${spec.id}:marker`,
|
|
841
|
+
position: new PositionProperty(() => current, false),
|
|
842
|
+
// trackedEntity 对一个点默认贴得极近;给个后上方的视角偏移。
|
|
843
|
+
viewFrom: Cesium.Cartesian3.fromElements(0, -followRange, followRange * FOLLOW_HEIGHT_RATIO),
|
|
844
|
+
point: {
|
|
845
|
+
pixelSize: spec.markerSize ?? 12,
|
|
846
|
+
color: cssColor(Cesium, spec.markerColor, Cesium.Color.YELLOW),
|
|
847
|
+
outlineColor: Cesium.Color.BLACK,
|
|
848
|
+
outlineWidth: 2,
|
|
849
|
+
heightReference,
|
|
850
|
+
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
|
851
|
+
}
|
|
852
|
+
});
|
|
853
|
+
await viewer.dataSources.add(source);
|
|
854
|
+
const removeTick = viewer.scene.preRender.addEventListener(() => {
|
|
855
|
+
const now = performance.now();
|
|
856
|
+
const delta = lastTick === void 0 ? 0 : (now - lastTick) / MS_PER_SECOND;
|
|
857
|
+
lastTick = now;
|
|
858
|
+
if (!playing || delta <= 0) return;
|
|
859
|
+
const step = advance(progress, delta, duration, speed, spec.loop ?? false);
|
|
860
|
+
progress = step.progress;
|
|
861
|
+
updatePosition();
|
|
862
|
+
emitProgress();
|
|
863
|
+
if (step.ended) {
|
|
864
|
+
playing = false;
|
|
865
|
+
events.emit("end", void 0);
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
const setFollow = (follow) => {
|
|
869
|
+
if (follow) viewer.trackedEntity = marker;
|
|
870
|
+
else if (viewer.trackedEntity === marker) viewer.trackedEntity = void 0;
|
|
871
|
+
};
|
|
872
|
+
const api = {
|
|
873
|
+
get progress() {
|
|
874
|
+
return progress;
|
|
875
|
+
},
|
|
876
|
+
get playing() {
|
|
877
|
+
return playing;
|
|
878
|
+
},
|
|
879
|
+
get speed() {
|
|
880
|
+
return speed;
|
|
881
|
+
},
|
|
882
|
+
play() {
|
|
883
|
+
if (progress >= 1 && !(spec.loop ?? false)) progress = 0;
|
|
884
|
+
playing = true;
|
|
885
|
+
lastTick = void 0;
|
|
886
|
+
},
|
|
887
|
+
pause() {
|
|
888
|
+
playing = false;
|
|
889
|
+
},
|
|
890
|
+
seek(next) {
|
|
891
|
+
if (typeof next !== "number" || !Number.isFinite(next)) {
|
|
892
|
+
throw new SmartEarthError("INVALID_OPTIONS", "seek \u9700\u8981 0~1 \u7684\u6570\u5B57\u3002");
|
|
893
|
+
}
|
|
894
|
+
progress = Math.min(1, Math.max(0, next));
|
|
895
|
+
updatePosition();
|
|
896
|
+
emitProgress();
|
|
897
|
+
viewer.scene.requestRender();
|
|
898
|
+
},
|
|
899
|
+
setSpeed(multiplier) {
|
|
900
|
+
if (typeof multiplier !== "number" || !(multiplier > 0)) {
|
|
901
|
+
throw new SmartEarthError("INVALID_OPTIONS", "\u500D\u901F\u5FC5\u987B > 0\u3002");
|
|
902
|
+
}
|
|
903
|
+
speed = multiplier;
|
|
904
|
+
},
|
|
905
|
+
setFollow,
|
|
906
|
+
on: (event, listener) => events.on(event, listener)
|
|
907
|
+
};
|
|
908
|
+
if (spec.follow) setFollow(true);
|
|
909
|
+
if (spec.autoplay) api.play();
|
|
910
|
+
return {
|
|
911
|
+
api,
|
|
912
|
+
setVisible(visible) {
|
|
913
|
+
source.show = visible;
|
|
914
|
+
viewer.scene.requestRender();
|
|
915
|
+
},
|
|
916
|
+
flyTarget: () => source,
|
|
917
|
+
destroy() {
|
|
918
|
+
playing = false;
|
|
919
|
+
removeTick();
|
|
920
|
+
setFollow(false);
|
|
921
|
+
events.clear();
|
|
922
|
+
viewer.dataSources.remove(source, true);
|
|
923
|
+
}
|
|
924
|
+
};
|
|
925
|
+
};
|
|
926
|
+
|
|
927
|
+
// src/layers/annotation.ts
|
|
928
|
+
var DEFAULT_LEVELS = { \u9AD8: "#ef4444", \u4E2D: "#f97316", \u4F4E: "#eab308" };
|
|
929
|
+
var DEFAULT_LEVEL = "\u4E2D";
|
|
930
|
+
var EXPORT_VERSION = 1;
|
|
931
|
+
var LABEL_OFFSET_Y3 = -18;
|
|
932
|
+
function invalid(message) {
|
|
933
|
+
throw new SmartEarthError("INVALID_OPTIONS", `\u6807\u6CE8\uFF1A${message}`);
|
|
934
|
+
}
|
|
935
|
+
function normalizeItem(raw, makeId) {
|
|
936
|
+
if (!isRecord(raw)) invalid("\u6BCF\u6761\u6807\u6CE8\u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
|
|
937
|
+
const { lon, lat, height, name } = raw;
|
|
938
|
+
if (typeof lon !== "number" || typeof lat !== "number" || !Number.isFinite(lon) || !Number.isFinite(lat)) {
|
|
939
|
+
invalid("\u7F3A\u5C11\u6709\u6548\u7684 lon/lat\u3002");
|
|
940
|
+
}
|
|
941
|
+
if (typeof name !== "string" || name.trim().length === 0) invalid("name \u5FC5\u586B\u3002");
|
|
942
|
+
return {
|
|
943
|
+
id: typeof raw.id === "string" && raw.id ? raw.id : makeId(),
|
|
944
|
+
name: name.trim(),
|
|
945
|
+
level: typeof raw.level === "string" && raw.level ? raw.level : DEFAULT_LEVEL,
|
|
946
|
+
...typeof raw.description === "string" ? { description: raw.description } : {},
|
|
947
|
+
lon,
|
|
948
|
+
lat,
|
|
949
|
+
...typeof height === "number" && Number.isFinite(height) ? { height } : {},
|
|
950
|
+
createdAt: typeof raw.createdAt === "string" ? raw.createdAt : (/* @__PURE__ */ new Date()).toISOString()
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
function parseImport(json) {
|
|
954
|
+
let parsed = json;
|
|
955
|
+
if (typeof json === "string") {
|
|
956
|
+
try {
|
|
957
|
+
parsed = JSON.parse(json);
|
|
958
|
+
} catch {
|
|
959
|
+
invalid("\u5BFC\u5165\u5185\u5BB9\u4E0D\u662F\u5408\u6CD5 JSON\u3002");
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
if (isRecord(parsed) && Array.isArray(parsed.items)) return parsed.items;
|
|
963
|
+
if (Array.isArray(parsed)) return parsed;
|
|
964
|
+
return invalid("\u5BFC\u5165\u5185\u5BB9\u9700\u8981 { version, items } \u6216\u6570\u7EC4\u3002");
|
|
965
|
+
}
|
|
966
|
+
function createEntity(context, spec, item, levels) {
|
|
967
|
+
const { Cesium } = context;
|
|
968
|
+
const clamp = item.height === void 0;
|
|
969
|
+
const heightReference = clamp ? Cesium.HeightReference.CLAMP_TO_GROUND : Cesium.HeightReference.NONE;
|
|
970
|
+
return new Cesium.Entity({
|
|
971
|
+
id: `${spec.id}:${item.id}`,
|
|
972
|
+
position: Cesium.Cartesian3.fromDegrees(item.lon, item.lat, item.height ?? 0),
|
|
973
|
+
point: {
|
|
974
|
+
pixelSize: 12,
|
|
975
|
+
color: cssColor(Cesium, levels[item.level], Cesium.Color.WHITE),
|
|
976
|
+
outlineColor: Cesium.Color.BLACK,
|
|
977
|
+
outlineWidth: 1,
|
|
978
|
+
heightReference,
|
|
979
|
+
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
|
980
|
+
},
|
|
981
|
+
label: {
|
|
982
|
+
text: item.name,
|
|
983
|
+
font: "13px sans-serif",
|
|
984
|
+
pixelOffset: new Cesium.Cartesian2(0, LABEL_OFFSET_Y3),
|
|
985
|
+
heightReference,
|
|
986
|
+
disableDepthTestDistance: Number.POSITIVE_INFINITY
|
|
987
|
+
}
|
|
988
|
+
});
|
|
989
|
+
}
|
|
990
|
+
var annotationLayerFactory = async (context, spec) => {
|
|
991
|
+
if (spec.levels !== void 0) requireLayerSpec(isRecord(spec.levels), spec.id, "levels \u5FC5\u987B\u662F { \u7B49\u7EA7: \u989C\u8272 }\u3002");
|
|
992
|
+
const { Cesium, viewer } = context;
|
|
993
|
+
const levels = spec.levels ?? DEFAULT_LEVELS;
|
|
994
|
+
const items = /* @__PURE__ */ new Map();
|
|
995
|
+
const events = new Emitter((error) => console.error("[smartearth-base] \u6807\u6CE8\u76D1\u542C\u5668\u51FA\u9519", error));
|
|
996
|
+
const source = new Cesium.CustomDataSource(spec.id);
|
|
997
|
+
let counter = 0;
|
|
998
|
+
const makeId = () => `a${Date.now().toString(36)}${(counter += 1).toString(36)}`;
|
|
999
|
+
const list = () => [...items.values()].map((entry) => entry.item);
|
|
1000
|
+
const changed = () => {
|
|
1001
|
+
events.emit("change", list());
|
|
1002
|
+
viewer.scene.requestRender();
|
|
1003
|
+
};
|
|
1004
|
+
const insert = (item) => {
|
|
1005
|
+
const existing = items.get(item.id);
|
|
1006
|
+
if (existing) {
|
|
1007
|
+
context.unregisterPickable(existing.entity);
|
|
1008
|
+
source.entities.remove(existing.entity);
|
|
1009
|
+
}
|
|
1010
|
+
const entity = source.entities.add(createEntity(context, spec, item, levels));
|
|
1011
|
+
context.registerPickable(entity, { layerId: spec.id, featureId: item.id, properties: { ...item } });
|
|
1012
|
+
items.set(item.id, { item, entity });
|
|
1013
|
+
return item;
|
|
1014
|
+
};
|
|
1015
|
+
const removeOne = (id) => {
|
|
1016
|
+
const entry = items.get(id);
|
|
1017
|
+
if (!entry) return false;
|
|
1018
|
+
context.unregisterPickable(entry.entity);
|
|
1019
|
+
source.entities.remove(entry.entity);
|
|
1020
|
+
items.delete(id);
|
|
1021
|
+
return true;
|
|
1022
|
+
};
|
|
1023
|
+
const initial = (spec.items ?? []).map((raw) => normalizeItem(raw, makeId));
|
|
1024
|
+
for (const item of initial) insert(item);
|
|
1025
|
+
try {
|
|
1026
|
+
await viewer.dataSources.add(source);
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
for (const { entity } of items.values()) context.unregisterPickable(entity);
|
|
1029
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u6807\u6CE8\u56FE\u5C42 ${spec.id} \u52A0\u8F7D\u5931\u8D25\uFF1A${describeLayerCause(error)}`);
|
|
1030
|
+
}
|
|
1031
|
+
let pending;
|
|
1032
|
+
const unsubscribe = context.onClick((event) => {
|
|
1033
|
+
if (!pending || !event.position) return;
|
|
1034
|
+
const { draft, resolve } = pending;
|
|
1035
|
+
pending = void 0;
|
|
1036
|
+
const item = insert(normalizeItem({ ...draft, ...event.position }, makeId));
|
|
1037
|
+
changed();
|
|
1038
|
+
resolve(item);
|
|
1039
|
+
});
|
|
1040
|
+
const api = {
|
|
1041
|
+
startPlacing(draft) {
|
|
1042
|
+
if (!isRecord(draft) || typeof draft.name !== "string" || !draft.name.trim()) invalid("startPlacing \u9700\u8981 name\u3002");
|
|
1043
|
+
pending?.cancel();
|
|
1044
|
+
return new Promise((resolve) => {
|
|
1045
|
+
pending = { draft, resolve, cancel: () => resolve(void 0) };
|
|
1046
|
+
});
|
|
1047
|
+
},
|
|
1048
|
+
cancelPlacing() {
|
|
1049
|
+
pending?.cancel();
|
|
1050
|
+
pending = void 0;
|
|
1051
|
+
},
|
|
1052
|
+
get placing() {
|
|
1053
|
+
return pending !== void 0;
|
|
1054
|
+
},
|
|
1055
|
+
add(item) {
|
|
1056
|
+
const added = insert(normalizeItem(item, makeId));
|
|
1057
|
+
changed();
|
|
1058
|
+
return added;
|
|
1059
|
+
},
|
|
1060
|
+
remove(id) {
|
|
1061
|
+
const removed = removeOne(id);
|
|
1062
|
+
if (removed) changed();
|
|
1063
|
+
return removed;
|
|
1064
|
+
},
|
|
1065
|
+
list,
|
|
1066
|
+
clear() {
|
|
1067
|
+
for (const id of [...items.keys()]) removeOne(id);
|
|
1068
|
+
changed();
|
|
1069
|
+
},
|
|
1070
|
+
exportJSON() {
|
|
1071
|
+
return JSON.stringify({ version: EXPORT_VERSION, items: list() }, null, 2);
|
|
1072
|
+
},
|
|
1073
|
+
importJSON(json, options) {
|
|
1074
|
+
const incoming = parseImport(json).map((raw) => normalizeItem(raw, makeId));
|
|
1075
|
+
if (!options?.append) for (const id of [...items.keys()]) removeOne(id);
|
|
1076
|
+
for (const item of incoming) insert(item);
|
|
1077
|
+
changed();
|
|
1078
|
+
return incoming.length;
|
|
1079
|
+
},
|
|
1080
|
+
on: (event, listener) => events.on(event, listener)
|
|
1081
|
+
};
|
|
1082
|
+
return {
|
|
1083
|
+
api,
|
|
1084
|
+
setVisible(visible) {
|
|
1085
|
+
source.show = visible;
|
|
1086
|
+
viewer.scene.requestRender();
|
|
1087
|
+
},
|
|
1088
|
+
flyTarget: () => items.size > 0 ? source : void 0,
|
|
1089
|
+
destroy() {
|
|
1090
|
+
pending?.cancel();
|
|
1091
|
+
pending = void 0;
|
|
1092
|
+
unsubscribe();
|
|
1093
|
+
events.clear();
|
|
1094
|
+
for (const { entity } of items.values()) context.unregisterPickable(entity);
|
|
1095
|
+
items.clear();
|
|
1096
|
+
viewer.dataSources.remove(source, true);
|
|
1097
|
+
}
|
|
1098
|
+
};
|
|
1099
|
+
};
|
|
1100
|
+
|
|
1101
|
+
// src/layers/riverRibbon.ts
|
|
1102
|
+
var METERS_PER_DEGREE = 111320;
|
|
1103
|
+
function toRadians(degrees) {
|
|
1104
|
+
return degrees * Math.PI / 180;
|
|
1105
|
+
}
|
|
1106
|
+
function vertexNormal(coords, i, metersPerLon) {
|
|
1107
|
+
const segmentNormal = (a, b) => {
|
|
1108
|
+
const dx = ((b[0] ?? 0) - (a[0] ?? 0)) * metersPerLon;
|
|
1109
|
+
const dy = ((b[1] ?? 0) - (a[1] ?? 0)) * METERS_PER_DEGREE;
|
|
1110
|
+
const length2 = Math.hypot(dx, dy) || 1;
|
|
1111
|
+
return [-dy / length2, dx / length2];
|
|
1112
|
+
};
|
|
1113
|
+
const prev = i > 0 ? segmentNormal(coords[i - 1], coords[i]) : void 0;
|
|
1114
|
+
const next = i < coords.length - 1 ? segmentNormal(coords[i], coords[i + 1]) : void 0;
|
|
1115
|
+
const nx = (prev?.[0] ?? 0) + (next?.[0] ?? 0);
|
|
1116
|
+
const ny = (prev?.[1] ?? 0) + (next?.[1] ?? 0);
|
|
1117
|
+
const length = Math.hypot(nx, ny) || 1;
|
|
1118
|
+
return [nx / length, ny / length];
|
|
1119
|
+
}
|
|
1120
|
+
function lineToRibbonRing(rawCoords, widthMeters) {
|
|
1121
|
+
const coords = rawCoords.filter((c, i) => i === 0 || c[0] !== rawCoords[i - 1]?.[0] || c[1] !== rawCoords[i - 1]?.[1]);
|
|
1122
|
+
if (coords.length < 2) {
|
|
1123
|
+
throw new SmartEarthError("INVALID_OPTIONS", "\u6CB3\u9053\u7EBF\u81F3\u5C11\u8981 2 \u4E2A\u4E0D\u540C\u7684\u70B9\u3002");
|
|
1124
|
+
}
|
|
1125
|
+
const meanLat = coords.reduce((sum, c) => sum + (c[1] ?? 0), 0) / Math.max(1, coords.length);
|
|
1126
|
+
const metersPerLon = METERS_PER_DEGREE * Math.cos(toRadians(meanLat));
|
|
1127
|
+
const half = widthMeters / 2;
|
|
1128
|
+
const offset = (c, i, side) => {
|
|
1129
|
+
const [nx, ny] = vertexNormal(coords, i, metersPerLon);
|
|
1130
|
+
const lon = (c[0] ?? 0) + side * nx * half / metersPerLon;
|
|
1131
|
+
const lat = (c[1] ?? 0) + side * ny * half / METERS_PER_DEGREE;
|
|
1132
|
+
return c.length > 2 ? [lon, lat, c[2] ?? 0] : [lon, lat];
|
|
1133
|
+
};
|
|
1134
|
+
const left = coords.map((c, i) => offset(c, i, 1));
|
|
1135
|
+
const right = coords.map((c, i) => offset(c, i, -1)).reverse();
|
|
1136
|
+
const ring = [...left, ...right];
|
|
1137
|
+
return [...ring, ring[0]];
|
|
1138
|
+
}
|
|
1139
|
+
function convertGeometry(geometry, widthMeters) {
|
|
1140
|
+
if (!isRecord(geometry)) return geometry;
|
|
1141
|
+
if (geometry.type === "LineString" && Array.isArray(geometry.coordinates)) {
|
|
1142
|
+
return { type: "Polygon", coordinates: [lineToRibbonRing(geometry.coordinates, widthMeters)] };
|
|
1143
|
+
}
|
|
1144
|
+
if (geometry.type === "MultiLineString" && Array.isArray(geometry.coordinates)) {
|
|
1145
|
+
return {
|
|
1146
|
+
type: "MultiPolygon",
|
|
1147
|
+
coordinates: geometry.coordinates.map((line) => [lineToRibbonRing(line, widthMeters)])
|
|
1148
|
+
};
|
|
1149
|
+
}
|
|
1150
|
+
return geometry;
|
|
1151
|
+
}
|
|
1152
|
+
var POLYGON_TYPES = /* @__PURE__ */ new Set(["Polygon", "MultiPolygon"]);
|
|
1153
|
+
function isPolygonFeature(feature) {
|
|
1154
|
+
if (!isRecord(feature)) return false;
|
|
1155
|
+
const geometry = feature.type === "Feature" ? feature.geometry : feature;
|
|
1156
|
+
return isRecord(geometry) && POLYGON_TYPES.has(String(geometry.type));
|
|
1157
|
+
}
|
|
1158
|
+
function polygonsOnly(geojson) {
|
|
1159
|
+
const features = isRecord(geojson) && geojson.type === "FeatureCollection" && Array.isArray(geojson.features) ? geojson.features : [geojson];
|
|
1160
|
+
return { type: "FeatureCollection", features: features.filter(isPolygonFeature) };
|
|
1161
|
+
}
|
|
1162
|
+
function ribbonizeLines(geojson, widthMeters) {
|
|
1163
|
+
if (!isRecord(geojson)) return geojson;
|
|
1164
|
+
if (geojson.type === "FeatureCollection" && Array.isArray(geojson.features)) {
|
|
1165
|
+
return { ...geojson, features: geojson.features.map((feature) => ribbonizeLines(feature, widthMeters)) };
|
|
1166
|
+
}
|
|
1167
|
+
if (geojson.type === "Feature") return { ...geojson, geometry: convertGeometry(geojson.geometry, widthMeters) };
|
|
1168
|
+
return convertGeometry(geojson, widthMeters);
|
|
1169
|
+
}
|
|
1170
|
+
function mapCoordinates(geojson, map) {
|
|
1171
|
+
if (!isRecord(geojson)) return geojson;
|
|
1172
|
+
if (geojson.type === "FeatureCollection" && Array.isArray(geojson.features)) {
|
|
1173
|
+
return { ...geojson, features: geojson.features.map((feature) => mapCoordinates(feature, map)) };
|
|
1174
|
+
}
|
|
1175
|
+
if (geojson.type === "Feature") return { ...geojson, geometry: mapCoordinates(geojson.geometry, map) };
|
|
1176
|
+
if (geojson.type === "GeometryCollection" && Array.isArray(geojson.geometries)) {
|
|
1177
|
+
return { ...geojson, geometries: geojson.geometries.map((geometry) => mapCoordinates(geometry, map)) };
|
|
1178
|
+
}
|
|
1179
|
+
const walk = (value) => Array.isArray(value) && typeof value[0] === "number" ? map(value) : Array.isArray(value) ? value.map(walk) : value;
|
|
1180
|
+
return "coordinates" in geojson ? { ...geojson, coordinates: walk(geojson.coordinates) } : geojson;
|
|
1181
|
+
}
|
|
1182
|
+
function hasMissingZ(geojson) {
|
|
1183
|
+
let missing = false;
|
|
1184
|
+
mapCoordinates(geojson, (coord) => {
|
|
1185
|
+
if (coord.length < 3 || typeof coord[2] !== "number" || !Number.isFinite(coord[2])) missing = true;
|
|
1186
|
+
return coord;
|
|
1187
|
+
});
|
|
1188
|
+
return missing;
|
|
1189
|
+
}
|
|
1190
|
+
function fillMissingZ(geojson, height) {
|
|
1191
|
+
return mapCoordinates(
|
|
1192
|
+
geojson,
|
|
1193
|
+
(coord) => coord.length >= 3 && Number.isFinite(coord[2]) ? coord : [coord[0] ?? 0, coord[1] ?? 0, height]
|
|
1194
|
+
);
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
// src/layers/riverWater.ts
|
|
1198
|
+
var DEFAULT_RIVER_WIDTH = 60;
|
|
1199
|
+
var RIVER_LINES_FIXED_IN = "4.0.2";
|
|
1200
|
+
var PIT_WATER_IN = "4.0.3";
|
|
1201
|
+
var usage = /* @__PURE__ */ new WeakMap();
|
|
1202
|
+
function systemsOf(render) {
|
|
1203
|
+
const candidate = render;
|
|
1204
|
+
if (typeof candidate.getSystem !== "function" || typeof candidate.enableSystem !== "function") {
|
|
1205
|
+
throw new SmartEarthError("RENDER_INIT_FAILED", "\u5F53\u524D sdk-render \u6CA1\u6709\u6CB3\u9053\u6C34\u9762\u7CFB\u7EDF\u63A5\u53E3\u3002");
|
|
1206
|
+
}
|
|
1207
|
+
return candidate;
|
|
1208
|
+
}
|
|
1209
|
+
function requireSystem(systems, name, methods) {
|
|
1210
|
+
const system = systems.getSystem(name);
|
|
1211
|
+
if (!system || methods.some((method) => typeof system[method] !== "function")) {
|
|
1212
|
+
throw new SmartEarthError("RENDER_INIT_FAILED", `\u5F53\u524D sdk-render \u7F3A\u5C11 ${name} \u7CFB\u7EDF\u7684\u516C\u5F00\u63A5\u53E3\u3002`);
|
|
1213
|
+
}
|
|
1214
|
+
return system;
|
|
1215
|
+
}
|
|
1216
|
+
var LINE_MODES = /* @__PURE__ */ new Set(["auto", "ribbon", "native"]);
|
|
1217
|
+
function validate4(spec) {
|
|
1218
|
+
requireLayerSpec(isRecord(spec.data) || typeof spec.data === "string", spec.id, "data \u9700\u8981\u6C34\u7CFB GeoJSON \u6216 URL\u3002");
|
|
1219
|
+
if (spec.dig !== void 0) {
|
|
1220
|
+
requireLayerSpec(isRecord(spec.dig) && typeof spec.dig.depth === "number" && spec.dig.depth > 0, spec.id, "dig.depth \u5FC5\u987B > 0\uFF08\u7C73\uFF09\u3002");
|
|
1221
|
+
const fill = spec.dig.fillWater;
|
|
1222
|
+
requireLayerSpec(fill === void 0 || typeof fill === "boolean" || isPitWaterOptions(fill), spec.id, "dig.fillWater \u53EA\u80FD\u662F\u5E03\u5C14\u503C\u6216 { freeboard?, minDepth?, spacingMeters? }\uFF08\u975E\u8D1F\u6570\u5B57\uFF09\u3002");
|
|
1223
|
+
}
|
|
1224
|
+
requireLayerSpec(spec.lift === void 0 || typeof spec.lift === "number" && Number.isFinite(spec.lift), spec.id, "lift \u5FC5\u987B\u662F\u6570\u5B57\uFF08\u7C73\uFF09\u3002");
|
|
1225
|
+
if (spec.config !== void 0) requireLayerSpec(isRecord(spec.config), spec.id, "config \u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
|
|
1226
|
+
requireLayerSpec(spec.width === void 0 || typeof spec.width === "number" && spec.width > 0, spec.id, "width \u5FC5\u987B > 0\uFF08\u7C73\uFF09\u3002");
|
|
1227
|
+
requireLayerSpec(spec.height === void 0 || typeof spec.height === "number" && Number.isFinite(spec.height), spec.id, "height \u5FC5\u987B\u662F\u6570\u5B57\uFF08\u7C73\uFF09\u3002");
|
|
1228
|
+
requireLayerSpec(spec.lineMode === void 0 || LINE_MODES.has(spec.lineMode), spec.id, "lineMode \u53EA\u80FD\u662F 'auto'\u3001'ribbon' \u6216 'native'\u3002");
|
|
1229
|
+
}
|
|
1230
|
+
function isPitWaterOptions(value) {
|
|
1231
|
+
if (!isRecord(value)) return false;
|
|
1232
|
+
return ["freeboard", "minDepth", "spacingMeters"].every((key) => {
|
|
1233
|
+
const field = value[key];
|
|
1234
|
+
return field === void 0 || typeof field === "number" && Number.isFinite(field) && field >= 0;
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
function pitWaterSupported(sdkRenderVersion) {
|
|
1238
|
+
return typeof sdkRenderVersion === "string" && compareVersions(sdkRenderVersion, PIT_WATER_IN) >= 0;
|
|
1239
|
+
}
|
|
1240
|
+
function riverLinesFixed(sdkRenderVersion) {
|
|
1241
|
+
return typeof sdkRenderVersion === "string" && compareVersions(sdkRenderVersion, RIVER_LINES_FIXED_IN) >= 0;
|
|
1242
|
+
}
|
|
1243
|
+
function placeWater(raw, spec, canPlaceOnTerrain, sdkHasHeight) {
|
|
1244
|
+
if (spec.dig?.fillWater) return { data: raw, placement: "pit" };
|
|
1245
|
+
if (!hasMissingZ(raw)) return { data: raw, placement: "data" };
|
|
1246
|
+
if (spec.height === void 0 && sdkHasHeight?.(raw) === true) return { data: raw, placement: "data" };
|
|
1247
|
+
if (spec.height !== void 0) return { data: fillMissingZ(raw, spec.height), placement: "data" };
|
|
1248
|
+
if (canPlaceOnTerrain) return { data: raw, placement: "terrain" };
|
|
1249
|
+
throw new SmartEarthError(
|
|
1250
|
+
"INVALID_OPTIONS",
|
|
1251
|
+
`\u6CB3\u9053\u56FE\u5C42 ${spec.id}\uFF1A\u6C34\u7CFB\u5750\u6807\u6CA1\u6709\u9AD8\u7A0B\uFF08Z\uFF09\uFF0C\u6C34\u9762\u4F1A\u843D\u5728 0 \u7C73\u3002\u7ED9\u5750\u6807\u52A0\u4E0A Z\uFF0C\u6216\u8BBE\u7F6E height\uFF08\u6C34\u9762\u9AD8\u7A0B\uFF0C\u7C73\uFF09\uFF1Bsdk-render 4.0.3 \u8D77\u4F1A\u81EA\u52A8\u8D34\u5730\u5F62\u3002`
|
|
1252
|
+
);
|
|
1253
|
+
}
|
|
1254
|
+
async function digTerrain(water, geojson, depth, showViz, layerId) {
|
|
1255
|
+
try {
|
|
1256
|
+
const areas = await water.loadTerrainAdjustFromGeoJSON(geojson);
|
|
1257
|
+
if (areas === 0) throw new Error("\u6CA1\u6709\u53EF\u6316\u7684\u9762\u8981\u7D20");
|
|
1258
|
+
await water.applyTerrainAdjust(-depth);
|
|
1259
|
+
water.setAppliedVizVisible?.(showViz);
|
|
1260
|
+
} catch (error) {
|
|
1261
|
+
water.clearAllTerrainAdjust();
|
|
1262
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u6CB3\u9053\u56FE\u5C42 ${layerId} \u5730\u5F62\u6316\u5751\u5931\u8D25\uFF1A${describeLayerCause(error)}`);
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
async function loadSurface(river, data, spec, width, placement) {
|
|
1266
|
+
if (placement === "terrain") {
|
|
1267
|
+
if (typeof river.loadFromGeoJsonOnTerrain !== "function") {
|
|
1268
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u6CB3\u9053\u56FE\u5C42 ${spec.id}\uFF1A\u5F53\u524D sdk-render \u6CA1\u6709\u8D34\u5730\u653E\u6C34\u63A5\u53E3\u3002`);
|
|
1269
|
+
}
|
|
1270
|
+
return river.loadFromGeoJsonOnTerrain(data, { namePrefix: spec.id, width, ...spec.lift !== void 0 ? { lift: spec.lift } : {} });
|
|
1271
|
+
}
|
|
1272
|
+
return river.loadFromGeoJson(data, {
|
|
1273
|
+
namePrefix: spec.id,
|
|
1274
|
+
width,
|
|
1275
|
+
...spec.offsetHeight !== void 0 ? { offsetHeight: spec.offsetHeight } : {},
|
|
1276
|
+
...spec.thickness !== void 0 ? { thickness: spec.thickness } : {}
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
async function fillPits(river, terrain, spec) {
|
|
1280
|
+
const fill = spec.dig?.fillWater;
|
|
1281
|
+
const options = typeof fill === "object" ? fill : {};
|
|
1282
|
+
if (typeof river.loadWaterFromTerrainAdjust !== "function" || typeof terrain.getTerrainAdjustAreas !== "function" || typeof terrain.getOriginalTerrainProvider !== "function") {
|
|
1283
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u6CB3\u9053\u56FE\u5C42 ${spec.id}\uFF1A\u5F53\u524D sdk-render \u6CA1\u6709\u6309\u5751\u52A0\u6C34\u63A5\u53E3\u3002`);
|
|
1284
|
+
}
|
|
1285
|
+
try {
|
|
1286
|
+
const layers = await river.loadWaterFromTerrainAdjust(terrain.getTerrainAdjustAreas(), {
|
|
1287
|
+
terrainProvider: terrain.getOriginalTerrainProvider(),
|
|
1288
|
+
namePrefix: spec.id,
|
|
1289
|
+
...options
|
|
1290
|
+
});
|
|
1291
|
+
if (layers.length === 0) throw new Error("\u6CA1\u6709\u751F\u6210\u6C34\u9762\uFF08\u5751\u7684\u504F\u79FB\u8981\u4E3A\u8D1F\u503C\uFF09");
|
|
1292
|
+
return layers;
|
|
1293
|
+
} catch (error) {
|
|
1294
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u6CB3\u9053\u56FE\u5C42 ${spec.id} \u6309\u5751\u52A0\u6C34\u5931\u8D25\uFF1A${describeLayerCause(error)}`);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
function prepareData(raw, spec, fixed) {
|
|
1298
|
+
const width = spec.width ?? DEFAULT_RIVER_WIDTH;
|
|
1299
|
+
const requested = spec.lineMode ?? "auto";
|
|
1300
|
+
const lineMode = requested === "auto" ? fixed ? "native" : "ribbon" : requested;
|
|
1301
|
+
const water = lineMode === "ribbon" ? ribbonizeLines(raw, width) : raw;
|
|
1302
|
+
const dig = fixed ? polygonsOnly(ribbonizeLines(raw, width)) : polygonsOnly(raw);
|
|
1303
|
+
return { width, lineMode, water, dig };
|
|
1304
|
+
}
|
|
1305
|
+
var riverWaterLayerFactory = async (context, spec) => {
|
|
1306
|
+
validate4(spec);
|
|
1307
|
+
const systems = systemsOf(context.render);
|
|
1308
|
+
const river = requireSystem(systems, "riverWater", ["update", "loadFromGeoJson", "removeLayer", "setLayerVisible"]);
|
|
1309
|
+
const pitSupported = pitWaterSupported(context.sdkRenderVersion);
|
|
1310
|
+
if (spec.dig?.fillWater && !pitSupported) {
|
|
1311
|
+
throw new SmartEarthError("INVALID_OPTIONS", `\u6CB3\u9053\u56FE\u5C42 ${spec.id}\uFF1A\u6309\u5751\u52A0\u6C34\uFF08dig.fillWater\uFF09\u9700\u8981 sdk-render ${PIT_WATER_IN} \u4EE5\u4E0A\u3002`);
|
|
1312
|
+
}
|
|
1313
|
+
const sdkHasHeight = pitSupported && typeof river.hasHeightInfo === "function" ? (geojson) => river.hasHeightInfo(geojson) : void 0;
|
|
1314
|
+
const placed = placeWater(await loadJson(spec.data, spec.id), spec, pitSupported, sdkHasHeight);
|
|
1315
|
+
const fixed = riverLinesFixed(context.sdkRenderVersion);
|
|
1316
|
+
const { width, lineMode, water: waterData, dig: digData } = prepareData(placed.data, spec, fixed);
|
|
1317
|
+
if (spec.dig && digData.features.length === 0) {
|
|
1318
|
+
const what = fixed ? "\u6570\u636E\u91CC\u6CA1\u6709\u6CB3\u9053\u7EBF\u6216\u9762\u8981\u7D20" : "\u5F53\u524D sdk-render \u53EA\u6316\u6E56\u3001\u5E93\u7B49\u9762\u8981\u7D20\uFF0C\u6570\u636E\u91CC\u6CA1\u6709 Polygon";
|
|
1319
|
+
throw new SmartEarthError("INVALID_OPTIONS", `\u6CB3\u9053\u56FE\u5C42 ${spec.id}\uFF1Adig ${what}\u3002`);
|
|
1320
|
+
}
|
|
1321
|
+
const state = usage.get(context.render) ?? { count: 0, enabledByUs: false };
|
|
1322
|
+
usage.set(context.render, state);
|
|
1323
|
+
if (spec.dig) {
|
|
1324
|
+
if (state.digOwner) {
|
|
1325
|
+
throw new SmartEarthError("INVALID_OPTIONS", `\u5730\u5F62\u6316\u5751\u662F\u5168\u5C40\u7684\uFF0C\u5DF2\u88AB\u56FE\u5C42 ${state.digOwner} \u5360\u7528\uFF1B\u5148\u79FB\u9664\u5B83\u518D\u52A0 ${spec.id}\u3002`);
|
|
1326
|
+
}
|
|
1327
|
+
state.digOwner = spec.id;
|
|
1328
|
+
}
|
|
1329
|
+
if (!systems.getSystemStatus("riverWater")) {
|
|
1330
|
+
systems.enableSystem("riverWater");
|
|
1331
|
+
state.enabledByUs = true;
|
|
1332
|
+
}
|
|
1333
|
+
state.count += 1;
|
|
1334
|
+
let terrain;
|
|
1335
|
+
let layerIds = [];
|
|
1336
|
+
const release = () => {
|
|
1337
|
+
for (const id of layerIds) river.removeLayer(id);
|
|
1338
|
+
if (terrain) terrain.clearAllTerrainAdjust();
|
|
1339
|
+
if (state.digOwner === spec.id) state.digOwner = void 0;
|
|
1340
|
+
state.count -= 1;
|
|
1341
|
+
if (state.count === 0 && state.enabledByUs) {
|
|
1342
|
+
systems.disableSystem("riverWater");
|
|
1343
|
+
state.enabledByUs = false;
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
try {
|
|
1347
|
+
if (spec.config) river.update(spec.config);
|
|
1348
|
+
if (placed.placement !== "pit") {
|
|
1349
|
+
const layers = await loadSurface(river, waterData, spec, width, placed.placement);
|
|
1350
|
+
layerIds = layers.map((layer) => layer.id);
|
|
1351
|
+
}
|
|
1352
|
+
if (spec.dig) {
|
|
1353
|
+
terrain = requireSystem(systems, "water", ["loadTerrainAdjustFromGeoJSON", "applyTerrainAdjust", "clearAllTerrainAdjust"]);
|
|
1354
|
+
await digTerrain(terrain, digData, spec.dig.depth, spec.showDigViz ?? false, spec.id);
|
|
1355
|
+
if (placed.placement === "pit") {
|
|
1356
|
+
const pit = await fillPits(river, terrain, spec);
|
|
1357
|
+
layerIds = pit.map((layer) => layer.id);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
} catch (error) {
|
|
1361
|
+
release();
|
|
1362
|
+
if (error instanceof SmartEarthError) throw error;
|
|
1363
|
+
throw new SmartEarthError("LAYER_LOAD_FAILED", `\u6CB3\u9053\u56FE\u5C42 ${spec.id} \u52A0\u8F7D\u5931\u8D25\uFF1A${describeLayerCause(error)}`);
|
|
1364
|
+
}
|
|
1365
|
+
const api = {
|
|
1366
|
+
get layerIds() {
|
|
1367
|
+
return [...layerIds];
|
|
1368
|
+
},
|
|
1369
|
+
lineMode,
|
|
1370
|
+
placement: placed.placement,
|
|
1371
|
+
update(config) {
|
|
1372
|
+
if (!isRecord(config)) throw new SmartEarthError("INVALID_OPTIONS", "update \u9700\u8981\u914D\u7F6E\u5BF9\u8C61\u3002");
|
|
1373
|
+
river.update(config);
|
|
1374
|
+
}
|
|
1375
|
+
};
|
|
1376
|
+
return {
|
|
1377
|
+
api,
|
|
1378
|
+
setVisible(visible) {
|
|
1379
|
+
for (const id of layerIds) river.setLayerVisible(id, visible);
|
|
1380
|
+
context.viewer.scene.requestRender();
|
|
1381
|
+
},
|
|
1382
|
+
destroy: release
|
|
1383
|
+
};
|
|
1384
|
+
};
|
|
1385
|
+
|
|
1386
|
+
// src/environment/panel.ts
|
|
1387
|
+
var PANEL_EDIT_DEBOUNCE_MS = 300;
|
|
1388
|
+
function panelElementOf(control) {
|
|
1389
|
+
const own = control.panelContainer;
|
|
1390
|
+
return own instanceof HTMLElement ? own : null;
|
|
1391
|
+
}
|
|
1392
|
+
function isShown(control, fallback) {
|
|
1393
|
+
const element = control ? panelElementOf(control) : null;
|
|
1394
|
+
if (!element || typeof getComputedStyle !== "function") return fallback;
|
|
1395
|
+
return element.isConnected && getComputedStyle(element).display !== "none";
|
|
1396
|
+
}
|
|
1397
|
+
function createPanelController(render, EnvironmentControl2, onEdit) {
|
|
1398
|
+
let control;
|
|
1399
|
+
let editTimer;
|
|
1400
|
+
const handleEdit = () => {
|
|
1401
|
+
if (!onEdit) return;
|
|
1402
|
+
clearTimeout(editTimer);
|
|
1403
|
+
editTimer = setTimeout(() => {
|
|
1404
|
+
editTimer = void 0;
|
|
1405
|
+
if (!destroyed) onEdit();
|
|
1406
|
+
}, PANEL_EDIT_DEBOUNCE_MS);
|
|
1407
|
+
};
|
|
1408
|
+
let pending;
|
|
1409
|
+
let requested = false;
|
|
1410
|
+
let destroyed = false;
|
|
1411
|
+
const ensure = async () => {
|
|
1412
|
+
if (control) return control;
|
|
1413
|
+
if (!EnvironmentControl2) {
|
|
1414
|
+
throw new SmartEarthError("ENVIRONMENT_UNSUPPORTED", "\u5F53\u524D @metagl/sdk-render \u6CA1\u6709\u73AF\u5883\u63A7\u5236\u9762\u677F\uFF08\u9700\u8981 4.x\uFF09\u3002");
|
|
1415
|
+
}
|
|
1416
|
+
pending ??= EnvironmentControl2.create({ render });
|
|
1417
|
+
let created;
|
|
1418
|
+
try {
|
|
1419
|
+
created = await pending;
|
|
1420
|
+
} catch (error) {
|
|
1421
|
+
pending = void 0;
|
|
1422
|
+
if (destroyed) throw new SmartEarthError("DESTROYED", "\u5730\u7403\u5DF2\u9500\u6BC1\u3002");
|
|
1423
|
+
throw new SmartEarthError("RENDER_INIT_FAILED", `\u73AF\u5883\u63A7\u5236\u9762\u677F\u521B\u5EFA\u5931\u8D25\uFF1A${describeCause(error)}`, error);
|
|
1424
|
+
}
|
|
1425
|
+
if (destroyed) {
|
|
1426
|
+
panelElementOf(created)?.remove();
|
|
1427
|
+
throw new SmartEarthError("DESTROYED", "\u5730\u7403\u5DF2\u9500\u6BC1\u3002");
|
|
1428
|
+
}
|
|
1429
|
+
control = created;
|
|
1430
|
+
const element = panelElementOf(created);
|
|
1431
|
+
element?.addEventListener("input", handleEdit);
|
|
1432
|
+
element?.addEventListener("change", handleEdit);
|
|
1433
|
+
return created;
|
|
1434
|
+
};
|
|
1435
|
+
return {
|
|
1436
|
+
async show(next) {
|
|
1437
|
+
requested = next;
|
|
1438
|
+
if (!next && !control && !pending) return;
|
|
1439
|
+
const panel = await ensure();
|
|
1440
|
+
panel.togglePanel(requested);
|
|
1441
|
+
},
|
|
1442
|
+
get visible() {
|
|
1443
|
+
return isShown(control, requested);
|
|
1444
|
+
},
|
|
1445
|
+
destroy() {
|
|
1446
|
+
destroyed = true;
|
|
1447
|
+
clearTimeout(editTimer);
|
|
1448
|
+
if (control) panelElementOf(control)?.remove();
|
|
1449
|
+
control = void 0;
|
|
1450
|
+
requested = false;
|
|
1451
|
+
}
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
// src/core/capture.ts
|
|
1456
|
+
var DEFAULT_MAX_WIDTH = 480;
|
|
1457
|
+
var JPEG_QUALITY = 0.85;
|
|
1458
|
+
function captureImage(viewer, maxWidth = DEFAULT_MAX_WIDTH) {
|
|
1459
|
+
if (!Number.isFinite(maxWidth) || maxWidth <= 0) {
|
|
1460
|
+
return Promise.reject(new SmartEarthError("INVALID_OPTIONS", "maxWidth \u8981\u662F\u6B63\u6570\uFF08\u50CF\u7D20\uFF09\u3002"));
|
|
1461
|
+
}
|
|
1462
|
+
return new Promise((resolve, reject) => {
|
|
1463
|
+
const scene = viewer.scene;
|
|
1464
|
+
const remove = scene.postRender.addEventListener(() => {
|
|
1465
|
+
remove();
|
|
1466
|
+
try {
|
|
1467
|
+
const source = scene.canvas;
|
|
1468
|
+
const scale = Math.min(1, maxWidth / Math.max(1, source.width));
|
|
1469
|
+
const target = document.createElement("canvas");
|
|
1470
|
+
target.width = Math.max(1, Math.round(source.width * scale));
|
|
1471
|
+
target.height = Math.max(1, Math.round(source.height * scale));
|
|
1472
|
+
target.getContext("2d")?.drawImage(source, 0, 0, target.width, target.height);
|
|
1473
|
+
const dataUrl = target.toDataURL("image/jpeg", JPEG_QUALITY);
|
|
1474
|
+
if (!dataUrl.startsWith("data:image/jpeg")) throw new Error("\u753B\u5E03\u8F93\u51FA\u65E0\u6548");
|
|
1475
|
+
resolve(dataUrl);
|
|
1476
|
+
} catch (error) {
|
|
1477
|
+
reject(new SmartEarthError("RENDER_INIT_FAILED", `\u622A\u56FE\u5931\u8D25\uFF1A${describeCause(error)}`, error));
|
|
1478
|
+
}
|
|
1479
|
+
});
|
|
1480
|
+
scene.requestRender();
|
|
1481
|
+
});
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
// src/core/assets.ts
|
|
1485
|
+
var CESIUM_PROBE = "Assets/approximateTerrainHeights.json";
|
|
1486
|
+
var SDK_RENDER_PROBE = "resources/readme.txt";
|
|
1487
|
+
function readCesiumBaseUrl() {
|
|
1488
|
+
const fromDefine = typeof CESIUM_BASE_URL === "string" ? CESIUM_BASE_URL : void 0;
|
|
1489
|
+
return fromDefine ?? cesiumGlobals().CESIUM_BASE_URL;
|
|
1490
|
+
}
|
|
1491
|
+
function joinUrl(base, path) {
|
|
1492
|
+
return `${base.endsWith("/") ? base : `${base}/`}${path}`;
|
|
1493
|
+
}
|
|
1494
|
+
async function probe(url, fetchImpl) {
|
|
1495
|
+
try {
|
|
1496
|
+
const response = await fetchImpl(url, { method: "GET", cache: "no-store" });
|
|
1497
|
+
if (!response.ok) return false;
|
|
1498
|
+
const type = response.headers.get("content-type") ?? "";
|
|
1499
|
+
return !type.includes("text/html");
|
|
1500
|
+
} catch {
|
|
1501
|
+
return false;
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
var HINT = "\u5728 vite.config \u91CC\u52A0\u4E0A smartEarthAssets()\uFF08@metagl/smartearth-base/vite\uFF09\uFF0C\u6216\u81EA\u884C\u628A\u8D44\u6E90\u62F7\u5230\u7AD9\u70B9\u3002";
|
|
1505
|
+
async function assertAssetsAvailable(assetsBasePath, fetchImpl = fetch) {
|
|
1506
|
+
const cesiumBase = readCesiumBaseUrl();
|
|
1507
|
+
if (!cesiumBase) {
|
|
1508
|
+
throw new SmartEarthError("ASSETS_MISSING", `\u672A\u8BBE\u7F6E CESIUM_BASE_URL\u3002${HINT}`);
|
|
1509
|
+
}
|
|
1510
|
+
const [cesiumOk, sdkOk] = await Promise.all([
|
|
1511
|
+
probe(joinUrl(cesiumBase, CESIUM_PROBE), fetchImpl),
|
|
1512
|
+
probe(joinUrl(assetsBasePath, SDK_RENDER_PROBE), fetchImpl)
|
|
1513
|
+
]);
|
|
1514
|
+
const missing = [
|
|
1515
|
+
...cesiumOk ? [] : [`Cesium \u8D44\u6E90\uFF08${cesiumBase}\uFF09`],
|
|
1516
|
+
...sdkOk ? [] : [`sdk-render \u8D44\u6E90\uFF08${assetsBasePath}resources/\uFF09`]
|
|
1517
|
+
];
|
|
1518
|
+
if (missing.length > 0) {
|
|
1519
|
+
throw new SmartEarthError("ASSETS_MISSING", `\u9759\u6001\u8D44\u6E90\u7F3A\u5931\uFF1A${missing.join("\u3001")}\u3002${HINT}`);
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
// src/core/basemap.ts
|
|
1524
|
+
var GEOVIS_MAX_LEVEL = 18;
|
|
1525
|
+
var GEOVIS_IMAGERY_URL = "https://tiles{s}.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&tmsIds=w&token=";
|
|
1526
|
+
var GEOVIS_ANNOTATION_URL = "https://tiles.geovisearth.com/base/v1/cia/{z}/{x}/{y}?format=webp&tmsIds=w&token=";
|
|
1527
|
+
var GEOVIS_TERRAIN_URL = "https://tiles.geovisearth.com/base/v1/terrain?token=";
|
|
1528
|
+
function addBasemap(Cesium, viewer, options) {
|
|
1529
|
+
const token = encodeURIComponent(options.geovisToken);
|
|
1530
|
+
const basemap = options.basemap;
|
|
1531
|
+
const layers = basemap === "geovis" ? [
|
|
1532
|
+
{ url: `${GEOVIS_IMAGERY_URL}${token}`, subdomains: ["1", "2", "3"], maximumLevel: GEOVIS_MAX_LEVEL },
|
|
1533
|
+
{ url: `${GEOVIS_ANNOTATION_URL}${token}`, maximumLevel: GEOVIS_MAX_LEVEL }
|
|
1534
|
+
] : [
|
|
1535
|
+
{
|
|
1536
|
+
url: basemap.imageryUrl,
|
|
1537
|
+
subdomains: basemap.subdomains ? [...basemap.subdomains] : void 0,
|
|
1538
|
+
maximumLevel: basemap.maximumLevel
|
|
1539
|
+
},
|
|
1540
|
+
...basemap.annotationUrl ? [{ url: basemap.annotationUrl, maximumLevel: basemap.maximumLevel }] : []
|
|
1541
|
+
];
|
|
1542
|
+
for (const layer of layers) {
|
|
1543
|
+
viewer.imageryLayers.addImageryProvider(
|
|
1544
|
+
new Cesium.UrlTemplateImageryProvider({
|
|
1545
|
+
url: layer.url,
|
|
1546
|
+
...layer.subdomains ? { subdomains: layer.subdomains } : {},
|
|
1547
|
+
...layer.maximumLevel !== void 0 ? { maximumLevel: layer.maximumLevel } : {}
|
|
1548
|
+
})
|
|
1549
|
+
);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
async function addTerrain(Cesium, viewer, options) {
|
|
1553
|
+
if (!options.terrain) return;
|
|
1554
|
+
try {
|
|
1555
|
+
viewer.terrainProvider = await Cesium.CesiumTerrainProvider.fromUrl(
|
|
1556
|
+
`${GEOVIS_TERRAIN_URL}${encodeURIComponent(options.geovisToken)}`,
|
|
1557
|
+
{ requestWaterMask: false, requestVertexNormals: true }
|
|
1558
|
+
);
|
|
1559
|
+
} catch (error) {
|
|
1560
|
+
throw new SmartEarthError(
|
|
1561
|
+
"AUTH_FAILED",
|
|
1562
|
+
`\u661F\u56FE\u5730\u5F62\u52A0\u8F7D\u5931\u8D25\uFF0C\u5730\u56FE\u4EE4\u724C\u53EF\u80FD\u65E0\u6548\u6216\u7F51\u7EDC\u4E0D\u901A\uFF1A${describeCause(error)}`,
|
|
1563
|
+
error
|
|
1564
|
+
);
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
// src/core/options.ts
|
|
1569
|
+
var DEFAULT_INITIAL_VIEW = {
|
|
1570
|
+
lon: 109,
|
|
1571
|
+
lat: 36,
|
|
1572
|
+
height: 12e6,
|
|
1573
|
+
heading: 0,
|
|
1574
|
+
pitch: -90
|
|
1575
|
+
};
|
|
1576
|
+
var QUALITIES = ["high", "medium", "low"];
|
|
1577
|
+
function isNonEmptyString(value) {
|
|
1578
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
1579
|
+
}
|
|
1580
|
+
function isRecord3(value) {
|
|
1581
|
+
return typeof value === "object" && value !== null;
|
|
1582
|
+
}
|
|
1583
|
+
function resolveAuth(auth) {
|
|
1584
|
+
if (isRecord3(auth)) {
|
|
1585
|
+
if (isNonEmptyString(auth.sdkToken)) return { token: auth.sdkToken.trim() };
|
|
1586
|
+
const licence = auth.licence;
|
|
1587
|
+
if (isRecord3(licence) && isNonEmptyString(licence.lic) && isNonEmptyString(licence.rsaPubKey)) {
|
|
1588
|
+
return { lic: licence.lic.trim(), rsaPubKey: licence.rsaPubKey.trim() };
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
throw new SmartEarthError(
|
|
1592
|
+
"AUTH_MISSING_SDK",
|
|
1593
|
+
"\u7F3A\u5C11 SmartEarth SDK \u6388\u6743\uFF1Aauth \u9700\u63D0\u4F9B sdkToken\uFF0C\u6216 licence.lic \u4E0E licence.rsaPubKey \u4E24\u9879\u3002"
|
|
1594
|
+
);
|
|
1595
|
+
}
|
|
1596
|
+
function resolveBasemap(basemap) {
|
|
1597
|
+
if (basemap === void 0 || basemap === "geovis") return "geovis";
|
|
1598
|
+
if (isRecord3(basemap) && isNonEmptyString(basemap.imageryUrl)) {
|
|
1599
|
+
if (basemap.annotationUrl !== void 0 && !isNonEmptyString(basemap.annotationUrl)) {
|
|
1600
|
+
throw new SmartEarthError("INVALID_OPTIONS", "basemap.annotationUrl \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002");
|
|
1601
|
+
}
|
|
1602
|
+
return basemap;
|
|
1603
|
+
}
|
|
1604
|
+
throw new SmartEarthError(
|
|
1605
|
+
"INVALID_OPTIONS",
|
|
1606
|
+
"basemap \u53EA\u80FD\u662F 'geovis' \u6216 { imageryUrl, annotationUrl? }\u3002"
|
|
1607
|
+
);
|
|
1608
|
+
}
|
|
1609
|
+
function resolveInitialView(view) {
|
|
1610
|
+
if (view === void 0) return DEFAULT_INITIAL_VIEW;
|
|
1611
|
+
if (!isRecord3(view)) throw new SmartEarthError("INVALID_OPTIONS", "initialView \u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
|
|
1612
|
+
const { lon, lat, height } = view;
|
|
1613
|
+
const ok = typeof lon === "number" && lon >= -180 && lon <= 180 && typeof lat === "number" && lat >= -90 && lat <= 90 && typeof height === "number" && height > 0;
|
|
1614
|
+
if (!ok) {
|
|
1615
|
+
throw new SmartEarthError(
|
|
1616
|
+
"INVALID_OPTIONS",
|
|
1617
|
+
"initialView \u9700\u8981 lon\uFF08-180~180\uFF09\u3001lat\uFF08-90~90\uFF09\u3001height\uFF08>0\uFF0C\u7C73\uFF09\u3002"
|
|
1618
|
+
);
|
|
1619
|
+
}
|
|
1620
|
+
return {
|
|
1621
|
+
lon,
|
|
1622
|
+
lat,
|
|
1623
|
+
height,
|
|
1624
|
+
heading: typeof view.heading === "number" ? view.heading : DEFAULT_INITIAL_VIEW.heading,
|
|
1625
|
+
pitch: typeof view.pitch === "number" ? view.pitch : DEFAULT_INITIAL_VIEW.pitch
|
|
1626
|
+
};
|
|
1627
|
+
}
|
|
1628
|
+
var BASELINES = ["environment", "cinematic"];
|
|
1629
|
+
function resolveEffects(effects) {
|
|
1630
|
+
if (effects === void 0) return {};
|
|
1631
|
+
const ok = isRecord3(effects) && !Array.isArray(effects) && Object.values(effects).every((v) => typeof v === "boolean");
|
|
1632
|
+
if (!ok) throw new SmartEarthError("INVALID_OPTIONS", "effects \u8981\u5199\u6210 { \u6548\u679C\u540D: true/false }\u3002");
|
|
1633
|
+
const unknown = Object.keys(effects).filter((name) => !ALL_EFFECTS.includes(name));
|
|
1634
|
+
if (unknown.length > 0) {
|
|
1635
|
+
throw new SmartEarthError("INVALID_OPTIONS", `effects \u91CC\u6CA1\u6709\u8FD9\u4E9B\u6548\u679C\uFF1A${unknown.join("\u3001")}\uFF1B\u53EF\u9009 ${ALL_EFFECTS.join("\u3001")}\u3002`);
|
|
1636
|
+
}
|
|
1637
|
+
return { ...effects };
|
|
1638
|
+
}
|
|
1639
|
+
function resolveEnvironmentOptions(options, assetsBasePath) {
|
|
1640
|
+
const baseline = options.baseline ?? "environment";
|
|
1641
|
+
if (!BASELINES.includes(baseline)) {
|
|
1642
|
+
throw new SmartEarthError("INVALID_OPTIONS", `baseline \u53EA\u80FD\u662F ${BASELINES.join(" / ")}\u3002`);
|
|
1643
|
+
}
|
|
1644
|
+
const showPanel = options.showPanel ?? false;
|
|
1645
|
+
if (typeof showPanel !== "boolean") throw new SmartEarthError("INVALID_OPTIONS", "showPanel \u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");
|
|
1646
|
+
const preset = options.presetFile;
|
|
1647
|
+
if (preset !== void 0 && preset !== false && (typeof preset !== "string" || preset.trim() === "")) {
|
|
1648
|
+
throw new SmartEarthError("INVALID_OPTIONS", "presetFile \u8981\u662F false \u6216\u9884\u8BBE\u6587\u4EF6\u5730\u5740\u3002");
|
|
1649
|
+
}
|
|
1650
|
+
const presetFile = preset === false ? null : preset ?? `${assetsBasePath}environment/preset.json`;
|
|
1651
|
+
return { baseline, effects: resolveEffects(options.effects), showPanel, presetFile };
|
|
1652
|
+
}
|
|
1653
|
+
function normalizeAssetsBasePath(path) {
|
|
1654
|
+
return path.endsWith("/") ? path : `${path}/`;
|
|
1655
|
+
}
|
|
1656
|
+
function resolveOptions(options) {
|
|
1657
|
+
if (!isRecord3(options)) {
|
|
1658
|
+
throw new SmartEarthError("INVALID_OPTIONS", "createEarth \u9700\u8981\u4F20\u5165\u53C2\u6570\u5BF9\u8C61\u3002");
|
|
1659
|
+
}
|
|
1660
|
+
const auth = resolveAuth(options.auth);
|
|
1661
|
+
const basemap = resolveBasemap(options.basemap);
|
|
1662
|
+
const terrain = options.terrain ?? true;
|
|
1663
|
+
if (typeof terrain !== "boolean") {
|
|
1664
|
+
throw new SmartEarthError("INVALID_OPTIONS", "terrain \u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");
|
|
1665
|
+
}
|
|
1666
|
+
const geovisToken = isNonEmptyString(options.geovisToken) ? options.geovisToken.trim() : "";
|
|
1667
|
+
if (!geovisToken && (basemap === "geovis" || terrain)) {
|
|
1668
|
+
throw new SmartEarthError(
|
|
1669
|
+
"AUTH_MISSING_MAP",
|
|
1670
|
+
`\u7F3A\u5C11\u661F\u56FE\u5730\u56FE\u4EE4\u724C geovisToken\uFF08\u661F\u56FE\u5E95\u56FE\u4E0E\u5730\u5F62\u90FD\u8981\u7528\uFF09\u3002\u8BF7\u5230 ${MAP_TOKEN_APPLY_URL} \u7533\u8BF7\u540E\u4F20\u5165\u3002`
|
|
1671
|
+
);
|
|
1672
|
+
}
|
|
1673
|
+
const quality = options.quality ?? "high";
|
|
1674
|
+
if (!QUALITIES.includes(quality)) {
|
|
1675
|
+
throw new SmartEarthError("INVALID_OPTIONS", `quality \u53EA\u80FD\u662F ${QUALITIES.join(" / ")}\u3002`);
|
|
1676
|
+
}
|
|
1677
|
+
const assetsBasePath = options.assetsBasePath ?? "/";
|
|
1678
|
+
if (typeof assetsBasePath !== "string" || assetsBasePath.length === 0) {
|
|
1679
|
+
throw new SmartEarthError("INVALID_OPTIONS", "assetsBasePath \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002");
|
|
1680
|
+
}
|
|
1681
|
+
return {
|
|
1682
|
+
auth,
|
|
1683
|
+
geovisToken,
|
|
1684
|
+
basemap,
|
|
1685
|
+
terrain,
|
|
1686
|
+
quality,
|
|
1687
|
+
assetsBasePath: normalizeAssetsBasePath(assetsBasePath),
|
|
1688
|
+
initialView: resolveInitialView(options.initialView),
|
|
1689
|
+
checkAssets: options.checkAssets ?? true,
|
|
1690
|
+
...resolveEnvironmentOptions(options, normalizeAssetsBasePath(assetsBasePath))
|
|
1691
|
+
};
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
// src/core/renderStateCompat.ts
|
|
1695
|
+
var installed = /* @__PURE__ */ new WeakSet();
|
|
1696
|
+
function installRenderStateCompatibility(Cesium) {
|
|
1697
|
+
const renderState = Cesium.RenderState;
|
|
1698
|
+
if (!renderState || installed.has(renderState)) return;
|
|
1699
|
+
const originalFromCache = renderState.fromCache.bind(renderState);
|
|
1700
|
+
renderState.fromCache = (options) => {
|
|
1701
|
+
if (!options || options.lineWidth === void 0 || options.lineWidth === 1) {
|
|
1702
|
+
return originalFromCache(options);
|
|
1703
|
+
}
|
|
1704
|
+
return originalFromCache({ ...options, lineWidth: 1 });
|
|
1705
|
+
};
|
|
1706
|
+
installed.add(renderState);
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
// src/core/createEarth.ts
|
|
1710
|
+
var DEFAULT_FLY_DURATION = 1.5;
|
|
1711
|
+
function getSupportedQualities() {
|
|
1712
|
+
const prototype = SdkRender.Render?.prototype;
|
|
1713
|
+
return qualitiesFor(prototype, SdkRender.DEMO_ENVIRONMENT_BASELINE);
|
|
1714
|
+
}
|
|
1715
|
+
async function resetToBaseline(render, quality) {
|
|
1716
|
+
const capable = render;
|
|
1717
|
+
if (typeof capable.loadConfig !== "function" || SdkRender.DEMO_ENVIRONMENT_BASELINE === void 0) {
|
|
1718
|
+
throw new SmartEarthError("ENVIRONMENT_UNSUPPORTED", "\u5F53\u524D @metagl/sdk-render \u4E0D\u652F\u6301\u91CD\u7F6E\u73AF\u5883\u914D\u7F6E\uFF08\u9700\u8981 4.x\uFF09\u3002");
|
|
1719
|
+
}
|
|
1720
|
+
try {
|
|
1721
|
+
const baseline = buildHighConfig(SdkRender.DEMO_ENVIRONMENT_BASELINE);
|
|
1722
|
+
await capable.loadConfig(baseline);
|
|
1723
|
+
syncEnabledFlags(render, baseline);
|
|
1724
|
+
if (typeof capable.setQuality === "function") {
|
|
1725
|
+
await capable.setQuality("high");
|
|
1726
|
+
if (quality !== "high") await capable.setQuality(quality);
|
|
1727
|
+
} else if (quality !== "high") {
|
|
1728
|
+
await applyQuality(capable, quality, SdkRender.DEMO_ENVIRONMENT_BASELINE);
|
|
1729
|
+
}
|
|
1730
|
+
} catch (error) {
|
|
1731
|
+
try {
|
|
1732
|
+
if (typeof capable.setQuality === "function") await capable.setQuality(quality);
|
|
1733
|
+
} catch {
|
|
1734
|
+
}
|
|
1735
|
+
throw new SmartEarthError("RENDER_INIT_FAILED", `\u91CD\u7F6E\u73AF\u5883\u914D\u7F6E\u5931\u8D25\uFF1A${describeCause(error)}`, error);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
async function withBaseQuality(render, quality, read) {
|
|
1739
|
+
if (quality === "high") return read();
|
|
1740
|
+
const capable = render;
|
|
1741
|
+
const toQuality = async (target) => {
|
|
1742
|
+
if (typeof capable.setQuality === "function") await capable.setQuality(target);
|
|
1743
|
+
else await applyQuality(capable, target, SdkRender.DEMO_ENVIRONMENT_BASELINE);
|
|
1744
|
+
};
|
|
1745
|
+
await toQuality("high");
|
|
1746
|
+
try {
|
|
1747
|
+
return await read();
|
|
1748
|
+
} finally {
|
|
1749
|
+
await toQuality(quality);
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
function readLightingLink() {
|
|
1753
|
+
try {
|
|
1754
|
+
const derived = SdkRender.DEMO_ENVIRONMENT_BASELINE_DERIVED;
|
|
1755
|
+
return typeof derived?.ssgiIntensityFromLighting === "function" && typeof derived.ssrtShaftIntensityFromLighting === "function" ? derived : void 0;
|
|
1756
|
+
} catch {
|
|
1757
|
+
return void 0;
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
function readEnvironmentControl() {
|
|
1761
|
+
try {
|
|
1762
|
+
const candidate = SdkRender.EnvironmentControl;
|
|
1763
|
+
return typeof candidate?.create === "function" ? candidate : void 0;
|
|
1764
|
+
} catch {
|
|
1765
|
+
return void 0;
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
async function applyStartupEnvironment(earth, options) {
|
|
1769
|
+
for (const [effect, enabled] of Object.entries(options.effects)) {
|
|
1770
|
+
earth.environment.setEffect(effect, enabled === true);
|
|
1771
|
+
}
|
|
1772
|
+
if (options.presetFile) await loadProjectPreset(earth, options.presetFile);
|
|
1773
|
+
if (options.showPanel) await earth.showPanel(true);
|
|
1774
|
+
}
|
|
1775
|
+
var HTTP_NOT_FOUND = 404;
|
|
1776
|
+
async function loadProjectPreset(earth, url) {
|
|
1777
|
+
let response;
|
|
1778
|
+
try {
|
|
1779
|
+
response = await fetch(url, { cache: "no-cache" });
|
|
1780
|
+
} catch (error) {
|
|
1781
|
+
throw new SmartEarthError("ASSETS_MISSING", `\u8BFB\u53D6\u5DE5\u7A0B\u73AF\u5883\u9884\u8BBE ${url} \u5931\u8D25\uFF1A${describeCause(error)}`, error);
|
|
1782
|
+
}
|
|
1783
|
+
if (response.status === HTTP_NOT_FOUND) return;
|
|
1784
|
+
if (!response.ok) {
|
|
1785
|
+
throw new SmartEarthError("ASSETS_MISSING", `\u8BFB\u53D6\u5DE5\u7A0B\u73AF\u5883\u9884\u8BBE ${url} \u5931\u8D25\uFF1AHTTP ${response.status}`);
|
|
1786
|
+
}
|
|
1787
|
+
if (!(response.headers.get("content-type") ?? "").includes("json")) return;
|
|
1788
|
+
let body;
|
|
1789
|
+
try {
|
|
1790
|
+
body = await response.json();
|
|
1791
|
+
} catch (error) {
|
|
1792
|
+
throw new SmartEarthError("INVALID_OPTIONS", `\u5DE5\u7A0B\u73AF\u5883\u9884\u8BBE ${url} \u4E0D\u662F\u5408\u6CD5\u7684 JSON\u3002`, error);
|
|
1793
|
+
}
|
|
1794
|
+
const snapshot = requirePresetDocument(body, `\u5DE5\u7A0B\u73AF\u5883\u9884\u8BBE ${url}`);
|
|
1795
|
+
await earth.environment.restoreSnapshot(snapshot, { time: true, camera: false });
|
|
1796
|
+
}
|
|
1797
|
+
function toRadians2(Cesium, degrees) {
|
|
1798
|
+
return Cesium.Math.toRadians(degrees);
|
|
1799
|
+
}
|
|
1800
|
+
function createViewer(Cesium, container) {
|
|
1801
|
+
try {
|
|
1802
|
+
return new Cesium.Viewer(container, {
|
|
1803
|
+
baseLayer: false,
|
|
1804
|
+
baseLayerPicker: false,
|
|
1805
|
+
geocoder: false,
|
|
1806
|
+
homeButton: false,
|
|
1807
|
+
sceneModePicker: false,
|
|
1808
|
+
navigationHelpButton: false,
|
|
1809
|
+
animation: false,
|
|
1810
|
+
timeline: false,
|
|
1811
|
+
fullscreenButton: false,
|
|
1812
|
+
vrButton: false,
|
|
1813
|
+
infoBox: false,
|
|
1814
|
+
selectionIndicator: false,
|
|
1815
|
+
shouldAnimate: true
|
|
1816
|
+
});
|
|
1817
|
+
} catch (error) {
|
|
1818
|
+
throw new SmartEarthError(
|
|
1819
|
+
"RENDER_INIT_FAILED",
|
|
1820
|
+
`\u4E09\u7EF4\u573A\u666F\u521B\u5EFA\u5931\u8D25\uFF08\u6D4F\u89C8\u5668\u53EF\u80FD\u4E0D\u652F\u6301 WebGL2\uFF09\uFF1A${describeCause(error)}`,
|
|
1821
|
+
error
|
|
1822
|
+
);
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
function isAuthFailure(error) {
|
|
1826
|
+
return /auth|licen[cs]e|鉴权|授权|token\s*(校验|invalid|expired)/i.test(describeCause(error));
|
|
1827
|
+
}
|
|
1828
|
+
function secretsOf(options) {
|
|
1829
|
+
const auth = options.auth;
|
|
1830
|
+
return [options.geovisToken, ..."token" in auth ? [auth.token] : [auth.lic, auth.rsaPubKey]];
|
|
1831
|
+
}
|
|
1832
|
+
function sanitizeError(error, secrets) {
|
|
1833
|
+
if (error instanceof SmartEarthError) {
|
|
1834
|
+
return new SmartEarthError(error.code, describeCause(error, secrets));
|
|
1835
|
+
}
|
|
1836
|
+
return new SmartEarthError("RENDER_INIT_FAILED", `SmartEarth \u521D\u59CB\u5316\u5931\u8D25\uFF1A${describeCause(error, secrets)}`);
|
|
1837
|
+
}
|
|
1838
|
+
function safely(action) {
|
|
1839
|
+
try {
|
|
1840
|
+
action();
|
|
1841
|
+
} catch {
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
function nativeQualityOption(quality) {
|
|
1845
|
+
return getSupportedQualities().includes("medium") && quality !== "high" ? { quality } : {};
|
|
1846
|
+
}
|
|
1847
|
+
async function createRender(viewer, options) {
|
|
1848
|
+
try {
|
|
1849
|
+
return await SdkRender.Render.createWithDefaults({
|
|
1850
|
+
viewer,
|
|
1851
|
+
baseline: options.baseline,
|
|
1852
|
+
assetsBasePath: options.assetsBasePath,
|
|
1853
|
+
...options.auth,
|
|
1854
|
+
...nativeQualityOption(options.quality)
|
|
1855
|
+
});
|
|
1856
|
+
} catch (error) {
|
|
1857
|
+
if (isAuthFailure(error)) {
|
|
1858
|
+
throw new SmartEarthError(
|
|
1859
|
+
"AUTH_FAILED",
|
|
1860
|
+
`SmartEarth SDK \u6388\u6743\u6821\u9A8C\u5931\u8D25\uFF08\u5728\u7EBF\u4EE4\u724C\u9700\u80FD\u8BBF\u95EE\u6821\u9A8C\u670D\u52A1\uFF1Blicence \u9700\u672C\u5730 sdk-licence \u670D\u52A1\uFF09\uFF1A${describeCause(error)}`,
|
|
1861
|
+
error
|
|
1862
|
+
);
|
|
1863
|
+
}
|
|
1864
|
+
throw new SmartEarthError("RENDER_INIT_FAILED", `SmartEarth \u6E32\u67D3\u521D\u59CB\u5316\u5931\u8D25\uFF1A${describeCause(error)}`, error);
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
function setInitialView(Cesium, viewer, options) {
|
|
1868
|
+
const view = options.initialView;
|
|
1869
|
+
viewer.camera.setView({
|
|
1870
|
+
destination: Cesium.Cartesian3.fromDegrees(view.lon, view.lat, view.height),
|
|
1871
|
+
orientation: {
|
|
1872
|
+
heading: toRadians2(Cesium, view.heading),
|
|
1873
|
+
pitch: toRadians2(Cesium, view.pitch),
|
|
1874
|
+
roll: 0
|
|
1875
|
+
}
|
|
1876
|
+
});
|
|
1877
|
+
}
|
|
1878
|
+
function toGeoPosition(Cesium, cartesian) {
|
|
1879
|
+
const carto = Cesium.Cartographic.fromCartesian(cartesian);
|
|
1880
|
+
if (!carto) return void 0;
|
|
1881
|
+
return {
|
|
1882
|
+
lon: Cesium.Math.toDegrees(carto.longitude),
|
|
1883
|
+
lat: Cesium.Math.toDegrees(carto.latitude),
|
|
1884
|
+
height: carto.height
|
|
1885
|
+
};
|
|
1886
|
+
}
|
|
1887
|
+
function pickPosition(Cesium, viewer, position) {
|
|
1888
|
+
const ray = viewer.camera.getPickRay(position);
|
|
1889
|
+
const cartesian = ray ? viewer.scene.globe.pick(ray, viewer.scene) : void 0;
|
|
1890
|
+
if (!cartesian) return void 0;
|
|
1891
|
+
const carto = Cesium.Cartographic.fromCartesian(cartesian);
|
|
1892
|
+
return {
|
|
1893
|
+
lon: Cesium.Math.toDegrees(carto.longitude),
|
|
1894
|
+
lat: Cesium.Math.toDegrees(carto.latitude),
|
|
1895
|
+
height: carto.height
|
|
1896
|
+
};
|
|
1897
|
+
}
|
|
1898
|
+
async function createEarth(container, rawOptions) {
|
|
1899
|
+
if (!(container instanceof HTMLElement)) {
|
|
1900
|
+
throw new SmartEarthError("INVALID_OPTIONS", "createEarth \u7684\u7B2C\u4E00\u4E2A\u53C2\u6570\u5FC5\u987B\u662F DOM \u5BB9\u5668\u5143\u7D20\u3002");
|
|
1901
|
+
}
|
|
1902
|
+
const options = resolveOptions(rawOptions);
|
|
1903
|
+
const Cesium = installGlobalCesium();
|
|
1904
|
+
if (options.checkAssets) await assertAssetsAvailable(options.assetsBasePath);
|
|
1905
|
+
installRenderStateCompatibility(Cesium);
|
|
1906
|
+
const secrets = secretsOf(options);
|
|
1907
|
+
let viewer;
|
|
1908
|
+
let render;
|
|
1909
|
+
try {
|
|
1910
|
+
viewer = createViewer(Cesium, container);
|
|
1911
|
+
addBasemap(Cesium, viewer, options);
|
|
1912
|
+
await addTerrain(Cesium, viewer, options);
|
|
1913
|
+
setInitialView(Cesium, viewer, options);
|
|
1914
|
+
render = await createRender(viewer, options);
|
|
1915
|
+
const qualityApplied = Object.keys(nativeQualityOption(options.quality)).length > 0;
|
|
1916
|
+
if (options.quality !== "high" && !qualityApplied) {
|
|
1917
|
+
await applyQuality(render, options.quality, SdkRender.DEMO_ENVIRONMENT_BASELINE);
|
|
1918
|
+
}
|
|
1919
|
+
const earth = assembleEarth(Cesium, viewer, render, options.quality);
|
|
1920
|
+
try {
|
|
1921
|
+
await applyStartupEnvironment(earth, options);
|
|
1922
|
+
} catch (error) {
|
|
1923
|
+
earth.destroy();
|
|
1924
|
+
throw error;
|
|
1925
|
+
}
|
|
1926
|
+
return earth;
|
|
1927
|
+
} catch (error) {
|
|
1928
|
+
const created = { viewer, render };
|
|
1929
|
+
safely(() => created.render?.destroy());
|
|
1930
|
+
safely(() => {
|
|
1931
|
+
if (created.viewer && !created.viewer.isDestroyed()) created.viewer.destroy();
|
|
1932
|
+
});
|
|
1933
|
+
throw sanitizeError(error, secrets);
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
function resolveFeature(Cesium, picked, pickables, resolvers) {
|
|
1937
|
+
const id = picked?.id;
|
|
1938
|
+
if (id instanceof Cesium.Entity) {
|
|
1939
|
+
const feature = pickables.get(id);
|
|
1940
|
+
if (feature) return { feature, entity: id };
|
|
1941
|
+
}
|
|
1942
|
+
for (const resolver of resolvers) {
|
|
1943
|
+
const feature = resolver(picked);
|
|
1944
|
+
if (feature) return { feature };
|
|
1945
|
+
}
|
|
1946
|
+
return {};
|
|
1947
|
+
}
|
|
1948
|
+
function createClickPipeline(Cesium, viewer, emitter, onError) {
|
|
1949
|
+
const pickables = /* @__PURE__ */ new WeakMap();
|
|
1950
|
+
const resolvers = /* @__PURE__ */ new Set();
|
|
1951
|
+
const clicks = new Emitter(onError);
|
|
1952
|
+
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
|
|
1953
|
+
handler.setInputAction((movement) => {
|
|
1954
|
+
const { feature, entity } = resolveFeature(Cesium, viewer.scene.pick(movement.position), pickables, resolvers);
|
|
1955
|
+
const groundPosition = pickPosition(Cesium, viewer, movement.position);
|
|
1956
|
+
const entityPosition = entity?.position?.getValue(viewer.clock.currentTime);
|
|
1957
|
+
const surfacePosition = feature && !entityPosition && viewer.scene.pickPositionSupported ? viewer.scene.pickPosition(movement.position) : void 0;
|
|
1958
|
+
const worldPosition = entityPosition ?? surfacePosition ?? (groundPosition ? Cesium.Cartesian3.fromDegrees(groundPosition.lon, groundPosition.lat, groundPosition.height) : void 0);
|
|
1959
|
+
const position = surfacePosition ? toGeoPosition(Cesium, surfacePosition) : groundPosition;
|
|
1960
|
+
const screen = { x: movement.position.x, y: movement.position.y };
|
|
1961
|
+
clicks.emit("click", { feature, position, worldPosition, screen });
|
|
1962
|
+
if (feature) emitter.emit("pick", { ...feature, position });
|
|
1963
|
+
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
|
1964
|
+
return { handler, clicks, pickables, resolvers };
|
|
1965
|
+
}
|
|
1966
|
+
function registerBuiltinLayers(registry) {
|
|
1967
|
+
registry.register("points", pointsLayerFactory);
|
|
1968
|
+
registry.register("geojson", geojsonLayerFactory);
|
|
1969
|
+
registry.register("tileset3d", tileset3dLayerFactory);
|
|
1970
|
+
registry.register("route", routeLayerFactory);
|
|
1971
|
+
registry.register("popup", popupLayerFactory);
|
|
1972
|
+
registry.register("annotation", annotationLayerFactory);
|
|
1973
|
+
registry.register("riverWater", riverWaterLayerFactory);
|
|
1974
|
+
}
|
|
1975
|
+
function assembleEarth(Cesium, viewer, render, initialQuality) {
|
|
1976
|
+
let quality = initialQuality;
|
|
1977
|
+
let destroyed = false;
|
|
1978
|
+
const reportListenerError = (error) => {
|
|
1979
|
+
console.error("[smartearth-base] \u4E8B\u4EF6\u76D1\u542C\u5668\u51FA\u9519", error);
|
|
1980
|
+
};
|
|
1981
|
+
const emitter = new Emitter(reportListenerError);
|
|
1982
|
+
const pbr = createEarthPbr(render);
|
|
1983
|
+
let notifyEnvironment;
|
|
1984
|
+
const panel = createPanelController(render, readEnvironmentControl(), () => notifyEnvironment?.("panel"));
|
|
1985
|
+
const pipeline = createClickPipeline(Cesium, viewer, emitter, reportListenerError);
|
|
1986
|
+
const clickHandler = pipeline.handler;
|
|
1987
|
+
const registry = createLayerRegistry(
|
|
1988
|
+
{
|
|
1989
|
+
viewer,
|
|
1990
|
+
Cesium,
|
|
1991
|
+
render,
|
|
1992
|
+
pbr,
|
|
1993
|
+
sdkRenderVersion: readSdkRenderVersion(),
|
|
1994
|
+
registerPickable: (entity, feature) => pipeline.pickables.set(entity, feature),
|
|
1995
|
+
unregisterPickable: (entity) => pipeline.pickables.delete(entity),
|
|
1996
|
+
registerPickResolver: (resolver) => {
|
|
1997
|
+
pipeline.resolvers.add(resolver);
|
|
1998
|
+
return () => pipeline.resolvers.delete(resolver);
|
|
1999
|
+
},
|
|
2000
|
+
onClick: (listener) => pipeline.clicks.on("click", listener)
|
|
2001
|
+
},
|
|
2002
|
+
() => !destroyed
|
|
2003
|
+
);
|
|
2004
|
+
registerBuiltinLayers(registry);
|
|
2005
|
+
const assertAlive = () => {
|
|
2006
|
+
if (destroyed) throw new SmartEarthError("DESTROYED", "\u5730\u7403\u5DF2\u9500\u6BC1\u3002");
|
|
2007
|
+
};
|
|
2008
|
+
const environment = createEarthEnvironment({
|
|
2009
|
+
viewer,
|
|
2010
|
+
Cesium,
|
|
2011
|
+
render,
|
|
2012
|
+
assertAlive,
|
|
2013
|
+
resetToBaseline: () => resetToBaseline(render, quality),
|
|
2014
|
+
lightingLink: readLightingLink(),
|
|
2015
|
+
getQuality: () => quality,
|
|
2016
|
+
withBaseQuality: (read) => withBaseQuality(render, quality, read)
|
|
2017
|
+
});
|
|
2018
|
+
notifyEnvironment = (source) => environment.notify(source);
|
|
2019
|
+
return {
|
|
2020
|
+
viewer,
|
|
2021
|
+
render,
|
|
2022
|
+
get quality() {
|
|
2023
|
+
return quality;
|
|
2024
|
+
},
|
|
2025
|
+
supportedQualities: qualitiesFor(
|
|
2026
|
+
render,
|
|
2027
|
+
SdkRender.DEMO_ENVIRONMENT_BASELINE
|
|
2028
|
+
),
|
|
2029
|
+
async setQuality(next) {
|
|
2030
|
+
assertAlive();
|
|
2031
|
+
const time = environment.getPreset() ? environment.getTime() : void 0;
|
|
2032
|
+
const preset = environment.suspendPreset();
|
|
2033
|
+
let reenterError;
|
|
2034
|
+
try {
|
|
2035
|
+
await applyQuality(render, next, SdkRender.DEMO_ENVIRONMENT_BASELINE);
|
|
2036
|
+
quality = next;
|
|
2037
|
+
} finally {
|
|
2038
|
+
if (preset) {
|
|
2039
|
+
try {
|
|
2040
|
+
environment.setPreset(preset, { deferAboveMeters: false });
|
|
2041
|
+
if (time) environment.setTime(time);
|
|
2042
|
+
} catch (error) {
|
|
2043
|
+
reenterError = error;
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
if (reenterError !== void 0) throw reenterError;
|
|
2048
|
+
environment.notify("quality");
|
|
2049
|
+
},
|
|
2050
|
+
layers: {
|
|
2051
|
+
register: (kind, factory) => registry.register(kind, factory),
|
|
2052
|
+
add: (spec) => {
|
|
2053
|
+
assertAlive();
|
|
2054
|
+
return registry.add(spec);
|
|
2055
|
+
},
|
|
2056
|
+
remove: (id) => registry.remove(id),
|
|
2057
|
+
setVisible: (id, visible) => registry.setVisible(id, visible),
|
|
2058
|
+
list: () => registry.list(),
|
|
2059
|
+
get: (id) => registry.get(id)
|
|
2060
|
+
},
|
|
2061
|
+
pbr,
|
|
2062
|
+
environment,
|
|
2063
|
+
captureImage(maxWidth) {
|
|
2064
|
+
assertAlive();
|
|
2065
|
+
return captureImage(viewer, maxWidth);
|
|
2066
|
+
},
|
|
2067
|
+
async showPanel(visible = true) {
|
|
2068
|
+
assertAlive();
|
|
2069
|
+
if (typeof visible !== "boolean") throw new SmartEarthError("INVALID_OPTIONS", "showPanel \u7684\u53C2\u6570\u5FC5\u987B\u662F true / false\u3002");
|
|
2070
|
+
await panel.show(visible);
|
|
2071
|
+
},
|
|
2072
|
+
get isPanelVisible() {
|
|
2073
|
+
return panel.visible;
|
|
2074
|
+
},
|
|
2075
|
+
async flyTo(target) {
|
|
2076
|
+
assertAlive();
|
|
2077
|
+
if (typeof target === "string") {
|
|
2078
|
+
await viewer.flyTo(registry.flyTarget(target), {
|
|
2079
|
+
duration: DEFAULT_FLY_DURATION
|
|
2080
|
+
});
|
|
2081
|
+
return;
|
|
2082
|
+
}
|
|
2083
|
+
await new Promise((resolve) => {
|
|
2084
|
+
viewer.camera.flyTo({
|
|
2085
|
+
destination: Cesium.Cartesian3.fromDegrees(target.lon, target.lat, target.height),
|
|
2086
|
+
orientation: {
|
|
2087
|
+
heading: toRadians2(Cesium, target.heading ?? 0),
|
|
2088
|
+
pitch: toRadians2(Cesium, target.pitch ?? -90),
|
|
2089
|
+
roll: 0
|
|
2090
|
+
},
|
|
2091
|
+
duration: target.duration ?? DEFAULT_FLY_DURATION,
|
|
2092
|
+
complete: () => resolve(),
|
|
2093
|
+
cancel: () => resolve()
|
|
2094
|
+
});
|
|
2095
|
+
});
|
|
2096
|
+
},
|
|
2097
|
+
on: (event, listener) => emitter.on(event, listener),
|
|
2098
|
+
destroy() {
|
|
2099
|
+
if (destroyed) return;
|
|
2100
|
+
destroyed = true;
|
|
2101
|
+
emitter.clear();
|
|
2102
|
+
safely(() => clickHandler.destroy());
|
|
2103
|
+
safely(() => registry.destroyAll());
|
|
2104
|
+
safely(() => panel.destroy());
|
|
2105
|
+
safely(() => environment.destroy());
|
|
2106
|
+
pipeline.clicks.clear();
|
|
2107
|
+
pipeline.resolvers.clear();
|
|
2108
|
+
safely(() => render.destroy());
|
|
2109
|
+
safely(() => {
|
|
2110
|
+
if (!viewer.isDestroyed()) viewer.destroy();
|
|
2111
|
+
});
|
|
2112
|
+
}
|
|
2113
|
+
};
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
export { CESIUM_MAX_VERSION_EXCLUSIVE, CESIUM_MIN_VERSION, LOW_QUALITY_OVERRIDES, createEarth, createEarthPbr, escapeHtml, getSupportedQualities, makeExtensible, supportsPbr };
|