Files
NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react/src/CesiumMapRenderer.tsx
T

999 lines
30 KiB
TypeScript

import {
forwardRef,
useEffect,
useImperativeHandle,
useRef,
} from "react";
import type * as CesiumModule from "cesium";
import type {
CesiumMapRendererHandle,
CesiumMapRendererProps,
MapCamera,
MapGhostPin,
MapGhostPinLayer,
MapProviderId,
MapRuntimeState,
} from "./contracts.js";
import {applyMapSceneEffects} from "./sceneEffects.js";
import { advanceGhostPins } from "./ghostPins.js";
import {
parseProviderEndpoint,
type ProviderEndpoint,
} from "./providerEndpoint.js";
import {
MapRuntimeError,
applyCacheIntent,
assetEndpointPath,
fetchMapRuntimeConfiguration,
fetchSameOriginJson,
initialMapRuntimeState,
withProviderState,
} from "./runtime.js";
type CesiumNamespace = typeof CesiumModule;
type RendererRuntime = {
Cesium: CesiumNamespace;
viewer: CesiumModule.Viewer;
ellipsoidTerrain: CesiumModule.EllipsoidTerrainProvider;
worldTerrain: CesiumModule.CesiumTerrainProvider | null;
imageryLayer: CesiumModule.ImageryLayer | null;
buildings: CesiumModule.Cesium3DTileset | null;
grid: CesiumModule.CustomDataSource;
ghostPins: CesiumModule.CustomDataSource;
currentGhostPins: MapGhostPin[];
ghostPinSourceSignature: string;
stopGhostPinAnimation: (() => void) | null;
rebuildGrid: () => void;
};
export const CesiumMapRenderer = forwardRef<
CesiumMapRendererHandle,
CesiumMapRendererProps
>(function CesiumMapRenderer({
runtimeConfigUrl,
camera,
layers,
settings,
cacheIntent,
ghostPins,
rendererGeneration = 0,
className,
onRuntimeStateChange,
onCameraChange,
onSceneReady,
}, forwardedRef) {
const containerRef = useRef<HTMLDivElement | null>(null);
const stateCallbackRef = useRef(onRuntimeStateChange);
const cameraCallbackRef = useRef(onCameraChange);
const sceneCallbackRef = useRef(onSceneReady);
sceneCallbackRef.current = onSceneReady;
const runtimeRef = useRef<RendererRuntime | null>(null);
const settingsRef = useRef(settings);
const layersRef = useRef(layers);
const ghostPinsRef = useRef(ghostPins);
stateCallbackRef.current = onRuntimeStateChange;
cameraCallbackRef.current = onCameraChange;
settingsRef.current = settings;
layersRef.current = layers;
ghostPinsRef.current = ghostPins;
useImperativeHandle(forwardedRef, () => ({
getViewAnchor: () => {
const runtime = runtimeRef.current;
return runtime ? viewAnchor(runtime) : null;
},
snapshotGhostPins: () => {
const runtime = runtimeRef.current;
return runtime
? runtime.currentGhostPins.map((pin) => ({ ...pin }))
: null;
},
}), []);
useEffect(() => {
const runtime = runtimeRef.current;
if (!runtime) {
return;
}
applyPresentation(runtime, settings, layers);
runtime.rebuildGrid();
syncGhostPinLayer(runtime, ghostPins);
updateGhostPinAnimation(
runtime,
Boolean(
ghostPins?.simulation_enabled
&& layers.targets
&& ghostPins.pins.length > 0
),
ghostPinsRef,
layersRef,
);
}, [settings, layers, ghostPins]);
useEffect(() => {
const container = containerRef.current;
if (!container) {
return;
}
const abortController = new AbortController();
let disposed = false;
let viewer: CesiumModule.Viewer | null = null;
let disposeConsumer: (() => void) | void;
let removeCameraListener: (() => void) | undefined;
let removeRenderListener: (() => void) | undefined;
let runtimeState = initialMapRuntimeState();
const publish = (next: MapRuntimeState) => {
runtimeState = next;
if (!disposed) {
stateCallbackRef.current?.(next);
}
};
publish(runtimeState);
void (async () => {
try {
const configuration = await fetchMapRuntimeConfiguration(
runtimeConfigUrl,
abortController.signal,
);
const Cesium = await import("cesium");
if (disposed) {
return;
}
const creditContainer = configuration.sandbox?.hide_credit_overlay
? createSandboxCreditContainer(container)
: undefined;
viewer = createViewer(Cesium, container, creditContainer);
const ellipsoidTerrain = new Cesium.EllipsoidTerrainProvider();
const grid = new Cesium.CustomDataSource("nodedc-map-grid");
const ghostPinDataSource = new Cesium.CustomDataSource(
"nodedc-map-ghost-pins",
);
void viewer.dataSources.add(grid);
void viewer.dataSources.add(ghostPinDataSource);
const runtime: RendererRuntime = {
Cesium,
viewer,
ellipsoidTerrain,
worldTerrain: null,
imageryLayer: null,
buildings: null,
grid,
ghostPins: ghostPinDataSource,
currentGhostPins: [],
ghostPinSourceSignature: "",
stopGhostPinAnimation: null,
rebuildGrid: () => undefined,
};
runtime.rebuildGrid = () => {
rebuildElevatedGrid(runtime, settingsRef.current, layersRef.current.grid);
};
runtimeRef.current = runtime;
viewer.terrainProvider = ellipsoidTerrain;
viewer.scene.globe.depthTestAgainstTerrain = true;
applyPresentation(runtime, settingsRef.current, layersRef.current);
applyCamera(Cesium, viewer, camera);
runtime.rebuildGrid();
syncGhostPinLayer(runtime, ghostPinsRef.current);
updateGhostPinAnimation(
runtime,
Boolean(
ghostPinsRef.current?.simulation_enabled
&& layersRef.current.targets
&& ghostPinsRef.current.pins.length > 0
),
ghostPinsRef,
layersRef,
);
removeCameraListener = bindCamera(
Cesium,
viewer,
cameraCallbackRef,
runtime.rebuildGrid,
);
removeRenderListener = bindRenderRecovery(viewer, publish);
disposeConsumer = sceneCallbackRef.current?.({Cesium, viewer, signal: abortController.signal});
const providerJobs = (["imagery", "terrain", "buildings"] as const).map(
async (providerId) => {
const visible = layers[providerId];
publish(
withProviderState(runtimeState, providerId, {
phase: visible ? "loading" : "disabled",
}),
);
if (!visible) {
return;
}
try {
const endpoint = await fetchProviderEndpoint(
configuration,
providerId,
abortController.signal,
);
if (disposed || !viewer) {
return;
}
await attachProvider(
runtime,
configuration.gateway.cache_proxy_prefix,
endpoint,
providerId,
cacheIntent,
false,
);
addAttributions(Cesium, viewer, endpoint);
applyPresentation(runtime, settingsRef.current, layersRef.current);
publish(
withProviderState(runtimeState, providerId, {
phase: "ready",
attributions: endpoint.attributions,
}),
);
} catch (error) {
if (abortController.signal.aborted) {
return;
}
publish(
withProviderState(runtimeState, providerId, {
phase: "error",
code: safeErrorCode(error),
}),
);
}
},
);
await Promise.allSettled(providerJobs);
if (disposed) {
removeCameraListener?.();
removeRenderListener?.();
runtime.stopGhostPinAnimation?.();
}
} catch (error) {
if (!abortController.signal.aborted) {
const code = safeErrorCode(error);
publish({
phase: "gateway-unavailable",
providers: {
imagery: { phase: "error", code },
terrain: { phase: "error", code },
buildings: { phase: "error", code },
},
code,
});
}
}
})();
return () => {
disposed = true;
abortController.abort();
try { disposeConsumer?.(); } finally {
removeCameraListener?.();
removeRenderListener?.();
runtimeRef.current?.stopGhostPinAnimation?.();
runtimeRef.current = null;
viewer?.destroy();
viewer = null;
container.replaceChildren();
}
};
}, [
runtimeConfigUrl,
rendererGeneration,
layers.imagery,
layers.terrain,
layers.buildings,
cacheIntent.enabled,
cacheIntent.no_overwrite,
]);
return <div ref={containerRef} className={className} data-nodedc-map-renderer="cesium" />;
});
function createViewer(
Cesium: CesiumNamespace,
container: HTMLElement,
creditContainer?: HTMLElement,
): CesiumModule.Viewer {
const viewer = new Cesium.Viewer(container, {
animation: false,
baseLayer: false,
baseLayerPicker: false,
fullscreenButton: false,
geocoder: false,
homeButton: false,
infoBox: false,
navigationHelpButton: false,
sceneModePicker: false,
selectionIndicator: false,
timeline: false,
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
requestRenderMode: true,
maximumRenderTimeChange: Number.POSITIVE_INFINITY,
showRenderLoopErrors: false,
creditContainer,
});
viewer.scene.rethrowRenderErrors = false;
return viewer;
}
function createSandboxCreditContainer(container: HTMLElement): HTMLDivElement {
const credits = document.createElement("div");
credits.hidden = true;
credits.setAttribute("aria-hidden", "true");
credits.dataset.nodedcSandboxCredits = "suppressed";
container.appendChild(credits);
return credits;
}
async function fetchProviderEndpoint(
configuration: Awaited<ReturnType<typeof fetchMapRuntimeConfiguration>>,
providerId: MapProviderId,
signal: AbortSignal,
): Promise<ProviderEndpoint> {
const document = await fetchSameOriginJson(
assetEndpointPath(configuration, providerId),
signal,
);
const expectedAssetId = configuration.assets[providerId];
return parseProviderEndpoint(document, expectedAssetId, providerId);
}
async function attachProvider(
runtime: RendererRuntime,
cacheProxyPrefix: string,
endpoint: ProviderEndpoint,
providerId: MapProviderId,
cacheIntent: CesiumMapRendererProps["cacheIntent"],
refresh: boolean,
): Promise<void> {
const { Cesium, viewer } = runtime;
const publicUrl =
providerId === "imagery" ? endpoint.options?.url : endpoint.url;
if (!publicUrl) {
throw new MapRuntimeError("map_provider_contract_mismatch");
}
const resource = new Cesium.Resource({
url: applyCacheIntent(publicUrl, cacheIntent, refresh),
proxy: new Cesium.DefaultProxy(cacheProxyPrefix),
});
if (providerId === "imagery") {
const provider = await Cesium.BingMapsImageryProvider.fromUrl(resource, {
// Cesium requires a key-shaped value to build Bing metadata and tile
// URLs. This is a public marker, not a credential: Map Gateway strips
// it and injects the server-owned provider key upstream.
key: "nodedc-gateway",
mapStyle: bingMapStyle(Cesium, endpoint.options?.mapStyle),
tileProtocol: "https",
});
runtime.imageryLayer = viewer.imageryLayers.addImageryProvider(provider);
return;
}
if (providerId === "terrain") {
runtime.worldTerrain = await Cesium.CesiumTerrainProvider.fromUrl(resource);
return;
}
runtime.buildings = await Cesium.Cesium3DTileset.fromUrl(resource);
viewer.scene.primitives.add(runtime.buildings);
}
function addAttributions(
Cesium: CesiumNamespace,
viewer: CesiumModule.Viewer,
endpoint: ProviderEndpoint,
): void {
for (const attribution of endpoint.attributions) {
if (attribution.html) {
viewer.creditDisplay.addStaticCredit(
new Cesium.Credit(attribution.html, attribution.collapsible),
);
}
}
}
function bindCamera(
Cesium: CesiumNamespace,
viewer: CesiumModule.Viewer,
callbackRef: { current: ((camera: MapCamera) => void) | undefined },
onMoveEnd: () => void,
): () => void {
const listener = () => {
onMoveEnd();
const position = viewer.camera.positionCartographic;
callbackRef.current?.({
longitude: Cesium.Math.toDegrees(position.longitude),
latitude: Cesium.Math.toDegrees(position.latitude),
height: position.height,
heading: Cesium.Math.toDegrees(viewer.camera.heading),
pitch: Cesium.Math.toDegrees(viewer.camera.pitch),
roll: Cesium.Math.toDegrees(viewer.camera.roll),
});
};
return viewer.camera.moveEnd.addEventListener(listener);
}
function bindRenderRecovery(
viewer: CesiumModule.Viewer,
publish: (state: MapRuntimeState) => void,
): () => void {
let recoveryAttempted = false;
return viewer.scene.renderError.addEventListener(() => {
if (!recoveryAttempted) {
recoveryAttempted = true;
viewer.scene.requestRender();
return;
}
publish({
phase: "render-error",
providers: {
imagery: { phase: "error", code: "cesium_render_error" },
terrain: { phase: "error", code: "cesium_render_error" },
buildings: { phase: "error", code: "cesium_render_error" },
},
code: "cesium_render_error",
});
});
}
function applyCamera(
Cesium: CesiumNamespace,
viewer: CesiumModule.Viewer,
camera: MapCamera | null,
): void {
if (!camera) {
viewer.camera.flyHome(0);
return;
}
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(
camera.longitude,
camera.latitude,
camera.height,
),
orientation: {
heading: Cesium.Math.toRadians(camera.heading),
pitch: Cesium.Math.toRadians(camera.pitch),
roll: Cesium.Math.toRadians(camera.roll),
},
});
}
function bingMapStyle(
Cesium: CesiumNamespace,
value: string | undefined,
): CesiumModule.BingMapsStyle {
if (value === "Road") {
return Cesium.BingMapsStyle.ROAD;
}
if (value === "AerialWithLabels") {
return Cesium.BingMapsStyle.AERIAL_WITH_LABELS;
}
return Cesium.BingMapsStyle.AERIAL;
}
function applyPresentation(
runtime: RendererRuntime,
settings: CesiumMapRendererProps["settings"],
layers: CesiumMapRendererProps["layers"],
): void {
const { Cesium, viewer, imageryLayer, buildings } = runtime;
if (imageryLayer) {
imageryLayer.show = layers.imagery && !settings.monochrome_enabled;
imageryLayer.brightness = settings.imagery_brightness / 100;
imageryLayer.contrast = settings.imagery_contrast / 100;
imageryLayer.saturation = settings.imagery_saturation / 100;
imageryLayer.gamma = settings.imagery_gamma / 100;
imageryLayer.hue = Cesium.Math.toRadians(settings.imagery_hue);
imageryLayer.alpha = settings.imagery_alpha / 100;
}
if (buildings) {
buildings.show = layers.buildings;
buildings.maximumScreenSpaceError =
settings.buildings_maximum_screen_space_error;
buildings.style = new Cesium.Cesium3DTileStyle({
color: settings.buildings_style_default
? `Boolean(\${feature['cesium#color']}) ? color(\${feature['cesium#color']}, ${settings.buildings_opacity}) : color('#ffffff', ${settings.buildings_opacity})`
: `color('${settings.buildings_color}', ${settings.buildings_opacity})`,
});
}
runtime.ghostPins.show = layers.targets;
viewer.terrainProvider =
layers.terrain && runtime.worldTerrain
? runtime.worldTerrain
: runtime.ellipsoidTerrain;
viewer.scene.globe.show = true;
viewer.scene.globe.baseColor = cssColor(
Cesium,
settings.monochrome_enabled
? settings.monochrome_color
: settings.globe_color,
"#15151b",
);
viewer.scene.globe.enableLighting = settings.sun_enabled;
viewer.scene.verticalExaggeration = clamp(
settings.terrain_exaggeration,
0.25,
3,
);
viewer.scene.backgroundColor = cssColor(
Cesium,
settings.background_color,
"#08090d",
);
viewer.scene.fog.enabled = settings.fog_enabled;
viewer.scene.fog.density = clamp(settings.fog_density / 10_000, 0, 0.01);
const atmosphere = viewer.scene.skyAtmosphere;
if (atmosphere) {
atmosphere.show = settings.atmosphere_enabled;
atmosphere.hueShift = clamp(settings.atmosphere_hue / 100, -1, 1);
atmosphere.saturationShift = clamp(
settings.atmosphere_saturation / 100,
-1,
1,
);
atmosphere.brightnessShift = clamp(
settings.atmosphere_brightness / 100,
-1,
1,
);
}
viewer.shadows = settings.shadows_enabled;
const sunDate = Cesium.JulianDate.toDate(Cesium.JulianDate.now());
if (!settings.sun_time_current) sunDate.setUTCHours(
Math.floor(clamp(settings.sun_hour, 0, 24)),
Math.round((settings.sun_hour % 1) * 60),
0,
0,
);
viewer.clock.currentTime = Cesium.JulianDate.fromDate(sunDate);
viewer.clock.shouldAnimate = false;
const sun = new Cesium.SunLight();
(sun as CesiumModule.SunLight & { intensity?: number }).intensity = clamp(
settings.sun_intensity / 100,
0,
2,
);
viewer.scene.light = sun;
applyMapSceneEffects(runtime, settings);
viewer.scene.requestRender();
}
function syncGhostPinLayer(
runtime: RendererRuntime,
layer: MapGhostPinLayer | undefined,
): void {
const nextPins = layer?.pins ?? [];
const sourceSignature = nextPins.map((pin) => [
pin.id,
pin.label,
pin.longitude,
pin.latitude,
pin.heading_degrees,
pin.speed_meters_per_second,
].join(":")).join("|");
if (sourceSignature !== runtime.ghostPinSourceSignature) {
runtime.currentGhostPins = nextPins.map((pin) => ({ ...pin }));
runtime.ghostPinSourceSignature = sourceSignature;
}
rebuildGhostPinEntities(runtime, layer);
}
function rebuildGhostPinEntities(
runtime: RendererRuntime,
layer: MapGhostPinLayer | undefined,
): void {
const { Cesium, viewer, ghostPins } = runtime;
ghostPins.entities.removeAll();
if (!layer) {
viewer.scene.requestRender();
return;
}
const presentation = layer.presentation;
const fillColor = cssColor(Cesium, presentation.color, "#6fb5fb").withAlpha(
clamp(presentation.opacity, 0, 1),
);
const outlineColor = cssColor(
Cesium,
presentation.outline_color,
"#0c0d12",
).withAlpha(clamp(presentation.outline_opacity, 0, 1));
const headImage = elevatedTargetImage(
fillColor,
outlineColor,
presentation.outline_width_px,
presentation.head_size_px,
);
const targetDistance = new Cesium.DistanceDisplayCondition(
0,
presentation.target_hide_camera_height_meters,
);
const labelDistance = new Cesium.DistanceDisplayCondition(
0,
presentation.label_hide_camera_height_meters,
);
for (const pin of runtime.currentGhostPins) {
const label = presentation.label_mode === "subject_id"
? pin.id
: pin.label;
ghostPins.entities.add({
id: pin.id,
position: ghostPinTopPosition(
runtime,
pin,
presentation.stem_height_meters,
),
polyline: {
positions: ghostPinStemPositions(
runtime,
pin,
presentation.stem_height_meters,
),
width: presentation.stem_width_px,
material: fillColor,
depthFailMaterial: fillColor,
distanceDisplayCondition: targetDistance,
},
billboard: {
image: headImage.image,
width: headImage.size,
height: headImage.size,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
distanceDisplayCondition: targetDistance,
},
label: {
text: label.slice(0, presentation.label_max_length),
font: `${presentation.label_font_weight} ${presentation.label_size_px}px Arial`,
fillColor: cssColor(
Cesium,
presentation.label_color,
"#f5f5f5",
),
outlineColor: Cesium.Color.TRANSPARENT,
outlineWidth: 0,
style: Cesium.LabelStyle.FILL,
show: presentation.label_mode !== "none",
showBackground: presentation.label_background_opacity > 0,
backgroundColor: cssColor(
Cesium,
presentation.label_background_color,
"#0c0d12",
).withAlpha(clamp(presentation.label_background_opacity, 0, 1)),
backgroundPadding: new Cesium.Cartesian2(
presentation.label_padding_x,
presentation.label_padding_y,
),
pixelOffset: new Cesium.Cartesian2(
presentation.label_offset_x,
presentation.label_offset_y,
),
horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
heightReference: Cesium.HeightReference.NONE,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
distanceDisplayCondition: labelDistance,
},
});
}
viewer.scene.requestRender();
}
function animateGhostPins(
runtime: RendererRuntime,
layerRef: { current: MapGhostPinLayer | undefined },
layersRef: { current: CesiumMapRendererProps["layers"] },
): () => void {
let frame = 0;
let previousTime = performance.now();
const tick = (time: number) => {
const layer = layerRef.current;
const elapsedSeconds = (time - previousTime) / 1000;
previousTime = time;
if (
layer?.simulation_enabled
&& layersRef.current.targets
&& runtime.currentGhostPins.length > 0
) {
runtime.currentGhostPins = advanceGhostPins(
runtime.currentGhostPins,
layer.anchor,
layer.radius_meters,
elapsedSeconds,
);
updateGhostPinPositions(runtime, layer);
runtime.viewer.scene.requestRender();
}
frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}
function updateGhostPinAnimation(
runtime: RendererRuntime,
active: boolean,
layerRef: { current: MapGhostPinLayer | undefined },
layersRef: { current: CesiumMapRendererProps["layers"] },
): void {
runtime.stopGhostPinAnimation?.();
runtime.stopGhostPinAnimation = active
? animateGhostPins(runtime, layerRef, layersRef)
: null;
}
function updateGhostPinPositions(
runtime: RendererRuntime,
layer: MapGhostPinLayer,
): void {
const { Cesium, ghostPins } = runtime;
for (const pin of runtime.currentGhostPins) {
const entity = ghostPins.entities.getById(pin.id);
if (!entity) continue;
entity.position = ghostPinTopPosition(
runtime,
pin,
layer.presentation.stem_height_meters,
);
if (entity.polyline) {
entity.polyline.positions = ghostPinStemPositions(
runtime,
pin,
layer.presentation.stem_height_meters,
);
}
}
}
function ghostPinTopPosition(
runtime: RendererRuntime,
pin: MapGhostPin,
stemHeightMeters: number,
): CesiumModule.CallbackPositionProperty {
return new runtime.Cesium.CallbackPositionProperty(() => (
runtime.Cesium.Cartesian3.fromDegrees(
pin.longitude,
pin.latitude,
ghostPinGroundHeight(runtime, pin) + stemHeightMeters,
)
), false);
}
function ghostPinStemPositions(
runtime: RendererRuntime,
pin: MapGhostPin,
stemHeightMeters: number,
): CesiumModule.CallbackProperty {
return new runtime.Cesium.CallbackProperty(() => {
const groundHeight = ghostPinGroundHeight(runtime, pin);
return [
runtime.Cesium.Cartesian3.fromDegrees(
pin.longitude,
pin.latitude,
groundHeight,
),
runtime.Cesium.Cartesian3.fromDegrees(
pin.longitude,
pin.latitude,
groundHeight + stemHeightMeters,
),
];
}, false);
}
function ghostPinGroundHeight(
runtime: RendererRuntime,
pin: MapGhostPin,
): number {
const cartographic = runtime.Cesium.Cartographic.fromDegrees(
pin.longitude,
pin.latitude,
);
return runtime.viewer.scene.globe.getHeight(cartographic) ?? 0;
}
function viewAnchor(runtime: RendererRuntime) {
const { Cesium, viewer } = runtime;
const canvas = viewer.scene.canvas;
const center = new Cesium.Cartesian2(
canvas.clientWidth / 2,
canvas.clientHeight / 2,
);
const ray = viewer.camera.getPickRay(center);
const intersection = ray
? viewer.scene.globe.pick(ray, viewer.scene)
: undefined;
const cartographic = intersection
? Cesium.Cartographic.fromCartesian(intersection)
: viewer.camera.positionCartographic;
if (!cartographic) return null;
return {
longitude: Cesium.Math.toDegrees(cartographic.longitude),
latitude: Cesium.Math.toDegrees(cartographic.latitude),
};
}
const elevatedTargetImageCache = new Map<string, string>();
function elevatedTargetImage(
fillColor: CesiumModule.Color,
outlineColor: CesiumModule.Color,
outlineWidthPx: number,
headSizePx: number,
) {
const safeHeadSize = Math.max(1, headSizePx);
const safeOutlineWidth = Math.max(0, outlineWidthPx);
const imageSize = Math.max(1, Math.ceil(safeHeadSize + safeOutlineWidth * 2));
const key = [
fillColor.toCssColorString(),
outlineColor.toCssColorString(),
safeOutlineWidth,
safeHeadSize,
imageSize,
].join("|");
const cached = elevatedTargetImageCache.get(key);
if (cached) return { image: cached, size: imageSize };
const center = imageSize / 2;
const radius = Math.max(0.5, safeHeadSize / 2);
const svg = [
`<svg xmlns="http://www.w3.org/2000/svg" width="${imageSize}" height="${imageSize}" viewBox="0 0 ${imageSize} ${imageSize}">`,
`<circle cx="${center}" cy="${center}" r="${radius}" fill="${fillColor.toCssColorString()}"`,
safeOutlineWidth > 0
? ` stroke="${outlineColor.toCssColorString()}" stroke-width="${safeOutlineWidth}"/>`
: "/>",
"</svg>",
].join("");
const image = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
elevatedTargetImageCache.set(key, image);
return { image, size: imageSize };
}
function rebuildElevatedGrid(
runtime: RendererRuntime,
settings: CesiumMapRendererProps["settings"],
visible: boolean,
): void {
const { Cesium, viewer, grid } = runtime;
const entities = grid.entities;
entities.removeAll();
if (!visible) {
viewer.scene.requestRender();
return;
}
const cameraHeightKm =
Math.max(0, Number(viewer.camera.positionCartographic?.height || 0)) / 1000;
const stepKm =
!settings.grid_lod_enabled ||
cameraHeightKm <= settings.grid_lod_1_max_height_km
? settings.grid_lod_1_step_km
: cameraHeightKm <= settings.grid_lod_2_max_height_km
? settings.grid_lod_2_step_km
: settings.grid_lod_3_step_km;
const safeStepKm = clamp(stepKm, 0.25, 100);
const safeRadiusKm = clamp(settings.grid_radius_km, safeStepKm, 150);
const stepsPerSide = Math.min(
32,
Math.max(1, Math.floor(safeRadiusKm / safeStepKm)),
);
const cameraPosition = viewer.camera.positionCartographic;
const latitude = cameraPosition
? Cesium.Math.toDegrees(cameraPosition.latitude)
: 55.751244;
const longitude = cameraPosition
? Cesium.Math.toDegrees(cameraPosition.longitude)
: 37.618423;
const metersPerLatitudeDegree = 110_574;
const metersPerLongitudeDegree = Math.max(
1,
111_320 * Math.cos(Cesium.Math.toRadians(latitude)),
);
const stepMeters = safeStepKm * 1000;
const radiusMeters = stepsPerSide * stepMeters;
const deltaLatitude = stepMeters / metersPerLatitudeDegree;
const deltaLongitude = stepMeters / metersPerLongitudeDegree;
const radiusLatitude = radiusMeters / metersPerLatitudeDegree;
const radiusLongitude = radiusMeters / metersPerLongitudeDegree;
const lineColor = cssColor(Cesium, settings.grid_color, "#f5f5f5").withAlpha(
clamp(settings.grid_opacity / 100, 0, 1),
);
const dotColor = cssColor(Cesium, settings.grid_dots_color, "#ffffff").withAlpha(
clamp(settings.grid_dots_opacity / 100, 0, 1),
);
const elevation = Math.max(0, settings.grid_height_meters);
for (let index = -stepsPerSide; index <= stepsPerSide; index += 1) {
const nextLatitude = latitude + index * deltaLatitude;
const nextLongitude = longitude + index * deltaLongitude;
entities.add({
polyline: {
positions: [
Cesium.Cartesian3.fromDegrees(
longitude - radiusLongitude,
nextLatitude,
elevation,
),
Cesium.Cartesian3.fromDegrees(
longitude + radiusLongitude,
nextLatitude,
elevation,
),
],
width: clamp(settings.grid_line_width, 1, 8),
material: lineColor,
},
});
entities.add({
polyline: {
positions: [
Cesium.Cartesian3.fromDegrees(
nextLongitude,
latitude - radiusLatitude,
elevation,
),
Cesium.Cartesian3.fromDegrees(
nextLongitude,
latitude + radiusLatitude,
elevation,
),
],
width: clamp(settings.grid_line_width, 1, 8),
material: lineColor,
},
});
}
if (settings.grid_dots_enabled) {
const dotStride = Math.max(
1,
Math.ceil((stepsPerSide * 2 + 1) / 25),
);
for (let row = -stepsPerSide; row <= stepsPerSide; row += dotStride) {
for (
let column = -stepsPerSide;
column <= stepsPerSide;
column += dotStride
) {
entities.add({
position: Cesium.Cartesian3.fromDegrees(
longitude + column * deltaLongitude,
latitude + row * deltaLatitude,
elevation,
),
point: {
pixelSize: clamp(settings.grid_dots_size, 2, 28),
color: dotColor,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
}
}
}
viewer.scene.requestRender();
}
function safeErrorCode(error: unknown): string {
return error instanceof MapRuntimeError ? error.code : "map_provider_unavailable";
}
function cssColor(
Cesium: CesiumNamespace,
value: string,
fallback: string,
): CesiumModule.Color {
return (
Cesium.Color.fromCssColorString(value) ??
Cesium.Color.fromCssColorString(fallback) ??
Cesium.Color.WHITE
);
}
function clamp(value: number, minimum: number, maximum: number): number {
return Math.min(maximum, Math.max(minimum, value));
}