mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 18:22:25 +00:00
Merge upstream main into feat/iss-3d-model
Main's renderer seam (#1760) keeps Cesium inside src/render/cesium/, so the ISS model now draws through the renderer contract: - issModel.js draws the station as an item of a draw-port `models` set (url, position, heading/pitch/roll from its flight axes, scale, minimum pixel size, display range), hands the near range over through the dots' `displayRange`, and reads the eye from the camera port. - issArticulation.js computes each joint's matrix as plain numbers and the Sun from geo/celestial, and hands them over by node name. - The contract's ModelItem gains `nodes`: transforms of a model's named glTF nodes, which the Cesium port writes once the model is ready and again only when they change; a dropped name gets its authored pose back. - issCommand.js asks the frame port for frames and zooms by shortening the camera port's follow offset. - A click on the model is told by its draw hit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
c737a354c4
1129 files changed
+150420
-46238
No files matched your search
+109
-38
@@ -2,20 +2,74 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { createApplication } from './application.js';
|
||||
import { installTrackpadPinchRelay } from '../render/cesium/ctrlWheelZoom.js';
|
||||
import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
installFreeLookHeightLimit,
|
||||
installGlobeInViewRecovery,
|
||||
installTrackpadPinchZoom,
|
||||
} from './viewer.js';
|
||||
import {
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
globeFrameShare,
|
||||
globeOutOfFrame,
|
||||
lookAngleWithinFrame,
|
||||
lookStepLosesGlobe,
|
||||
} from '../globeInView.js';
|
||||
import { installFreeLookHeightLimit } from '../render/cesium/freeLookLimit.js';
|
||||
import { installGlobeInViewRecovery } from './globeInViewRecovery.js';
|
||||
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../globeInView.js';
|
||||
import * as globeInView from '../globeInView.js';
|
||||
import { createCesiumCamera } from '../render/cesium/camera.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { entityFollowTarget } from '../data/followed.js';
|
||||
|
||||
/** The camera port bound over each real Cesium camera a test makes. */
|
||||
const cameraPorts = new WeakMap();
|
||||
|
||||
/**
|
||||
* Bind `viewer` the Cesium renderer's own camera port over its real camera,
|
||||
* with the camera's own `moveStart` and `moveEnd` so a test raises them, and
|
||||
* a frame port that counts render requests on the scene.
|
||||
*/
|
||||
function bindCameraPorts(viewer) {
|
||||
const { camera, scene } = viewer;
|
||||
const noEvent = { addEventListener: () => () => {} };
|
||||
const real = createCesiumCamera({
|
||||
scene: {
|
||||
postUpdate: noEvent,
|
||||
preUpdate: noEvent,
|
||||
get screenSpaceCameraController() {
|
||||
return scene.screenSpaceCameraController;
|
||||
},
|
||||
requestRender: () => scene.requestRender?.(),
|
||||
},
|
||||
camera,
|
||||
report: (error) => {
|
||||
throw error;
|
||||
},
|
||||
}).port;
|
||||
const port = Object.create(real, {
|
||||
on: { value: (event, cb) => camera[event].addEventListener(cb) },
|
||||
});
|
||||
cameraPorts.set(camera, port);
|
||||
bindRenderer(viewer, {
|
||||
camera: port,
|
||||
get canvas() {
|
||||
return scene.canvas;
|
||||
},
|
||||
frame: {
|
||||
on: () => () => {},
|
||||
requestRender: () => scene.requestRender?.(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// The frame measures take a camera pose; these take the test's camera.
|
||||
const poseOf = (camera) => cameraPorts.get(camera).pose();
|
||||
const LOOKS = {
|
||||
lookUp: 'up',
|
||||
lookDown: 'down',
|
||||
lookLeft: 'left',
|
||||
lookRight: 'right',
|
||||
};
|
||||
const globeFrameShare = (camera, options) =>
|
||||
globeInView.globeFrameShare(poseOf(camera), options);
|
||||
const globeOutOfFrame = (camera, options) =>
|
||||
globeInView.globeOutOfFrame(poseOf(camera), options);
|
||||
const lookAngleWithinFrame = (camera, look, angle, options) =>
|
||||
globeInView.lookAngleWithinFrame(poseOf(camera), LOOKS[look], angle, options);
|
||||
const lookStepLosesGlobe = (camera, look, angle, options) =>
|
||||
globeInView.lookStepLosesGlobe(poseOf(camera), LOOKS[look], angle, options);
|
||||
|
||||
const phases = ['Scene', 'Controls', 'Data', 'Tools'];
|
||||
function fixture(overrides = {}) {
|
||||
@@ -235,8 +289,9 @@ test('the separate viewer export imports without constructing a browser viewer',
|
||||
});
|
||||
|
||||
test('the viewer gets the starry sky as an option, which keeps the Sun and Moon', async () => {
|
||||
const { applicationViewerOptions } = await import('./viewer.js');
|
||||
const { StarrySky } = await import('../sky/starrySky.js');
|
||||
const { applicationViewerOptions } =
|
||||
await import('../render/cesium/applicationViewer.js');
|
||||
const { StarrySky } = await import('../render/cesium/starrySky.js');
|
||||
const creditContainer = {};
|
||||
const options = applicationViewerOptions(creditContainer);
|
||||
// CesiumWidget skips scene.sun and scene.moon when skyBox is false.
|
||||
@@ -300,14 +355,13 @@ function pinchFixture({ zoomEventTypes } = {}) {
|
||||
return { viewer, controller, container, handlers, relayed, createEvent };
|
||||
}
|
||||
|
||||
test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs', () => {
|
||||
test('the trackpad pinch relay leaves the zoom bindings and plain or line-mode wheels alone', () => {
|
||||
const original = [1, 2, 3];
|
||||
const f = pinchFixture({ zoomEventTypes: original });
|
||||
const dispose = installTrackpadPinchZoom(f.viewer, {
|
||||
const dispose = installTrackpadPinchRelay(f.viewer, {
|
||||
createWheelEvent: (_type, init) => f.createEvent(init),
|
||||
});
|
||||
assert.deepEqual(f.controller.zoomEventTypes.slice(0, 3), original);
|
||||
assert.equal(f.controller.zoomEventTypes.length, 4);
|
||||
assert.equal(f.controller.zoomEventTypes, original);
|
||||
|
||||
const plain = f.createEvent({ deltaY: 2 });
|
||||
f.container.emit(plain);
|
||||
@@ -325,7 +379,7 @@ test('trackpad pinch adds the Ctrl+wheel binding without replacing Cesium inputs
|
||||
|
||||
test('trackpad pinch relays pixel deltas once with bounded amplification', () => {
|
||||
const f = pinchFixture({ zoomEventTypes: [1, 2, 3] });
|
||||
installTrackpadPinchZoom(f.viewer, {
|
||||
installTrackpadPinchRelay(f.viewer, {
|
||||
createWheelEvent: (_type, init) => f.createEvent(init),
|
||||
});
|
||||
|
||||
@@ -345,7 +399,7 @@ test('trackpad pinch relays pixel deltas once with bounded amplification', () =>
|
||||
|
||||
test('trackpad pinch falls back to the original event when relay construction fails', () => {
|
||||
const f = pinchFixture({ zoomEventTypes: [1, 2, 3] });
|
||||
installTrackpadPinchZoom(f.viewer, {
|
||||
installTrackpadPinchRelay(f.viewer, {
|
||||
createWheelEvent() {
|
||||
throw new Error('unsupported');
|
||||
},
|
||||
@@ -382,7 +436,10 @@ function freeLookFixture({ enableLook = true, height = 0 } = {}) {
|
||||
|
||||
test('free look follows camera height and is restored on dispose', () => {
|
||||
const f = freeLookFixture({ height: 500 });
|
||||
const dispose = installFreeLookHeightLimit(f.viewer);
|
||||
const dispose = installFreeLookHeightLimit(
|
||||
f.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
assert.equal(f.controller.enableLook, true);
|
||||
|
||||
f.frame(FREE_LOOK_MAX_HEIGHT_METERS + 1);
|
||||
@@ -402,7 +459,10 @@ test('free look follows camera height and is restored on dispose', () => {
|
||||
test('drags that start on the stars orbit above the free-look height', () => {
|
||||
// Below Cesium's trackball height such a drag turns the camera in place.
|
||||
const f = freeLookFixture({ height: 500 });
|
||||
const dispose = installFreeLookHeightLimit(f.viewer);
|
||||
const dispose = installFreeLookHeightLimit(
|
||||
f.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
assert.equal(
|
||||
f.controller.minimumTrackBallHeight,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
@@ -412,7 +472,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
|
||||
|
||||
const lower = freeLookFixture({ height: 500 });
|
||||
lower.controller.minimumTrackBallHeight = 500_000;
|
||||
const disposeLower = installFreeLookHeightLimit(lower.viewer);
|
||||
const disposeLower = installFreeLookHeightLimit(
|
||||
lower.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
assert.equal(
|
||||
lower.controller.minimumTrackBallHeight,
|
||||
500_000,
|
||||
@@ -422,7 +485,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
|
||||
assert.equal(lower.controller.minimumTrackBallHeight, 500_000);
|
||||
|
||||
const later = freeLookFixture({ height: 500 });
|
||||
const disposeLater = installFreeLookHeightLimit(later.viewer);
|
||||
const disposeLater = installFreeLookHeightLimit(
|
||||
later.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
later.controller.minimumTrackBallHeight = 2_000_000;
|
||||
disposeLater();
|
||||
assert.equal(
|
||||
@@ -434,7 +500,10 @@ test('drags that start on the stars orbit above the free-look height', () => {
|
||||
|
||||
test('free look keeps a setting other code makes after it is installed', () => {
|
||||
const f = freeLookFixture({ height: 500 });
|
||||
const dispose = installFreeLookHeightLimit(f.viewer);
|
||||
const dispose = installFreeLookHeightLimit(
|
||||
f.viewer,
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
);
|
||||
f.controller.enableLook = false;
|
||||
f.frame(10);
|
||||
assert.equal(f.controller.enableLook, false, 'turned off stays off');
|
||||
@@ -454,7 +523,7 @@ test('free look keeps a setting other code makes after it is installed', () => {
|
||||
|
||||
test('free look stays off when the viewer had it disabled', () => {
|
||||
const f = freeLookFixture({ enableLook: false, height: 500 });
|
||||
installFreeLookHeightLimit(f.viewer);
|
||||
installFreeLookHeightLimit(f.viewer, FREE_LOOK_MAX_HEIGHT_METERS);
|
||||
f.frame(10);
|
||||
assert.equal(f.controller.enableLook, false);
|
||||
});
|
||||
@@ -479,7 +548,9 @@ function realCamera({ width = 1600, height = 900, mode } = {}) {
|
||||
};
|
||||
const camera = new Cesium.Camera(scene);
|
||||
camera.frustum.aspectRatio = width / height;
|
||||
return { camera, scene, viewer: { camera, scene } };
|
||||
const viewer = { camera, scene };
|
||||
bindCameraPorts(viewer);
|
||||
return { camera, scene, viewer };
|
||||
}
|
||||
|
||||
function aim(
|
||||
@@ -573,7 +644,8 @@ test('a move that ends with the globe out of frame turns back to nadir', () => {
|
||||
Cesium.Cartesian3.equalsEpsilon(camera.positionWC, position, 0, 1e-3),
|
||||
);
|
||||
assert.equal(globeOutOfFrame(camera), false);
|
||||
assert.equal(scene.renders, 1);
|
||||
// One render for the new view, one the recovery asks for itself.
|
||||
assert.equal(scene.renders, 2, 'the turned view is drawn');
|
||||
|
||||
// Looking up near the ground, then zoomed out past the limit.
|
||||
aim(camera, { alt: 3_834_000, pitch: 10 });
|
||||
@@ -602,7 +674,7 @@ function moveEndKeepsView(camera) {
|
||||
return Cesium.Cartesian3.equalsEpsilon(camera.directionWC, direction, 1e-9);
|
||||
}
|
||||
|
||||
test('globe recovery leaves partial, low, locked and 2D views alone', () => {
|
||||
test('globe recovery leaves partial, low, locked and following views alone', () => {
|
||||
for (const view of partialGlobeViews) {
|
||||
const { camera, viewer } = realCamera();
|
||||
installGlobeInViewRecovery(viewer);
|
||||
@@ -626,19 +698,18 @@ test('globe recovery leaves partial, low, locked and 2D views alone', () => {
|
||||
assert.equal(globeOutOfFrame(locked.camera), true);
|
||||
assert.ok(moveEndKeepsView(locked.camera), 'locked camera');
|
||||
|
||||
// Tracking an entity that has no position yet keeps an identity transform.
|
||||
// Following an entity that has no position yet keeps an identity transform.
|
||||
const tracked = realCamera();
|
||||
tracked.viewer.trackedEntity = { id: 'pending-fix' };
|
||||
const pending = entityFollowTarget(
|
||||
{ id: 'pending-fix' },
|
||||
{ position: () => null },
|
||||
);
|
||||
Object.defineProperty(cameraPorts.get(tracked.camera), 'followed', {
|
||||
get: () => pending,
|
||||
});
|
||||
installGlobeInViewRecovery(tracked.viewer);
|
||||
aim(tracked.camera, reportedStuckView);
|
||||
assert.ok(moveEndKeepsView(tracked.camera), 'tracked camera');
|
||||
|
||||
const flat = realCamera({ mode: Cesium.SceneMode.COLUMBUS_VIEW });
|
||||
installGlobeInViewRecovery(flat.viewer);
|
||||
flat.scene.mode = Cesium.SceneMode.SCENE3D;
|
||||
aim(flat.camera, reportedStuckView);
|
||||
flat.scene.mode = Cesium.SceneMode.COLUMBUS_VIEW;
|
||||
assert.ok(moveEndKeepsView(flat.camera), 'Columbus view');
|
||||
});
|
||||
|
||||
test('the look limit from orbit tolerates grid noise and never reaches zero', () => {
|
||||
|
||||
Vendored
+28
-20
@@ -1,8 +1,11 @@
|
||||
import { catalogControlServices } from './catalog.js';
|
||||
import { StyleManager } from '../ui/composition.js';
|
||||
import { flyToAustin } from '../camera.js';
|
||||
import { installZoomOutGuard } from './zoomOutGuard.js';
|
||||
import { applyStartView, START_VIEW } from '../camera.js';
|
||||
import { initCockpitCloudEffects } from '../cockpitCloudEffects.js';
|
||||
import { createViewSky } from '../viewSky.js';
|
||||
import { findGlobe } from '../render/rendererOf.js';
|
||||
import { useDisplayStore } from '../ui/stores/display.js';
|
||||
import { applicationPinia } from '../ui/vueRuntime.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
/**
|
||||
@@ -10,12 +13,13 @@ import { t } from '../i18n/index.js';
|
||||
* opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host
|
||||
* whose address does not carry one. `localePicker: false` removes the language
|
||||
* picker, for a host that offers its own language choice (`switchLocale` from
|
||||
* the `./i18n` entry).
|
||||
* the `./i18n` entry). `startView` is where the camera starts (the whole
|
||||
* planet by default; a host may pass a city); a shared view flies from there.
|
||||
* `services.cockpitSubjects` adds the application's own first-person subjects
|
||||
* to the Cockpit (src/cockpitSubjectProviders.js).
|
||||
*/
|
||||
export function createApplicationControls({
|
||||
scene: { viewer, mapStackController, operations },
|
||||
scene: { viewer, mapStackController, operations, viewerDrawsEntity },
|
||||
loaderStatus,
|
||||
Controls = StyleManager,
|
||||
services,
|
||||
@@ -24,7 +28,10 @@ export function createApplicationControls({
|
||||
defer,
|
||||
initialShareCode = null,
|
||||
localePicker = true,
|
||||
startView = START_VIEW,
|
||||
}) {
|
||||
// Every boot starts from the same view, before share restoration flies on.
|
||||
applyStartView(viewer, startView);
|
||||
// Initialize the style manager (post-processing, HUD, locations, share links)
|
||||
const styleManager = new Controls(viewer, {
|
||||
services: {
|
||||
@@ -34,6 +41,8 @@ export function createApplicationControls({
|
||||
fetchRegionalBrief: (...args) =>
|
||||
operations.requests.regional.getBrief(...args),
|
||||
...catalogControlServices(catalog),
|
||||
// Whether an entity is one of the viewer's own; the scene answers it.
|
||||
viewerDrawsEntity: viewerDrawsEntity ?? services?.viewerDrawsEntity,
|
||||
},
|
||||
requestServices: operations.requests,
|
||||
mapStackController,
|
||||
@@ -45,28 +54,27 @@ export function createApplicationControls({
|
||||
defer(() => styleManager.orbitController.stop());
|
||||
defer(() => styleManager.hud.destroy());
|
||||
defer(() => styleManager.dispose());
|
||||
defer(
|
||||
installZoomOutGuard(viewer, {
|
||||
subscribeCameraHandoff: (listener) =>
|
||||
styleManager.subscribeCameraHandoff?.(listener),
|
||||
}),
|
||||
);
|
||||
// The previous multi-canvas weather compositor remains disabled. Cockpit
|
||||
// clouds use a separate, capped low-resolution GPU pass that never attaches
|
||||
// Cesium fog or post-process stages and is fully stopped in map mode.
|
||||
const weatherEffects = null;
|
||||
const cockpitCloudEffects = initCockpitCloudEffects(viewer, {
|
||||
weatherService: operations.requests.weather,
|
||||
});
|
||||
// Where the renderer draws weather, it draws the cockpit's clouds too.
|
||||
const cockpitCloudEffects = findGlobe(viewer)?.weather
|
||||
? null
|
||||
: initCockpitCloudEffects(viewer, {
|
||||
weatherService: operations.requests.weather,
|
||||
});
|
||||
defer(() => cockpitCloudEffects?.destroy());
|
||||
// The atmosphere, sun lighting, sun, moon, stars and Milky Way the user
|
||||
// chooses in the Display panel.
|
||||
const viewSky = createViewSky(viewer, {
|
||||
store: useDisplayStore(applicationPinia()),
|
||||
});
|
||||
defer(() => viewSky.destroy());
|
||||
|
||||
// If no share link state, do default fly-to Austin
|
||||
if (!styleManager.hasShareState) {
|
||||
loaderStatus.textContent = t('Flying to Austin, TX...');
|
||||
defer(flyToAustin(viewer));
|
||||
} else {
|
||||
loaderStatus.textContent = t('Restoring shared view...');
|
||||
}
|
||||
loaderStatus.textContent = styleManager.hasShareState
|
||||
? t('Restoring shared view...')
|
||||
: t('Loading');
|
||||
|
||||
return { styleManager, weatherEffects, cockpitCloudEffects };
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import test, { after, before } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import '../testSupport/stubMgrs.mjs';
|
||||
import { installVueDom } from '../testSupport/vueDom.mjs';
|
||||
import { MAXIMUM_ZOOM_DISTANCE_M } from './zoomOutGuard.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
const { createApplicationControls } = await import('./controls.js');
|
||||
|
||||
@@ -13,35 +12,20 @@ before(() => {
|
||||
});
|
||||
after(() => uninstallDom());
|
||||
|
||||
test('application controls install the zoom-out guard and remove it on teardown', () => {
|
||||
const canvas = document.createElement('canvas');
|
||||
const controller = { maximumZoomDistance: Infinity };
|
||||
const scene = {
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
screenSpaceCameraController: controller,
|
||||
preRender: new Cesium.Event(),
|
||||
postUpdate: new Cesium.Event(),
|
||||
};
|
||||
const camera = {
|
||||
position: Cesium.Cartesian3.fromDegrees(0, 0, 1_000_000),
|
||||
positionCartographic: { height: 1_000_000 },
|
||||
};
|
||||
const viewer = { scene, camera, canvas };
|
||||
const handoffs = new Set();
|
||||
test('the application controls start and stop', () => {
|
||||
class Controls {
|
||||
hasShareState = true;
|
||||
orbitController = { stop() {} };
|
||||
hud = { destroy() {} };
|
||||
dispose() {}
|
||||
subscribeCameraHandoff(listener) {
|
||||
handoffs.add(listener);
|
||||
return () => handoffs.delete(listener);
|
||||
}
|
||||
}
|
||||
const cleanups = [];
|
||||
createApplicationControls({
|
||||
scene: {
|
||||
viewer,
|
||||
viewer: bindFakeCesiumCamera({
|
||||
isDestroyed: () => false,
|
||||
camera: { setView() {} },
|
||||
}),
|
||||
mapStackController: {},
|
||||
operations: {
|
||||
surface: { controlServices: {} },
|
||||
@@ -54,15 +38,5 @@ test('application controls install the zoom-out guard and remove it on teardown'
|
||||
catalog: { get: (id) => ({ id }) },
|
||||
defer: (cleanup) => cleanups.push(cleanup),
|
||||
});
|
||||
|
||||
assert.equal(controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
|
||||
assert.equal(scene.preRender.numberOfListeners, 1);
|
||||
assert.equal(scene.postUpdate.numberOfListeners, 1);
|
||||
assert.equal(handoffs.size, 1);
|
||||
|
||||
for (const cleanup of cleanups.reverse()) cleanup();
|
||||
assert.equal(controller.maximumZoomDistance, Infinity);
|
||||
assert.equal(scene.preRender.numberOfListeners, 0);
|
||||
assert.equal(scene.postUpdate.numberOfListeners, 0);
|
||||
assert.equal(handoffs.size, 0);
|
||||
});
|
||||
+1
-1
@@ -15,7 +15,7 @@ export function createApplicationData({
|
||||
const dataManager = new LayerLifecycle(viewer, {
|
||||
allowQaRegistration,
|
||||
// A panel's host may report it hidden while it is on screen; its layers
|
||||
// keep polling (see keepPanelRendering in embed.js).
|
||||
// keep polling (see keepPanelRendering in app/panelRendering.js).
|
||||
visibilityTarget: panelAwareVisibility(document),
|
||||
getSourceAvailability: catalog?.getSourceAvailability,
|
||||
});
|
||||
|
||||
+24
-65
@@ -11,13 +11,14 @@
|
||||
* embedded or not.
|
||||
*/
|
||||
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
announceNavigationAuthority,
|
||||
watchCameraOwner,
|
||||
} from '../navigationPolicy.js';
|
||||
import { toRadians } from '../geo/index.js';
|
||||
import { t, translateKnown } from '../i18n/index.js';
|
||||
import { GOOGLE_LABEL } from '../layers/streetLevel/providers/google/policy.js';
|
||||
import { cameraOf } from '../render/rendererOf.js';
|
||||
import {
|
||||
annotationsFromParams,
|
||||
createView,
|
||||
@@ -69,7 +70,8 @@ function isFreshPanelResult() {
|
||||
|
||||
/**
|
||||
* `doc`'s visibility for work that pauses in a hidden page. A panel's host
|
||||
* may report it hidden while it is on screen (see keepPanelRendering), so an
|
||||
* may report it hidden while it is on screen (see keepPanelRendering in
|
||||
* render/cesium/panelRendering.js), so an
|
||||
* inline panel always reads as visible.
|
||||
*/
|
||||
export function panelAwareVisibility(doc = globalThis.document) {
|
||||
@@ -89,52 +91,6 @@ export function panelAwareVisibility(doc = globalThis.document) {
|
||||
};
|
||||
}
|
||||
|
||||
// A panel keeps drawing at about this rate when its host stops animation
|
||||
// frames; see keepPanelRendering.
|
||||
const PANEL_FRAME_MS = 33;
|
||||
const MISSED_FRAMES_MS = 250;
|
||||
|
||||
/**
|
||||
* Keep the globe drawing in an inline panel. Some hosts report a panel on
|
||||
* screen as hidden, which stops the browser's animation frames and with them
|
||||
* Cesium's render loop; while frames stop arriving, draw from a timer.
|
||||
* Returns a function that stops it.
|
||||
*/
|
||||
export function keepPanelRendering(
|
||||
viewer,
|
||||
{ windowRef = globalThis.window, now = () => performance.now() } = {},
|
||||
) {
|
||||
let lastFrame = now();
|
||||
let frameRequest = null;
|
||||
const onFrame = () => {
|
||||
lastFrame = now();
|
||||
frameRequest = windowRef.requestAnimationFrame(onFrame);
|
||||
};
|
||||
frameRequest = windowRef.requestAnimationFrame(onFrame);
|
||||
// Cesium stops its render loop after a render error, and the timer stops
|
||||
// with it; Retry restarts both. The render failure notice logs the error
|
||||
// (src/ui/renderFailure.js).
|
||||
const timer = windowRef.setInterval(() => {
|
||||
if (
|
||||
viewer.useDefaultRenderLoop === false ||
|
||||
now() - lastFrame < MISSED_FRAMES_MS ||
|
||||
viewer.isDestroyed?.()
|
||||
)
|
||||
return;
|
||||
try {
|
||||
viewer.resize();
|
||||
viewer.render();
|
||||
} catch {
|
||||
// Raised as a render error by now (src/ui/renderFailure.js), which
|
||||
// stops this timer; thrown on, it would only reach the host page.
|
||||
}
|
||||
}, PANEL_FRAME_MS);
|
||||
return () => {
|
||||
windowRef.clearInterval(timer);
|
||||
windowRef.cancelAnimationFrame(frameRequest);
|
||||
};
|
||||
}
|
||||
|
||||
const delay = (ms, signal) =>
|
||||
new Promise((resolve) => {
|
||||
const timer = setTimeout(resolve, ms);
|
||||
@@ -152,21 +108,19 @@ const delay = (ms, signal) =>
|
||||
function flyTo(viewer, camera) {
|
||||
announceNavigationAuthority('embed-view');
|
||||
return new Promise((resolve) => {
|
||||
viewer.camera.flyTo({
|
||||
destination: Cesium.Cartesian3.fromDegrees(
|
||||
camera.lon,
|
||||
camera.lat,
|
||||
camera.altitude_m,
|
||||
),
|
||||
orientation: {
|
||||
heading: Cesium.Math.toRadians(camera.heading_deg),
|
||||
pitch: Cesium.Math.toRadians(camera.pitch_deg),
|
||||
roll: 0,
|
||||
cameraOf(viewer).flyTo(
|
||||
{ lon: camera.lon, lat: camera.lat, height: camera.altitude_m },
|
||||
{
|
||||
orientation: {
|
||||
heading: toRadians(camera.heading_deg),
|
||||
pitch: toRadians(camera.pitch_deg),
|
||||
roll: 0,
|
||||
},
|
||||
durationS: FLIGHT_SECONDS,
|
||||
onComplete: () => resolve(true),
|
||||
onCancel: () => resolve(false),
|
||||
},
|
||||
duration: FLIGHT_SECONDS,
|
||||
complete: () => resolve(true),
|
||||
cancel: () => resolve(false),
|
||||
});
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -314,6 +268,9 @@ export async function applyView(
|
||||
/**
|
||||
* Install embed mode when the page asks for it, and draw any annotations the
|
||||
* opening link carries. Returns a function that removes the message handler.
|
||||
* `keepRendering({windowRef})` keeps the globe drawing in an inline panel
|
||||
* whose host stops animation frames, and returns a function that stops it;
|
||||
* the application scene gives it (`keepPanelRendering`).
|
||||
*/
|
||||
export function installViews({
|
||||
shell,
|
||||
@@ -321,6 +278,7 @@ export function installViews({
|
||||
dataManager,
|
||||
run,
|
||||
signal,
|
||||
keepRendering = null,
|
||||
terrain = null,
|
||||
location = globalThis.location,
|
||||
windowRef = globalThis.window,
|
||||
@@ -433,9 +391,10 @@ export function installViews({
|
||||
|
||||
windowRef.document.body.classList.add('ui-embed');
|
||||
shell.setCleanView?.(true);
|
||||
const stopRendering = isEmbeddedInline()
|
||||
? keepPanelRendering(viewer, { windowRef })
|
||||
: () => {};
|
||||
const stopRendering =
|
||||
isEmbeddedInline() && keepRendering
|
||||
? keepRendering({ windowRef })
|
||||
: () => {};
|
||||
// A framing page talks to the app across frames; an inline panel shares
|
||||
// the page with it and talks through the page's own window.
|
||||
const peer = isEmbeddedInline() ? windowRef : windowRef.parent;
|
||||
|
||||
+11
-57
@@ -1,10 +1,10 @@
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
applyView,
|
||||
installViews,
|
||||
isEmbedded,
|
||||
keepPanelRendering,
|
||||
panelAwareVisibility,
|
||||
} from './embed.js';
|
||||
import { LayerLifecycle } from '../data/lifecycle.js';
|
||||
@@ -12,7 +12,7 @@ import { createView, viewToParams } from '../view/index.js';
|
||||
|
||||
const fakeViewer = () => {
|
||||
const flights = [];
|
||||
return {
|
||||
return bindFakeCesiumCamera({
|
||||
flights,
|
||||
camera: {
|
||||
flyTo(options) {
|
||||
@@ -20,7 +20,7 @@ const fakeViewer = () => {
|
||||
options.complete();
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
};
|
||||
const fakeLayers = (enabled) => ({
|
||||
getAll: () =>
|
||||
@@ -329,6 +329,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn
|
||||
globalThis.GEV_EMBED_INLINE = true;
|
||||
try {
|
||||
assert.equal(isEmbedded({ search: '' }), true);
|
||||
const kept = [];
|
||||
const remove = installViews({
|
||||
shell: { initialRestorePromise: Promise.resolve() },
|
||||
viewer: fakeViewer(),
|
||||
@@ -336,7 +337,13 @@ test('an app loaded inline into a panel page talks through its own window', asyn
|
||||
run: recorder().run,
|
||||
location: { search: '', hash: '' },
|
||||
windowRef,
|
||||
// The scene's panel rendering, kept on while the views are installed.
|
||||
keepRendering: (options) => {
|
||||
kept.push(options.windowRef === windowRef);
|
||||
return () => kept.push('stopped');
|
||||
},
|
||||
});
|
||||
assert.deepEqual(kept, [true]);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.deepEqual(posted, [{ type: 'gev:ready' }]);
|
||||
const event = new Event('message');
|
||||
@@ -349,6 +356,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn
|
||||
assert.equal(posted[1].id, 7);
|
||||
assert.equal(posted[1].ok, true);
|
||||
remove();
|
||||
assert.deepEqual(kept, [true, 'stopped']);
|
||||
} finally {
|
||||
delete globalThis.GEV_EMBED_INLINE;
|
||||
}
|
||||
@@ -427,60 +435,6 @@ test('annotations in a link are drawn after it restores, embedded or not', async
|
||||
]);
|
||||
});
|
||||
|
||||
test('a panel keeps drawing from a timer while animation frames stop', () => {
|
||||
let clock = 0;
|
||||
let tick = null;
|
||||
let frame = null;
|
||||
const windowRef = {
|
||||
requestAnimationFrame: (fn) => ((frame = fn), 1),
|
||||
cancelAnimationFrame: () => (frame = null),
|
||||
setInterval: (fn) => ((tick = fn), 1),
|
||||
clearInterval: () => (tick = null),
|
||||
};
|
||||
const drawn = [];
|
||||
const viewer = {
|
||||
resize: () => drawn.push('resize'),
|
||||
render: () => drawn.push('render'),
|
||||
};
|
||||
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
|
||||
// Frames arrive: the render loop draws, so the timer does nothing.
|
||||
clock = 100;
|
||||
frame();
|
||||
tick();
|
||||
assert.deepEqual(drawn, []);
|
||||
// Frames stop, as in a panel its host reports hidden: the timer draws.
|
||||
clock = 400;
|
||||
tick();
|
||||
assert.deepEqual(drawn, ['resize', 'render']);
|
||||
stop();
|
||||
assert.equal(tick, null);
|
||||
assert.equal(frame, null);
|
||||
});
|
||||
|
||||
test('a panel stops drawing while its render loop is stopped', () => {
|
||||
let tick = null;
|
||||
const windowRef = {
|
||||
requestAnimationFrame: () => 1,
|
||||
cancelAnimationFrame() {},
|
||||
setInterval: (fn) => ((tick = fn), 1),
|
||||
clearInterval() {},
|
||||
};
|
||||
const drawn = [];
|
||||
const viewer = { resize() {}, render: () => drawn.push('render') };
|
||||
let clock = 0;
|
||||
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
|
||||
// Cesium stops its render loop after a render error.
|
||||
viewer.useDefaultRenderLoop = false;
|
||||
clock = 1000;
|
||||
tick();
|
||||
assert.deepEqual(drawn, []);
|
||||
// Retry restarts it, and the timer draws again.
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
tick();
|
||||
assert.deepEqual(drawn, ['render']);
|
||||
stop();
|
||||
});
|
||||
|
||||
test('a followed aircraft owns the camera, and cockpit view is entered after it', async () => {
|
||||
const viewer = fakeViewer();
|
||||
const { calls, run } = recorder();
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* @module app/globeInViewRecovery
|
||||
* @description Turns the camera back to the planet when a move ends looking
|
||||
* away from it, through the renderer's camera and frame ports.
|
||||
*/
|
||||
import { PI_OVER_TWO } from '../geo/vector.js';
|
||||
import {
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
globeOutOfFrame,
|
||||
isFreeGlobeCamera,
|
||||
} from '../globeInView.js';
|
||||
import { canvasOf, findCamera, findFrame } from '../render/rendererOf.js';
|
||||
|
||||
/** Whether two vectors agree to `tolerance` in every component. */
|
||||
const within = (a, b, tolerance) =>
|
||||
Math.abs(a.x - b.x) <= tolerance &&
|
||||
Math.abs(a.y - b.y) <= tolerance &&
|
||||
Math.abs(a.z - b.z) <= tolerance;
|
||||
|
||||
// How often a moving camera is sampled to see whether it has come to rest, how
|
||||
// far a pose may drift between samples and still count as at rest, and how
|
||||
// long after the camera last moved the check gives up if the camera never
|
||||
// raises moveEnd.
|
||||
const SETTLE_SAMPLE_MS = 250;
|
||||
const SETTLE_POSITION_TOLERANCE_M = 1e-3;
|
||||
const SETTLE_DIRECTION_TOLERANCE = 1e-9;
|
||||
const SETTLE_GIVE_UP_MS = 5 * 60_000;
|
||||
|
||||
/**
|
||||
* Turn the camera back to the planet when a move ends above `minHeight` with
|
||||
* no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about
|
||||
* one sample cell thick can count as none), and return the disposer. Views with
|
||||
* more surface, such as an oblique orbital shot, are left as they are. This
|
||||
* catches a saved or shared view that looked away, or any other move that ends
|
||||
* looking away from the planet.
|
||||
* Heading and position are kept. Following cameras, locked ones (a target's
|
||||
* frame), a camera flight in progress, a pointer held down on the canvas
|
||||
* (a drag held still), and any time `paused`
|
||||
* returns true (an authored scene playing) are left alone; a check they defer
|
||||
* runs once they end, however long they last.
|
||||
* `keyholeRadius`
|
||||
* returns the radius of the visible circle when a scope mask hides the rest of
|
||||
* the frame (see `globeFrameShare`), or 0; it is read at every check.
|
||||
*
|
||||
* The camera's `moveEnd` alone is not enough: the default renderer compares
|
||||
* the camera with the last frame's to the last rounding error, and at some of
|
||||
* these poses the camera drifts by a rounding error every frame, so it never
|
||||
* sees it stop.
|
||||
* So each `moveStart` also starts a check of its own that samples the pose
|
||||
* every 250 ms, with a tolerance for that drift, and once the pose has held
|
||||
* for half a second after moving runs the same recovery. It keeps watching
|
||||
* until the camera raises `moveEnd`, since under that drift it raises no new
|
||||
* `moveStart` for a later move, and gives up five minutes after the camera
|
||||
* last moved.
|
||||
* `setTimeout` and `clearTimeout` can be injected for tests.
|
||||
*/
|
||||
export function installGlobeInViewRecovery(
|
||||
viewer,
|
||||
{
|
||||
minHeight = FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
keyholeRadius = () => 0,
|
||||
paused = () => false,
|
||||
setTimeout: schedule = globalThis.setTimeout,
|
||||
clearTimeout: unschedule = globalThis.clearTimeout,
|
||||
} = {},
|
||||
) {
|
||||
const camera = findCamera(viewer);
|
||||
if (!camera) throw new TypeError('A viewer with a camera is required');
|
||||
|
||||
// A pointer held on the globe is a gesture in progress, even when it holds
|
||||
// still for half a second: the check waits until every pointer pressed on
|
||||
// it (each finger of a pinch) is released. A release the page never sees,
|
||||
// outside the window, is taken as given when the window loses focus, the
|
||||
// page is hidden, the canvas loses the pointer's capture, or the pointer
|
||||
// moves with no button down.
|
||||
const canvas = canvasOf(viewer);
|
||||
const releaseTarget = canvas?.ownerDocument ?? canvas;
|
||||
const releaseWindow = canvas?.ownerDocument?.defaultView;
|
||||
const heldPointers = new Set();
|
||||
const onPointerDown = (event) => heldPointers.add(event?.pointerId);
|
||||
const onPointerUp = (event) => heldPointers.delete(event?.pointerId);
|
||||
const onPointerMove = (event) => {
|
||||
if (event?.buttons === 0) heldPointers.delete(event.pointerId);
|
||||
};
|
||||
const releaseAll = () => heldPointers.clear();
|
||||
const onVisibilityChange = () => {
|
||||
if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll();
|
||||
};
|
||||
const listeners = [
|
||||
[canvas, 'pointerdown', onPointerDown],
|
||||
[canvas, 'lostpointercapture', onPointerUp],
|
||||
[releaseTarget, 'pointerup', onPointerUp],
|
||||
[releaseTarget, 'pointercancel', onPointerUp],
|
||||
[releaseTarget, 'pointermove', onPointerMove],
|
||||
[canvas?.ownerDocument, 'visibilitychange', onVisibilityChange],
|
||||
[releaseWindow, 'blur', releaseAll],
|
||||
];
|
||||
for (const [target, type, listener] of listeners)
|
||||
target?.addEventListener?.(type, listener);
|
||||
|
||||
// Returns false while a flight, a paused scene or a held pointer defers the
|
||||
// check, so the caller can try again once it ends.
|
||||
const recover = () => {
|
||||
if (!isFreeGlobeCamera(viewer)) return true;
|
||||
if (camera.flying || paused() || heldPointers.size > 0) return false;
|
||||
const pose = camera.pose();
|
||||
if (
|
||||
!(pose.height > minHeight) ||
|
||||
!globeOutOfFrame(pose, { keyholeRadius: keyholeRadius() })
|
||||
)
|
||||
return true;
|
||||
camera.setView({
|
||||
orientation: { heading: pose.heading, pitch: -PI_OVER_TWO, roll: 0 },
|
||||
});
|
||||
findFrame(viewer)?.requestRender?.('globe-in-view');
|
||||
return true;
|
||||
};
|
||||
|
||||
let lastPosition = null;
|
||||
let lastDirection = null;
|
||||
const remember = () => {
|
||||
({ position: lastPosition, direction: lastDirection } = camera.pose());
|
||||
};
|
||||
let settleTimer = null;
|
||||
let settleElapsed = 0;
|
||||
let restingSamples = 0;
|
||||
let movedSinceCheck = false;
|
||||
const stopSettling = () => {
|
||||
if (settleTimer !== null) unschedule(settleTimer);
|
||||
settleTimer = null;
|
||||
};
|
||||
const sample = () => {
|
||||
settleTimer = null;
|
||||
settleElapsed += SETTLE_SAMPLE_MS;
|
||||
const now = camera.pose();
|
||||
const atRest =
|
||||
within(now.position, lastPosition, SETTLE_POSITION_TOLERANCE_M) &&
|
||||
within(now.direction, lastDirection, SETTLE_DIRECTION_TOLERANCE);
|
||||
restingSamples = atRest ? restingSamples + 1 : 0;
|
||||
if (!atRest) {
|
||||
movedSinceCheck = true;
|
||||
settleElapsed = 0;
|
||||
}
|
||||
// Two quiet samples in a row after a move: at rest for half a second, as
|
||||
// for moveEnd.
|
||||
if (restingSamples >= 2 && movedSinceCheck) {
|
||||
if (recover()) movedSinceCheck = false;
|
||||
// A flight or a playing scene bounds its own deferral.
|
||||
else settleElapsed = 0;
|
||||
}
|
||||
if (settleElapsed >= SETTLE_GIVE_UP_MS) return;
|
||||
remember();
|
||||
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
|
||||
};
|
||||
const startSettling = () => {
|
||||
stopSettling();
|
||||
settleElapsed = 0;
|
||||
restingSamples = 0;
|
||||
movedSinceCheck = true;
|
||||
remember();
|
||||
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
|
||||
};
|
||||
const removeMoveEnd = camera.on('moveEnd', () => {
|
||||
if (recover()) stopSettling();
|
||||
// Deferred: keep sampling so the check runs once the flight or scene ends.
|
||||
else if (settleTimer === null) startSettling();
|
||||
});
|
||||
const removeMoveStart = camera.on('moveStart', startSettling);
|
||||
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
stopSettling();
|
||||
removeMoveEnd();
|
||||
removeMoveStart();
|
||||
for (const [target, type, listener] of listeners)
|
||||
target?.removeEventListener?.(type, listener);
|
||||
heldPointers.clear();
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createDroneAirspaceLayer } from '../../layers/droneAirspace/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
|
||||
/** Wire FAA special-use airspace into the application catalog. */
|
||||
export function createApplicationDroneAirspace(options) {
|
||||
@@ -13,10 +11,7 @@ export function createApplicationDroneAirspace(options) {
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFirmsHeatmapLayer as createLayer } from '../../layers/firms/index.js';
|
||||
import * as render from '../../renderGovernor.js';
|
||||
import * as sprites from '../../data/spriteOrder.js';
|
||||
@@ -29,8 +28,5 @@ export function createApplicationFirms({ surface, ...options }) {
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
screenSpaceEventHandlerFactory:
|
||||
options.screenSpaceEventHandlerFactory ??
|
||||
((viewer) => new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)),
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createGhostMapsLayer } from '../../layers/ghostMaps/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
|
||||
/** Wire the S2 Underground GhostMaps layer into the application catalog. */
|
||||
export function createApplicationGhostMaps(options) {
|
||||
@@ -14,10 +12,7 @@ export function createApplicationGhostMaps(options) {
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
createFirePerimetersLayer,
|
||||
createInciwebIndexSource,
|
||||
@@ -6,7 +5,6 @@ import {
|
||||
} from '../../layers/perimeters/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
|
||||
/** Wire WFIGS fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters(options) {
|
||||
@@ -20,10 +18,7 @@ export function createApplicationFirePerimeters(options) {
|
||||
inciwebSource: createInciwebIndexSource(),
|
||||
inciwebPublications: createInciwebPublicationSource(),
|
||||
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { fleetModelServices } from './fleetModels.js';
|
||||
import * as sprites from '../../data/spriteOrder.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { applyTrackedCameraFrame } from '../../data/trackedCamera.js';
|
||||
import { WORLD_FOCUS_FRAMING, requestWorldFocus } from '../../worldFocus.js';
|
||||
import {
|
||||
railFeedCredit,
|
||||
@@ -52,7 +51,6 @@ export function createApplicationRail({
|
||||
camera: {
|
||||
framing: WORLD_FOCUS_FRAMING.train,
|
||||
requestWorldFocus,
|
||||
applyTrackedCameraFrame,
|
||||
isCockpitActive: () =>
|
||||
globalThis.document?.body?.classList?.contains('cockpit-mode') ===
|
||||
true,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createShipwrecksLayer } from '../../layers/shipwrecks/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
@@ -14,8 +13,6 @@ export function createApplicationShipwrecks(options) {
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
...options,
|
||||
|
||||
@@ -3,9 +3,7 @@ import { createMapillaryProvider } from '../../layers/streetLevel/providers/mapi
|
||||
import { createGoogleProvider } from '../../layers/streetLevel/providers/google/index.js';
|
||||
import { createKartaViewProvider } from '../../layers/streetLevel/providers/kartaview/index.js';
|
||||
import { createPanoramaxProvider } from '../../layers/streetLevel/providers/panoramax/index.js';
|
||||
import * as sprites from '../../data/spriteOrder.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as input from '../../data/inputOwnership.js';
|
||||
import * as scenePick from '../../data/scenePick.js';
|
||||
import * as render from '../../renderGovernor.js';
|
||||
|
||||
@@ -37,6 +35,6 @@ export function createApplicationStreetLevel({
|
||||
}) {
|
||||
return createStreetLevelLayer({
|
||||
providers,
|
||||
services: { sprites, picking, input, scenePick, render },
|
||||
services: { picking, scenePick, render },
|
||||
});
|
||||
}
|
||||
@@ -1,12 +1,9 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js';
|
||||
import { overlayHost } from './overlayHost.js';
|
||||
/** Wire cable source geometry to the application overlay host. */
|
||||
export function createApplicationCables(options) {
|
||||
return createSubmarineCableLayer({
|
||||
overlayHost,
|
||||
screenSpaceEventHandlerFactory: (canvas) =>
|
||||
new Cesium.ScreenSpaceEventHandler(canvas),
|
||||
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
|
||||
...options,
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createWildlifeSightingsLayer } from '../../layers/wildlifeSightings/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
@@ -17,8 +16,6 @@ export function createApplicationWildlifeSightings(options) {
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
sprites,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
|
||||
import { governorRequestRender } from '../renderGovernor.js';
|
||||
import {
|
||||
clearSelectedEntityContextForLayer,
|
||||
getSelectedEntityContext,
|
||||
registerEntityContext,
|
||||
removeEntityContextsForLayer,
|
||||
selectEntityContext,
|
||||
@@ -19,6 +20,7 @@ export const localGeoJsonServices = Object.freeze({
|
||||
setVisible: setOverlaySourceVisible,
|
||||
}),
|
||||
clearSelectedEntityContextForLayer,
|
||||
getSelectedEntityContext,
|
||||
registerEntityContext,
|
||||
removeEntityContextsForLayer,
|
||||
selectEntityContext,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MapStackController } from '../mapStackController.js';
|
||||
import '../render/cesium/mapEngine.js';
|
||||
import {
|
||||
installRenderGovernor,
|
||||
uninstallRenderGovernor,
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
governorRequestRender,
|
||||
getRenderGovernorDiagnostics,
|
||||
} from '../renderGovernor.js';
|
||||
import { framePortFor } from '../testSupport/fakeFramePort.mjs';
|
||||
|
||||
test('destroy invalidates a pending imagery provider before it can touch the viewer', async () => {
|
||||
let resolveProvider;
|
||||
@@ -44,11 +46,11 @@ test('uninstall only releases the current viewer and makes later render requests
|
||||
},
|
||||
},
|
||||
};
|
||||
installRenderGovernor(viewer);
|
||||
installRenderGovernor(framePortFor(viewer.scene));
|
||||
holdContinuousRender('fixture');
|
||||
uninstallRenderGovernor({});
|
||||
uninstallRenderGovernor(framePortFor({}));
|
||||
assert.equal(getRenderGovernorDiagnostics().installed, true);
|
||||
uninstallRenderGovernor(viewer);
|
||||
uninstallRenderGovernor(framePortFor(viewer.scene));
|
||||
const before = renders;
|
||||
governorRequestRender('late');
|
||||
assert.equal(renders, before);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* @module app/panelRendering
|
||||
* @description Keeping the globe drawing in an inline panel whose host stops
|
||||
* animation frames (`src/app/embed.js`, embed mode), through the ports alone: the
|
||||
* application scene hands it to the embed views (`src/app/scene.js`).
|
||||
*/
|
||||
|
||||
// A panel keeps drawing at about this rate when its host stops animation
|
||||
// frames; see keepPanelRendering.
|
||||
const PANEL_FRAME_MS = 33;
|
||||
const MISSED_FRAMES_MS = 250;
|
||||
|
||||
/** A render error's details, including the plain objects workers report. */
|
||||
function describeError(error) {
|
||||
if (error instanceof Error)
|
||||
return `${error.name}: ${error.message}\n${error.stack}`;
|
||||
try {
|
||||
return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {}));
|
||||
} catch {
|
||||
return String(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep `renderer` drawing in an inline panel. Some hosts report a panel on
|
||||
* screen as hidden, which stops the browser's animation frames and with them
|
||||
* the renderer's own loop; while frames stop arriving, draw from a timer
|
||||
* (`resize`, then a frame of the loop, `frame.renderNow({ifDue: true})`: the
|
||||
* camera moves, input and the clock run, and it draws when due). While the
|
||||
* renderer's loop is stopped after a failed frame (`stopped` in its frame
|
||||
* diagnostics) the timer waits, and goes on once a retry starts the loop
|
||||
* again; the render failure notice reports the error
|
||||
* (src/render/cesium/renderFailure.js). Where the renderer never says so, a frame
|
||||
* that fails stops the timer, its error reported in full. Returns a
|
||||
* function that stops it.
|
||||
* @param {import('../render/contract/renderer').Renderer} renderer
|
||||
* @param {{windowRef?: Window, now?: () => number}} [options]
|
||||
* @returns {() => void}
|
||||
*/
|
||||
export function keepPanelRendering(
|
||||
renderer,
|
||||
{ windowRef = globalThis.window, now = () => performance.now() } = {},
|
||||
) {
|
||||
let lastFrame = now();
|
||||
let frameRequest = null;
|
||||
const onFrame = () => {
|
||||
lastFrame = now();
|
||||
frameRequest = windowRef.requestAnimationFrame(onFrame);
|
||||
};
|
||||
frameRequest = windowRef.requestAnimationFrame(onFrame);
|
||||
let failed = false;
|
||||
const stopped = () => renderer.frame.diagnostics?.().stopped;
|
||||
const timer = windowRef.setInterval(() => {
|
||||
if (failed || now() - lastFrame < MISSED_FRAMES_MS || stopped()) return;
|
||||
try {
|
||||
renderer.resize();
|
||||
renderer.frame.renderNow({ ifDue: true });
|
||||
} catch (error) {
|
||||
// Stopped by now: the render failure notice has the error.
|
||||
if (stopped() !== undefined) return;
|
||||
// Report the error in full: workers report plain objects, which
|
||||
// would print as [object Object].
|
||||
failed = true;
|
||||
console.error(
|
||||
"[God's Eye View panel] render error:",
|
||||
describeError(error),
|
||||
);
|
||||
}
|
||||
}, PANEL_FRAME_MS);
|
||||
return () => {
|
||||
windowRef.clearInterval(timer);
|
||||
windowRef.cancelAnimationFrame(frameRequest);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { keepPanelRendering } from './panelRendering.js';
|
||||
|
||||
const windowWith = () => {
|
||||
const handles = { tick: null, frame: null };
|
||||
handles.windowRef = {
|
||||
requestAnimationFrame: (fn) => ((handles.frame = fn), 1),
|
||||
cancelAnimationFrame: () => (handles.frame = null),
|
||||
setInterval: (fn) => ((handles.tick = fn), 1),
|
||||
clearInterval: () => (handles.tick = null),
|
||||
};
|
||||
return handles;
|
||||
};
|
||||
|
||||
test('a panel keeps drawing from a timer while animation frames stop', () => {
|
||||
let clock = 0;
|
||||
const handles = windowWith();
|
||||
const drawn = [];
|
||||
const renderer = {
|
||||
resize: () => drawn.push('resize'),
|
||||
frame: {
|
||||
renderNow: (options) =>
|
||||
drawn.push(options?.ifDue ? 'loop frame' : 'forced frame'),
|
||||
},
|
||||
};
|
||||
const stop = keepPanelRendering(renderer, {
|
||||
windowRef: handles.windowRef,
|
||||
now: () => clock,
|
||||
});
|
||||
// Frames arrive: the render loop draws, so the timer does nothing.
|
||||
clock = 100;
|
||||
handles.frame();
|
||||
handles.tick();
|
||||
assert.deepEqual(drawn, []);
|
||||
// Frames stop, as in a panel its host reports hidden: the timer draws.
|
||||
clock = 400;
|
||||
handles.tick();
|
||||
// A frame of the loop, as the loop's own: the camera moves, input and
|
||||
// the clock run, and it draws when due.
|
||||
assert.deepEqual(drawn, ['resize', 'loop frame']);
|
||||
stop();
|
||||
assert.equal(handles.tick, null);
|
||||
assert.equal(handles.frame, null);
|
||||
});
|
||||
|
||||
test('a panel reports a failed frame in full and stops drawing', () => {
|
||||
const handles = windowWith();
|
||||
let renders = 0;
|
||||
const renderer = {
|
||||
resize() {},
|
||||
frame: {
|
||||
renderNow() {
|
||||
renders += 1;
|
||||
// Workers report plain objects.
|
||||
throw { name: 'RuntimeError', message: 'worker failed' };
|
||||
},
|
||||
},
|
||||
};
|
||||
const logged = [];
|
||||
const original = console.error;
|
||||
console.error = (...args) => logged.push(args.join(' '));
|
||||
try {
|
||||
let clock = 0;
|
||||
const stop = keepPanelRendering(renderer, {
|
||||
windowRef: handles.windowRef,
|
||||
now: () => clock,
|
||||
});
|
||||
clock = 1000;
|
||||
handles.tick();
|
||||
assert.match(logged[0], /render error: .*"message":"worker failed"/);
|
||||
handles.tick();
|
||||
assert.equal(renders, 1, 'no frame after the one that failed');
|
||||
stop();
|
||||
} finally {
|
||||
console.error = original;
|
||||
}
|
||||
});
|
||||
|
||||
test('a panel waits while its renderer’s loop is stopped after a failed frame, and draws again once it restarts', () => {
|
||||
let clock = 0;
|
||||
const handles = windowWith();
|
||||
let stopped = false;
|
||||
let fail = false;
|
||||
let renders = 0;
|
||||
const renderer = {
|
||||
resize() {},
|
||||
frame: {
|
||||
diagnostics: () => ({ stopped }),
|
||||
renderNow() {
|
||||
renders += 1;
|
||||
if (fail) {
|
||||
// The renderer stops its loop as the frame fails.
|
||||
stopped = true;
|
||||
throw new Error('frame failed');
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
const errors = [];
|
||||
const error = console.error;
|
||||
console.error = (...args) => errors.push(args);
|
||||
try {
|
||||
const stop = keepPanelRendering(renderer, {
|
||||
windowRef: handles.windowRef,
|
||||
now: () => clock,
|
||||
});
|
||||
clock = 1000;
|
||||
fail = true;
|
||||
handles.tick();
|
||||
assert.equal(renders, 1);
|
||||
// Stopped: the timer waits, and leaves the error to the notice.
|
||||
handles.tick();
|
||||
assert.equal(renders, 1);
|
||||
assert.deepEqual(errors, []);
|
||||
// A retry starts the loop again: the timer draws again.
|
||||
stopped = false;
|
||||
fail = false;
|
||||
handles.tick();
|
||||
assert.equal(renders, 2);
|
||||
stop();
|
||||
} finally {
|
||||
console.error = error;
|
||||
}
|
||||
});
|
||||
@@ -1,11 +1,13 @@
|
||||
// Retry in an inline panel whose host stops animation frames, so the panel
|
||||
// draws from keepPanelRendering's timer. Drives Cesium's real startRenderLoop
|
||||
// and useDefaultRenderLoop setter (CesiumWidget.prototype).
|
||||
// and useDefaultRenderLoop setter (CesiumWidget.prototype), through the
|
||||
// Cesium frame port.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { keepPanelRendering } from './embed.js';
|
||||
import { renderLoopFixture } from '../ui/renderLoopFixture.mjs';
|
||||
import { keepPanelRendering } from './panelRendering.js';
|
||||
import { renderLoopFixture } from '../render/cesium/renderLoopFixture.mjs';
|
||||
import { createSceneFrame } from '../render/cesium/frame.js';
|
||||
|
||||
function setup() {
|
||||
let tick = null;
|
||||
@@ -23,6 +25,7 @@ function setup() {
|
||||
const scene = {
|
||||
renderError: new Cesium.Event(),
|
||||
preUpdate: new Cesium.Event(),
|
||||
preRender: new Cesium.Event(),
|
||||
postRender: new Cesium.Event(),
|
||||
requestRender() {},
|
||||
initializeFrame() {},
|
||||
@@ -46,7 +49,16 @@ function setup() {
|
||||
},
|
||||
notice: { allowReload: false },
|
||||
});
|
||||
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
|
||||
const frame = createSceneFrame(viewer);
|
||||
const renderer = { resize: () => viewer.resize(), frame: frame.port };
|
||||
const stopPanel = keepPanelRendering(renderer, {
|
||||
windowRef,
|
||||
now: () => clock,
|
||||
});
|
||||
const stop = () => {
|
||||
stopPanel();
|
||||
frame.dispose();
|
||||
};
|
||||
viewer.useDefaultRenderLoop = true;
|
||||
const timerFrame = () => {
|
||||
clock += 400;
|
||||
|
||||
+148
-41
@@ -1,30 +1,66 @@
|
||||
import { createApplicationOperations } from './operations.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
createApplicationViewer,
|
||||
installFreeLookHeightLimit,
|
||||
installTrackpadPinchZoom,
|
||||
} from '../app/viewer.js';
|
||||
import { registerDataCredits } from '../data/dataCredits.js';
|
||||
import { configureCreditKeyboardAccess } from '../creditKeyboard.js';
|
||||
import { mountCreditsView } from '../ui/creditsView.js';
|
||||
import { MapStackController } from '../mapStackController.js';
|
||||
import { loadPhotorealisticTileset } from '../mapStartup.js';
|
||||
import { mapEngineFor } from '../maps/engine.js';
|
||||
import { initLogoGaze } from '../logoGaze.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import {
|
||||
holdContinuousRender,
|
||||
installRenderGovernor,
|
||||
uninstallRenderGovernor,
|
||||
governorRequestRender,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
} from '../renderGovernor.js';
|
||||
import { describeError } from './errors.js';
|
||||
import { isEmbeddedInline } from './embed.js';
|
||||
import { installRenderFailureNotice } from '../ui/renderFailure.js';
|
||||
import { worldClock, worldTimeFor } from '../time/worldClock.js';
|
||||
import { followWorldTime } from '../time/viewerClock.js';
|
||||
import { onLocaleChange, t } from '../i18n/index.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
applicationHooksOf,
|
||||
provideApplicationHooks,
|
||||
} from '../render/applicationHooks.js';
|
||||
import { keepPanelRendering } from './panelRendering.js';
|
||||
import { useStatusStore } from '../ui/stores/status.js';
|
||||
import { applicationPinia } from '../ui/vueRuntime.js';
|
||||
import { createSceneHost } from '../render/rendererOf.js';
|
||||
|
||||
/** Construct the application globe using the caller's local configuration. */
|
||||
let defaultLoad = null;
|
||||
|
||||
/**
|
||||
* The application's composition root picks the renderer: the one given, else
|
||||
* the default (Cesium), loaded only then, so a page on the stub never
|
||||
* loads it. This is the only part of an adapter the application imports. A
|
||||
* page that starts on the default calls this as it starts, so the renderer
|
||||
* loads beside the rest of the page rather than after it.
|
||||
* @returns {Promise<object>} The default `RendererPlugin`.
|
||||
*/
|
||||
export function loadDefaultRenderer() {
|
||||
if (defaultLoad) return defaultLoad;
|
||||
const load = (async () => {
|
||||
const { cesiumRenderer } = await import('../render/cesium/application.js');
|
||||
return cesiumRenderer;
|
||||
})();
|
||||
defaultLoad = load;
|
||||
// A load that failed is tried again by the next call.
|
||||
load.catch(() => {
|
||||
if (defaultLoad === load) defaultLoad = null;
|
||||
});
|
||||
return load;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct the application globe using the caller's local configuration.
|
||||
* `renderer` is the `RendererPlugin` that draws it, or a promise of one
|
||||
* (default: Cesium, `loadDefaultRenderer`). The
|
||||
* application runs on a renderer with only the contract's required members:
|
||||
* what a renderer's plugin hands it beside the contract
|
||||
* (`src/render/applicationHooks.js`) it uses where given, and does without
|
||||
* where not.
|
||||
*/
|
||||
export async function createApplicationScene({
|
||||
renderer: givenPlugin,
|
||||
requestServices,
|
||||
googleApiKey,
|
||||
googleTokens = null,
|
||||
@@ -51,26 +87,76 @@ export async function createApplicationScene({
|
||||
});
|
||||
}
|
||||
loaderStatus.textContent = t('Configuring viewer...');
|
||||
// Provider attribution stays visible, including clean-view and recording.
|
||||
const creditContainer = document.createElement('div');
|
||||
creditContainer.id = 'cesium-credits';
|
||||
document.body.appendChild(creditContainer);
|
||||
defer(() => creditContainer.remove());
|
||||
const viewer = createApplicationViewer({
|
||||
container: 'cesiumContainer',
|
||||
creditContainer,
|
||||
// The render failure notice below replaces Cesium's dead-end panel.
|
||||
showRenderLoopErrors: false,
|
||||
const rendererPlugin = (await givenPlugin) ?? (await loadDefaultRenderer());
|
||||
signal.throwIfAborted();
|
||||
const container = document.getElementById('cesiumContainer');
|
||||
const renderer = await rendererPlugin.create({
|
||||
container,
|
||||
googleApiKey: googleApiKey || undefined,
|
||||
googleTokens: googleTokens
|
||||
? (options) => googleTokens.token(options)
|
||||
: undefined,
|
||||
worldDataToken: cesiumToken || undefined,
|
||||
signal,
|
||||
});
|
||||
// The scene object every layer and tool is handed: the application's own,
|
||||
// bound to the renderer.
|
||||
const scene = createSceneHost(renderer, { container });
|
||||
const viewer = scene.host;
|
||||
// The governor keeps its holds on the renderer's frame port. The loop
|
||||
// draws every frame until the application's tools are up (they release
|
||||
// 'boot'), as it did before anything could hold it. A camera move holds
|
||||
// it drawing every frame too.
|
||||
installRenderGovernor(renderer.frame, { camera: renderer.camera });
|
||||
holdContinuousRender('boot');
|
||||
defer(() => {
|
||||
uninstallRenderGovernor(viewer);
|
||||
if (!viewer.isDestroyed()) viewer.destroy();
|
||||
try {
|
||||
uninstallRenderGovernor(renderer.frame);
|
||||
} finally {
|
||||
try {
|
||||
renderer.destroy();
|
||||
} finally {
|
||||
scene.release();
|
||||
}
|
||||
}
|
||||
});
|
||||
// An inline panel must not reload or navigate its host's page.
|
||||
defer(
|
||||
installRenderFailureNotice(viewer, { allowReload: !isEmbeddedInline() }),
|
||||
);
|
||||
defer(installTrackpadPinchZoom(viewer));
|
||||
// What the plugin hands the application beside the contract, each hook
|
||||
// optional (render/applicationHooks.js).
|
||||
if (typeof rendererPlugin.applicationHooks === 'function')
|
||||
provideApplicationHooks(
|
||||
renderer,
|
||||
rendererPlugin.applicationHooks(renderer),
|
||||
);
|
||||
const hooks = applicationHooksOf(renderer);
|
||||
// The renderer follows its container's size (`Renderer.resize`).
|
||||
if (typeof ResizeObserver === 'function' && container) {
|
||||
const resizes = new ResizeObserver(() => renderer.resize());
|
||||
resizes.observe(container);
|
||||
defer(() => resizes.disconnect());
|
||||
}
|
||||
// Before any layer binds a click: every layer and tool shares this one.
|
||||
// Deferred after the renderer, so it is released before the renderer goes.
|
||||
const input = inputFor(viewer);
|
||||
defer(() => input.destroy());
|
||||
// Ctrl+wheel and trackpad pinches zoom the globe, not the page.
|
||||
const { controls } = renderer.camera;
|
||||
if (!controls.zoomInputs.includes('ctrlWheel'))
|
||||
controls.zoomInputs = [...controls.zoomInputs, 'ctrlWheel'];
|
||||
// The user's outward zooms stop at a whole-Earth view, which stays framed.
|
||||
if (renderer.capabilities.has('keepEarthFramed')) {
|
||||
controls.keepEarthFramed = true;
|
||||
defer(() => {
|
||||
controls.keepEarthFramed = false;
|
||||
});
|
||||
}
|
||||
// The renderer's own notice when the globe stops drawing, in place of a
|
||||
// dead-end panel; an inline panel must not reload or navigate its host's
|
||||
// page.
|
||||
const offRenderFailure = hooks.renderFailureNotice?.({
|
||||
allowReload: !isEmbeddedInline(),
|
||||
store: useStatusStore(applicationPinia()),
|
||||
});
|
||||
if (offRenderFailure) defer(offRenderFailure);
|
||||
defer(
|
||||
followWorldTime(viewer, worldTimeFor('sky'), {
|
||||
subscribe: worldClock.subscribe,
|
||||
@@ -83,32 +169,35 @@ export async function createApplicationScene({
|
||||
: releaseContinuousRender('world-time'),
|
||||
}),
|
||||
);
|
||||
defer(installFreeLookHeightLimit(viewer));
|
||||
registerDataCredits(viewer, credits);
|
||||
configureCreditKeyboardAccess(document);
|
||||
defer(onLocaleChange(() => configureCreditKeyboardAccess(document)));
|
||||
// The credits, in the application's own line, unless the renderer shows
|
||||
// them in a display of its own.
|
||||
if (!hooks.ownCreditDisplay) defer(mountCreditsView(viewer));
|
||||
loaderStatus.textContent =
|
||||
googleApiKey || googleTokens || cesiumToken
|
||||
? t('Loading Google 3D Tiles...')
|
||||
: t('Loading the keyless globe...');
|
||||
const photoreal = await loadPhotorealisticTileset(Cesium, {
|
||||
// The map stacks, and the photoreal base among them, switch through the
|
||||
// scene's map engine: the renderer's own, or its globe port.
|
||||
const engine = mapOptions.engine ?? mapEngineFor(viewer);
|
||||
const photoreal = (await engine.loadPhotoreal?.(viewer, {
|
||||
googleApiKey,
|
||||
googleTokens,
|
||||
cesiumToken,
|
||||
});
|
||||
})) ?? { tileset: null, route: 'none', errors: [] };
|
||||
const tileset = photoreal.tileset;
|
||||
// A provider can finish after cancellation; retain ownership of its result.
|
||||
defer(() => {
|
||||
if (tileset && !tileset.isDestroyed()) {
|
||||
if (!viewer.scene.primitives.remove(tileset)) tileset.destroy();
|
||||
}
|
||||
if (!tileset || engine.isDestroyed(tileset)) return;
|
||||
engine.removeTileset(viewer, tileset);
|
||||
engine.release(tileset);
|
||||
});
|
||||
signal.throwIfAborted();
|
||||
if (tileset) {
|
||||
viewer.scene.primitives.add(tileset);
|
||||
engine.addTileset(viewer, tileset);
|
||||
// NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom.
|
||||
// Google Photorealistic 3D Tiles provide their own terrain/elevation.
|
||||
viewer.scene.globe.show = false;
|
||||
renderer.globe.setGlobeVisible(false);
|
||||
console.info(`[Init] Google 3D Tiles loaded via ${photoreal.route}.`);
|
||||
} else {
|
||||
if (photoreal.errors.length) {
|
||||
@@ -125,7 +214,7 @@ export async function createApplicationScene({
|
||||
},
|
||||
);
|
||||
}
|
||||
viewer.scene.globe.show = true;
|
||||
renderer.globe.setGlobeVisible(true);
|
||||
}
|
||||
|
||||
loaderStatus.textContent = t('Initializing systems...');
|
||||
@@ -133,6 +222,7 @@ export async function createApplicationScene({
|
||||
const mapStackController = new MapController(viewer, {
|
||||
requestRender: governorRequestRender,
|
||||
...mapOptions,
|
||||
engine,
|
||||
googleTileset: tileset,
|
||||
cesiumToken,
|
||||
initialStack: tileset ? 'photoreal' : 'esri-imagery',
|
||||
@@ -154,5 +244,22 @@ export async function createApplicationScene({
|
||||
});
|
||||
|
||||
signal.throwIfAborted();
|
||||
return { viewer, tileset, mapStackController, operations };
|
||||
return {
|
||||
renderer,
|
||||
viewer,
|
||||
tileset,
|
||||
mapStackController,
|
||||
operations,
|
||||
input,
|
||||
// Keeps the globe drawing in an inline panel whose host stops animation
|
||||
// frames (embed mode, src/app/embed.js); returns its disposer.
|
||||
keepPanelRendering: (options) => keepPanelRendering(renderer, options),
|
||||
// What the renderer's plugin hands the application beside the contract,
|
||||
// each optional: trims stale draw commands, says whether an entity is
|
||||
// the renderer's own, and what QA scripts read
|
||||
// (render/applicationHooks.js).
|
||||
trimStaleCommands: hooks.trimStaleCommands,
|
||||
viewerDrawsEntity: hooks.viewerDrawsEntity,
|
||||
qaHandles: hooks.qaHandles,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createApplicationScene } from './scene.js';
|
||||
import { createApplicationRequestServices } from '../services/requests.js';
|
||||
import { createStubRendererPlugin } from '../render/stub/index.js';
|
||||
import { rendererOf } from '../render/rendererOf.js';
|
||||
|
||||
/** Start the scene on a stub renderer with `capabilities`. */
|
||||
async function startOnStub(t, { capabilities = [], ...rest } = {}) {
|
||||
document.body.innerHTML = '<div id="cesiumContainer"></div>';
|
||||
const made = [];
|
||||
const deferred = [];
|
||||
t.after(async () => {
|
||||
for (const fn of deferred.reverse()) await fn();
|
||||
});
|
||||
const scene = await createApplicationScene({
|
||||
renderer: createStubRendererPlugin({ capabilities }, (renderer) =>
|
||||
made.push(renderer),
|
||||
),
|
||||
requestServices: createApplicationRequestServices(),
|
||||
loaderStatus: { textContent: '' },
|
||||
signal: new AbortController().signal,
|
||||
defer: (fn) => deferred.push(fn),
|
||||
...rest,
|
||||
});
|
||||
return { scene, renderer: made[0], deferred };
|
||||
}
|
||||
|
||||
test('the scene runs on a renderer with only the required members', async (t) => {
|
||||
const { scene, renderer, deferred } = await startOnStub(t);
|
||||
assert.equal(scene.renderer, renderer);
|
||||
assert.equal(rendererOf(scene.viewer), renderer, 'the scene object is bound');
|
||||
assert.equal(
|
||||
scene.viewer.container,
|
||||
document.getElementById('cesiumContainer'),
|
||||
);
|
||||
assert.equal(scene.viewer.isDestroyed(), false);
|
||||
assert.ok(
|
||||
scene.viewer.container.contains(renderer.canvas),
|
||||
'the renderer fills the container',
|
||||
);
|
||||
// Nothing of the engine on the scene object.
|
||||
assert.deepEqual(Object.keys(scene.viewer).sort(), [
|
||||
'container',
|
||||
'isDestroyed',
|
||||
]);
|
||||
// No hooks: each is left out, not faked.
|
||||
for (const name of ['trimStaleCommands', 'viewerDrawsEntity', 'qaHandles'])
|
||||
assert.equal(scene[name], undefined, name);
|
||||
// What the renderer does through its ports.
|
||||
assert.equal(typeof scene.keepPanelRendering, 'function');
|
||||
assert.equal(
|
||||
renderer.camera.controls.keepEarthFramed,
|
||||
undefined,
|
||||
'no framing on a renderer without it',
|
||||
);
|
||||
// Keyless, the map stack shows Esri on the globe through the globe port.
|
||||
assert.equal(scene.tileset, null);
|
||||
assert.equal(scene.mapStackController.getActiveId(), 'esri-imagery');
|
||||
const layers = renderer.globe.imagery.list();
|
||||
assert.equal(layers.length, 1, 'one base imagery layer');
|
||||
assert.ok(
|
||||
renderer.testing.calls.some(
|
||||
(call) =>
|
||||
call.port === 'globe' &&
|
||||
call.member === 'imagery.add' &&
|
||||
call.args[0]?.url?.includes('World_Imagery'),
|
||||
),
|
||||
'Esri imagery through the port',
|
||||
);
|
||||
assert.equal(scene.mapStackController.getDrapeSurface(), 'globe');
|
||||
// The credits show in the application's own line: the Esri base's on it,
|
||||
// the data credits in the list it opens.
|
||||
const line = document.getElementById('gev-credits');
|
||||
assert.ok(line, 'a credits line');
|
||||
assert.match(line.textContent, /Esri/);
|
||||
assert.ok(
|
||||
document.querySelectorAll('#gev-credits-panel li').length > 10,
|
||||
'the data credits',
|
||||
);
|
||||
|
||||
// Switching stacks goes through the port too.
|
||||
await scene.mapStackController.setStack('osm');
|
||||
assert.equal(scene.mapStackController.getActiveId(), 'osm');
|
||||
assert.equal(renderer.globe.imagery.list().length, 1, 'Esri gave way');
|
||||
|
||||
for (const fn of deferred.splice(0).reverse()) await fn();
|
||||
assert.equal(scene.viewer.isDestroyed(), true);
|
||||
assert.equal(rendererOf(scene.viewer), null, 'and lets go of the renderer');
|
||||
assert.equal(renderer.globe.imagery.list().length, 0, 'imagery released');
|
||||
assert.equal(document.getElementById('gev-credits'), null, 'credits gone');
|
||||
});
|
||||
|
||||
test('the scene keeps the Earth framed where the renderer can', async (t) => {
|
||||
const { renderer, deferred } = await startOnStub(t, {
|
||||
capabilities: ['keepEarthFramed'],
|
||||
});
|
||||
assert.equal(renderer.camera.controls.keepEarthFramed, true);
|
||||
const controls = renderer.camera.controls;
|
||||
for (const fn of deferred.splice(0).reverse()) await fn();
|
||||
assert.equal(controls.keepEarthFramed, false, 'and lets go on teardown');
|
||||
});
|
||||
|
||||
test("the scene takes a plugin's application hooks", async (t) => {
|
||||
const stub = createStubRendererPlugin({ capabilities: [] });
|
||||
const given = [];
|
||||
const handles = Object.freeze({ probe: 'qa' });
|
||||
const { scene } = await startOnStub(t, {
|
||||
renderer: {
|
||||
id: 'stub-with-hooks',
|
||||
create: (options) => stub.create(options),
|
||||
applicationHooks(made) {
|
||||
given.push(made);
|
||||
return { qaHandles: handles, ownCreditDisplay: true };
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(given, [scene.renderer], 'asked once, for the renderer');
|
||||
assert.equal(scene.qaHandles, handles, 'QA scripts read its handles');
|
||||
assert.equal(
|
||||
document.getElementById('gev-credits'),
|
||||
null,
|
||||
'its own display shows the credits',
|
||||
);
|
||||
});
|
||||
|
||||
test('with credentials, the photoreal base loads through the globe port', async (t) => {
|
||||
const { scene, renderer } = await startOnStub(t, {
|
||||
capabilities: ['photoreal', 'globeVisibility'],
|
||||
googleApiKey: 'stub-key',
|
||||
});
|
||||
assert.ok(scene.tileset, 'a photoreal base');
|
||||
assert.equal(scene.mapStackController.getActiveId(), 'photoreal');
|
||||
assert.equal(renderer.globe.isGlobeVisible(), false, 'the globe is hidden');
|
||||
const photoreal = renderer.testing.calls.filter(
|
||||
(call) => call.port === 'globe' && call.member === 'setPhotoreal',
|
||||
);
|
||||
assert.equal(photoreal[0]?.args[0]?.key, 'stub-key');
|
||||
|
||||
// A globe stack hides photoreal through the port, and shows the globe.
|
||||
await scene.mapStackController.setStack('esri-imagery');
|
||||
assert.equal(renderer.globe.isGlobeVisible(), true);
|
||||
assert.equal(
|
||||
renderer.testing.calls
|
||||
.filter((call) => call.port === 'globe' && call.member === 'setPhotoreal')
|
||||
.at(-1).args[0],
|
||||
null,
|
||||
);
|
||||
await scene.mapStackController.setStack('photoreal');
|
||||
assert.equal(renderer.globe.isGlobeVisible(), false);
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
|
||||
import '../render/cesium/input.js';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
|
||||
@@ -1,25 +1,41 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { flyToAustin } from '../camera.js';
|
||||
import { applyStartView, START_VIEW } from '../camera.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
test('teardown before the initial camera delay prevents a late flight', (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
let flights = 0;
|
||||
let cancelled = 0;
|
||||
const stop = flyToAustin({
|
||||
function viewerRecording(views) {
|
||||
return bindFakeCesiumCamera({
|
||||
isDestroyed: () => false,
|
||||
camera: {
|
||||
setView() {},
|
||||
flyTo() {
|
||||
flights++;
|
||||
setView(view) {
|
||||
views.push(view);
|
||||
},
|
||||
cancelFlight() {
|
||||
cancelled++;
|
||||
flyTo() {
|
||||
assert.fail('a start view is set, not flown to');
|
||||
},
|
||||
},
|
||||
});
|
||||
stop();
|
||||
t.mock.timers.tick(1000);
|
||||
assert.equal(flights, 0);
|
||||
assert.equal(cancelled, 1);
|
||||
}
|
||||
|
||||
test('the camera starts over the whole planet, looking straight down', () => {
|
||||
const views = [];
|
||||
applyStartView(viewerRecording(views));
|
||||
assert.equal(views.length, 1);
|
||||
assert.ok(START_VIEW.height >= 20000000, 'the whole planet is in view');
|
||||
assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 2) < 1e-9);
|
||||
assert.equal(views[0].orientation.heading, 0);
|
||||
});
|
||||
|
||||
test('a host can start the camera at a city instead', () => {
|
||||
const views = [];
|
||||
applyStartView(viewerRecording(views), {
|
||||
lon: 2.35,
|
||||
lat: 48.86,
|
||||
height: 5000,
|
||||
heading: 90,
|
||||
pitch: -30,
|
||||
});
|
||||
assert.equal(views.length, 1);
|
||||
assert.ok(Math.abs(views[0].orientation.heading - Math.PI / 2) < 1e-9);
|
||||
assert.ok(Math.abs(views[0].orientation.pitch + Math.PI / 6) < 1e-9);
|
||||
});
|
||||
+40
-28
@@ -1,3 +1,4 @@
|
||||
import { onFollowChanged } from '../data/followed.js';
|
||||
import { SceneDirector } from '../scenes/director.js';
|
||||
import { initAnnotations } from '../annotations/index.js';
|
||||
import { initDrawTool } from '../annotations/drawTool.js';
|
||||
@@ -24,17 +25,22 @@ import {
|
||||
isScopeMaskEnabled,
|
||||
} from '../scopeMask.js';
|
||||
import { KEYHOLE_OUTER_RADIUS } from '../celestialRing.js';
|
||||
import { installGlobeInViewRecovery } from './viewer.js';
|
||||
import { installGlobeInViewRecovery } from './globeInViewRecovery.js';
|
||||
import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
|
||||
import {
|
||||
installRenderGovernor,
|
||||
getRenderGovernorDiagnostics,
|
||||
governorRequestRender,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
} from '../renderGovernor.js';
|
||||
import { entityRecord, readEntityRecord } from '../data/entityRecords.js';
|
||||
import { overlayHost } from './layers/overlayHost.js';
|
||||
|
||||
/** Attach scene tools, rendering listeners and the application debug handle. */
|
||||
/**
|
||||
* Attach scene tools, rendering listeners and the application debug handle.
|
||||
* `scene` is what `createApplicationScene` returns; its `trimStaleCommands`
|
||||
* runs after each layer disable (a scene without one keeps that memory).
|
||||
*/
|
||||
export function createApplicationTools({
|
||||
scene,
|
||||
controls,
|
||||
@@ -49,11 +55,11 @@ export function createApplicationTools({
|
||||
signal,
|
||||
defer,
|
||||
}) {
|
||||
const { viewer, tileset, mapStackController, operations } = scene;
|
||||
const { viewer, renderer, tileset, mapStackController, operations } = scene;
|
||||
const { styleManager, weatherEffects, cockpitCloudEffects } = controls;
|
||||
const { dataManager } = data;
|
||||
const sceneDirector = new SceneDirector(viewer, styleManager, dataManager, {
|
||||
dataPacks: sceneDataPacks,
|
||||
dataPacks: { overlayHost, ...sceneDataPacks },
|
||||
isMapStackAvailable: (id) =>
|
||||
mapStackController?.isStackAvailable(id) === true,
|
||||
});
|
||||
@@ -198,19 +204,21 @@ export function createApplicationTools({
|
||||
}
|
||||
if (startChrome)
|
||||
defer(startChrome({ loadingScreen, styleManager, dataManager, signal }));
|
||||
// Idle render governor: flips the scene into requestRenderMode whenever
|
||||
// nothing animates per frame. Installed AFTER every module above has had
|
||||
// its chance to register pre-install holds. (perf wave 2)
|
||||
installRenderGovernor(viewer);
|
||||
// Cesium keeps a turned-off layer's draw commands (and so all its entities)
|
||||
// alive in reused per-pass arrays; trim them after each disable.
|
||||
defer(
|
||||
installLayerReleaseTrim({
|
||||
scene: viewer.scene,
|
||||
dataManager,
|
||||
requestRender: governorRequestRender,
|
||||
}),
|
||||
);
|
||||
// Idle render governor: the loop draws on demand whenever nothing animates
|
||||
// per frame. It goes idle only now, after every module above has had its
|
||||
// chance to hold. (perf wave 2)
|
||||
releaseContinuousRender('boot');
|
||||
// The renderer may keep a turned-off layer's draw commands (and so all its
|
||||
// entities) alive; trim them after each disable.
|
||||
if (scene.trimStaleCommands)
|
||||
defer(
|
||||
installLayerReleaseTrim({
|
||||
frame: renderer.frame,
|
||||
dataManager,
|
||||
requestRender: governorRequestRender,
|
||||
trim: scene.trimStaleCommands,
|
||||
}),
|
||||
);
|
||||
|
||||
// Install the explicit scope mask used by the DISPLAY controls.
|
||||
installScopeMask(viewer);
|
||||
@@ -218,12 +226,10 @@ export function createApplicationTools({
|
||||
|
||||
// The follow camera recomputes the tracked target's dead-reckon position
|
||||
// every frame — tracking anything is a per-frame animation. (perf wave 2)
|
||||
const removeTrackingListener = viewer.trackedEntityChanged.addEventListener(
|
||||
() => {
|
||||
if (viewer.trackedEntity) holdContinuousRender('tracked-entity');
|
||||
else releaseContinuousRender('tracked-entity');
|
||||
},
|
||||
);
|
||||
const removeTrackingListener = onFollowChanged(viewer, (followed) => {
|
||||
if (followed) holdContinuousRender('tracked-entity');
|
||||
else releaseContinuousRender('tracked-entity');
|
||||
});
|
||||
|
||||
// Hidden-state suspension (perf wave 2): when the window/tab is hidden,
|
||||
// stop the default render loop outright — a hidden canvas repaints for
|
||||
@@ -232,9 +238,9 @@ export function createApplicationTools({
|
||||
// the loop, refresh the one DOM surface we gated, render a frame.
|
||||
const syncVisibilitySuspension = () => {
|
||||
// A panel's host may report it hidden while it is on screen; the panel
|
||||
// keeps drawing itself (see keepPanelRendering in embed.js).
|
||||
// keeps drawing itself (see keepPanelRendering in app/panelRendering.js).
|
||||
const hidden = document.hidden && !isEmbeddedInline();
|
||||
viewer.useDefaultRenderLoop = !hidden;
|
||||
renderer.frame.suspend(hidden);
|
||||
cockpitCloudEffects?.setSuspended?.(hidden);
|
||||
if (!hidden) {
|
||||
data.presentation.flushVisible();
|
||||
@@ -267,6 +273,10 @@ export function createApplicationTools({
|
||||
getRenderGovernorDiagnostics,
|
||||
surfaceServices: operations.surface,
|
||||
requestRender: governorRequestRender,
|
||||
entityRecords: { read: readEntityRecord, write: entityRecord },
|
||||
// What the renderer's plugin lets QA scripts read (the Cesium viewer,
|
||||
// for the default renderer), in place of the scene object above.
|
||||
...scene.qaHandles,
|
||||
};
|
||||
const debug = window.__godsEyeView;
|
||||
defer(() => {
|
||||
@@ -299,11 +309,13 @@ export function createApplicationTools({
|
||||
run: (name, args, options = {}) =>
|
||||
voiceCommands.runner(name, args, { ...options, signal }),
|
||||
signal,
|
||||
keepRendering: scene.keepPanelRendering,
|
||||
terrain: operations.requests.terrain,
|
||||
}),
|
||||
);
|
||||
// An application's own tool takes the pointer as Draw does, and its own
|
||||
// click handlers yield while a tool holds it, as the layers' do
|
||||
// Any other tool takes the pointer as Draw does (the newest
|
||||
// claim takes over; `claim(owner, {onLost})` tells the tool it replaces),
|
||||
// and its own click handlers yield while a tool holds it, as the layers' do
|
||||
// (data/inputOwnership.js).
|
||||
return {
|
||||
sceneDirector,
|
||||
|
||||
@@ -1,447 +0,0 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { IDLE_FRAME_RATE } from '../renderGovernor.js';
|
||||
import { applyModelAtmosphereWorkaround } from './atmosphereCompat.js';
|
||||
import { StarrySky } from '../sky/starrySky.js';
|
||||
import {
|
||||
FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
globeOutOfFrame,
|
||||
isFreeGlobeCamera,
|
||||
} from '../globeInView.js';
|
||||
|
||||
/**
|
||||
* At the farthest a hand can zoom out, the globe is this share of the
|
||||
* screen's height across. Cesium sets no limit, so zooming on left the globe
|
||||
* a speck among the stars.
|
||||
*/
|
||||
const MIN_GLOBE_SHARE = 0.3;
|
||||
|
||||
/**
|
||||
* The farthest a hand can zoom out, in metres above the ellipsoid, for a
|
||||
* vertical field of view. It follows the screen's shape, as the app's own
|
||||
* whole-globe view does, so that view always lies within it.
|
||||
* @param {number} fovy Vertical field of view, radians.
|
||||
*/
|
||||
export function zoomOutLimit(fovy) {
|
||||
const radius = Cesium.Ellipsoid.WGS84.maximumRadius;
|
||||
const angular = Math.atan(MIN_GLOBE_SHARE * Math.tan(fovy / 2));
|
||||
return radius / Math.sin(angular) - radius;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hold a hand's zoom out to `zoomOutLimit` on the globe, each frame, since the
|
||||
* field of view follows the screen's shape. The limit never sits below the
|
||||
* camera: one already past it (a flight, a screen turned) stops there rather
|
||||
* than jumping in at the next zoom. Flat maps keep Cesium's own, unlimited.
|
||||
* @returns {() => void} Stop limiting.
|
||||
*/
|
||||
export function limitZoomOut(viewer) {
|
||||
const { scene, camera } = viewer;
|
||||
return scene.preRender.addEventListener(() => {
|
||||
const controller = scene.screenSpaceCameraController;
|
||||
const fovy = camera.frustum.fovy;
|
||||
if (scene.mode !== Cesium.SceneMode.SCENE3D || !Number.isFinite(fovy)) {
|
||||
controller.maximumZoomDistance = Number.POSITIVE_INFINITY;
|
||||
return;
|
||||
}
|
||||
controller.maximumZoomDistance = Math.max(
|
||||
zoomOutLimit(fovy),
|
||||
camera.positionCartographic?.height ?? 0,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const PINCH_ZOOM_MULTIPLIER = 8;
|
||||
const MAX_PINCH_PIXEL_DELTA = 120;
|
||||
|
||||
function boundedPinchDelta(delta) {
|
||||
if (!Number.isFinite(delta) || delta === 0) return delta;
|
||||
return (
|
||||
Math.sign(delta) *
|
||||
Math.min(Math.abs(delta) * PINCH_ZOOM_MULTIPLIER, MAX_PINCH_PIXEL_DELTA)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add browser trackpad pinch to Cesium's zoom inputs and return its disposer.
|
||||
* Browsers expose this gesture as a small pixel-mode Ctrl+wheel event.
|
||||
*/
|
||||
export function installTrackpadPinchZoom(
|
||||
viewer,
|
||||
{ createWheelEvent = (type, init) => new WheelEvent(type, init) } = {},
|
||||
) {
|
||||
const controller = viewer?.scene?.screenSpaceCameraController;
|
||||
const container = viewer?.container;
|
||||
const canvas = viewer?.canvas;
|
||||
if (!controller || !container || !canvas)
|
||||
throw new TypeError('A complete Cesium viewer is required');
|
||||
|
||||
const originalZoomEventTypes = controller.zoomEventTypes;
|
||||
const zoomEventTypes = Array.isArray(originalZoomEventTypes)
|
||||
? originalZoomEventTypes
|
||||
: originalZoomEventTypes === undefined
|
||||
? []
|
||||
: [originalZoomEventTypes];
|
||||
const alreadyHandlesControlWheel = zoomEventTypes.some(
|
||||
(binding) =>
|
||||
binding?.eventType === Cesium.CameraEventType.WHEEL &&
|
||||
binding?.modifier === Cesium.KeyboardEventModifier.CTRL,
|
||||
);
|
||||
const configuredZoomEventTypes = alreadyHandlesControlWheel
|
||||
? originalZoomEventTypes
|
||||
: [
|
||||
...zoomEventTypes,
|
||||
{
|
||||
eventType: Cesium.CameraEventType.WHEEL,
|
||||
modifier: Cesium.KeyboardEventModifier.CTRL,
|
||||
},
|
||||
];
|
||||
if (!alreadyHandlesControlWheel)
|
||||
controller.zoomEventTypes = configuredZoomEventTypes;
|
||||
|
||||
const relayedEvents = new WeakSet();
|
||||
const relayPinch = (event) => {
|
||||
if (
|
||||
!event.ctrlKey ||
|
||||
relayedEvents.has(event) ||
|
||||
event.deltaMode !== 0 ||
|
||||
!Number.isFinite(event.deltaY) ||
|
||||
event.deltaY === 0
|
||||
)
|
||||
return;
|
||||
let relayed;
|
||||
try {
|
||||
relayed = createWheelEvent('wheel', {
|
||||
deltaX: event.deltaX,
|
||||
deltaY: boundedPinchDelta(event.deltaY),
|
||||
deltaZ: event.deltaZ,
|
||||
deltaMode: event.deltaMode,
|
||||
screenX: event.screenX,
|
||||
screenY: event.screenY,
|
||||
clientX: event.clientX,
|
||||
clientY: event.clientY,
|
||||
ctrlKey: true,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
view: globalThis.window,
|
||||
});
|
||||
} catch {
|
||||
// The registered Ctrl+wheel binding can still consume the original.
|
||||
return;
|
||||
}
|
||||
relayedEvents.add(relayed);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
canvas.dispatchEvent(relayed);
|
||||
};
|
||||
container.addEventListener('wheel', relayPinch, {
|
||||
capture: true,
|
||||
passive: false,
|
||||
});
|
||||
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
container.removeEventListener('wheel', relayPinch, true);
|
||||
if (
|
||||
!alreadyHandlesControlWheel &&
|
||||
controller.zoomEventTypes === configuredZoomEventTypes
|
||||
)
|
||||
controller.zoomEventTypes = originalZoomEventTypes;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow Cesium's free look only below `maxHeight` and return its disposer.
|
||||
* Orbit, tilt and zoom stay available at every height. A value other code
|
||||
* sets later is kept as the one to allow below that height, and restored on
|
||||
* dispose; a `false` written while the camera is above `maxHeight` cannot be
|
||||
* told apart from this limit's own write, so dispose restores the earlier
|
||||
* value then. `enableLook` gates the Shift+drag binding only: below its trackball
|
||||
* height Cesium also turns the camera in place for a drag that starts on the
|
||||
* stars. That height is lowered to `maxHeight` too, so above it such a drag
|
||||
* orbits the globe, as it does above Cesium's own 7,500 km.
|
||||
*/
|
||||
export function installFreeLookHeightLimit(
|
||||
viewer,
|
||||
maxHeight = FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
) {
|
||||
const scene = viewer?.scene;
|
||||
const controller = scene?.screenSpaceCameraController;
|
||||
const camera = viewer?.camera;
|
||||
if (!controller || !camera || !scene?.preUpdate)
|
||||
throw new TypeError('A complete Cesium viewer is required');
|
||||
|
||||
const originalTrackBallHeight = controller.minimumTrackBallHeight;
|
||||
const trackBallHeight = Math.min(originalTrackBallHeight, maxHeight);
|
||||
controller.minimumTrackBallHeight = trackBallHeight;
|
||||
let wanted = controller.enableLook;
|
||||
let written;
|
||||
const sync = () => {
|
||||
if (written !== undefined && controller.enableLook !== written)
|
||||
wanted = controller.enableLook;
|
||||
const height = camera.positionCartographic?.height;
|
||||
written = wanted && !(Number.isFinite(height) && height > maxHeight);
|
||||
controller.enableLook = written;
|
||||
};
|
||||
sync();
|
||||
const removeListener = scene.preUpdate.addEventListener(sync);
|
||||
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
removeListener();
|
||||
if (controller.enableLook === written) controller.enableLook = wanted;
|
||||
if (controller.minimumTrackBallHeight === trackBallHeight)
|
||||
controller.minimumTrackBallHeight = originalTrackBallHeight;
|
||||
};
|
||||
}
|
||||
|
||||
// How often a moving camera is sampled to see whether it has come to rest, how
|
||||
// far a pose may drift between samples and still count as at rest, and how
|
||||
// long after the camera last moved the check gives up if Cesium never raises
|
||||
// moveEnd.
|
||||
const SETTLE_SAMPLE_MS = 250;
|
||||
const SETTLE_POSITION_TOLERANCE_M = 1e-3;
|
||||
const SETTLE_DIRECTION_TOLERANCE = 1e-9;
|
||||
const SETTLE_GIVE_UP_MS = 5 * 60_000;
|
||||
|
||||
/**
|
||||
* Turn the camera back to the planet when a move ends above `minHeight` with
|
||||
* no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about
|
||||
* one sample cell thick can count as none), and return the disposer. Views with
|
||||
* more surface, such as an oblique orbital shot, are left as they are. This
|
||||
* catches a saved or shared view that looked away, or any other move that ends
|
||||
* looking away from the planet.
|
||||
* Heading and position are kept. Tracked cameras, locked ones (non-identity
|
||||
* transform), a camera flight in progress, a pointer held down on the canvas
|
||||
* (a drag held still), the 2D and Columbus modes, and any time `paused`
|
||||
* returns true (an authored scene playing) are left alone; a check they defer
|
||||
* runs once they end, however long they last.
|
||||
* `keyholeRadius`
|
||||
* returns the radius of the visible circle when a scope mask hides the rest of
|
||||
* the frame (see `globeFrameShare`), or 0; it is read at every check.
|
||||
*
|
||||
* Cesium's `moveEnd` alone is not enough: Cesium compares the camera with the
|
||||
* last frame's to the last rounding error, and at some of these poses the
|
||||
* camera drifts by a rounding error every frame, so Cesium never sees it stop.
|
||||
* So each `moveStart` also starts a check of its own that samples the pose
|
||||
* every 250 ms, with a tolerance for that drift, and once the pose has held
|
||||
* for half a second after moving runs the same recovery. It keeps watching
|
||||
* until Cesium raises `moveEnd`, since under that drift Cesium raises no new
|
||||
* `moveStart` for a later move, and gives up five minutes after the camera
|
||||
* last moved.
|
||||
* `setTimeout` and `clearTimeout` can be injected for tests.
|
||||
*/
|
||||
export function installGlobeInViewRecovery(
|
||||
viewer,
|
||||
{
|
||||
minHeight = FREE_LOOK_MAX_HEIGHT_METERS,
|
||||
keyholeRadius = () => 0,
|
||||
paused = () => false,
|
||||
setTimeout: schedule = globalThis.setTimeout,
|
||||
clearTimeout: unschedule = globalThis.clearTimeout,
|
||||
} = {},
|
||||
) {
|
||||
const scene = viewer?.scene;
|
||||
const camera = viewer?.camera;
|
||||
if (!scene || !camera?.moveEnd || !camera?.moveStart)
|
||||
throw new TypeError('A complete Cesium viewer is required');
|
||||
|
||||
// A pointer held on the globe is a gesture in progress, even when it holds
|
||||
// still for half a second: the check waits until every pointer pressed on
|
||||
// it (each finger of a pinch) is released. A release the page never sees,
|
||||
// outside the window, is taken as given when the window loses focus, the
|
||||
// page is hidden, the canvas loses the pointer's capture, or the pointer
|
||||
// moves with no button down.
|
||||
const canvas = scene.canvas;
|
||||
const releaseTarget = canvas?.ownerDocument ?? canvas;
|
||||
const releaseWindow = canvas?.ownerDocument?.defaultView;
|
||||
const heldPointers = new Set();
|
||||
const onPointerDown = (event) => heldPointers.add(event?.pointerId);
|
||||
const onPointerUp = (event) => heldPointers.delete(event?.pointerId);
|
||||
const onPointerMove = (event) => {
|
||||
if (event?.buttons === 0) heldPointers.delete(event.pointerId);
|
||||
};
|
||||
const releaseAll = () => heldPointers.clear();
|
||||
const onVisibilityChange = () => {
|
||||
if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll();
|
||||
};
|
||||
const listeners = [
|
||||
[canvas, 'pointerdown', onPointerDown],
|
||||
[canvas, 'lostpointercapture', onPointerUp],
|
||||
[releaseTarget, 'pointerup', onPointerUp],
|
||||
[releaseTarget, 'pointercancel', onPointerUp],
|
||||
[releaseTarget, 'pointermove', onPointerMove],
|
||||
[canvas?.ownerDocument, 'visibilitychange', onVisibilityChange],
|
||||
[releaseWindow, 'blur', releaseAll],
|
||||
];
|
||||
for (const [target, type, listener] of listeners)
|
||||
target?.addEventListener?.(type, listener);
|
||||
|
||||
// Returns false while a flight, a paused scene or a held pointer defers the
|
||||
// check, so the caller can try again once it ends.
|
||||
const recover = () => {
|
||||
if (!isFreeGlobeCamera(viewer)) return true;
|
||||
// Cesium has no public running-flight flag.
|
||||
if (camera._currentFlight || paused() || heldPointers.size > 0)
|
||||
return false;
|
||||
const height = camera.positionCartographic?.height;
|
||||
if (
|
||||
!(height > minHeight) ||
|
||||
!globeOutOfFrame(camera, { keyholeRadius: keyholeRadius() })
|
||||
)
|
||||
return true;
|
||||
camera.setView({
|
||||
orientation: {
|
||||
heading: camera.heading,
|
||||
pitch: -Cesium.Math.PI_OVER_TWO,
|
||||
roll: 0,
|
||||
},
|
||||
});
|
||||
scene.requestRender?.();
|
||||
return true;
|
||||
};
|
||||
|
||||
const lastPosition = new Cesium.Cartesian3();
|
||||
const lastDirection = new Cesium.Cartesian3();
|
||||
let settleTimer = null;
|
||||
let settleElapsed = 0;
|
||||
let restingSamples = 0;
|
||||
let movedSinceCheck = false;
|
||||
const stopSettling = () => {
|
||||
if (settleTimer !== null) unschedule(settleTimer);
|
||||
settleTimer = null;
|
||||
};
|
||||
const sample = () => {
|
||||
settleTimer = null;
|
||||
settleElapsed += SETTLE_SAMPLE_MS;
|
||||
const atRest =
|
||||
Cesium.Cartesian3.equalsEpsilon(
|
||||
camera.positionWC,
|
||||
lastPosition,
|
||||
0,
|
||||
SETTLE_POSITION_TOLERANCE_M,
|
||||
) &&
|
||||
Cesium.Cartesian3.equalsEpsilon(
|
||||
camera.directionWC,
|
||||
lastDirection,
|
||||
0,
|
||||
SETTLE_DIRECTION_TOLERANCE,
|
||||
);
|
||||
restingSamples = atRest ? restingSamples + 1 : 0;
|
||||
if (!atRest) {
|
||||
movedSinceCheck = true;
|
||||
settleElapsed = 0;
|
||||
}
|
||||
// Two quiet samples in a row after a move: at rest for half a second, as
|
||||
// for moveEnd.
|
||||
if (restingSamples >= 2 && movedSinceCheck) {
|
||||
if (recover()) movedSinceCheck = false;
|
||||
// A flight or a playing scene bounds its own deferral.
|
||||
else settleElapsed = 0;
|
||||
}
|
||||
if (settleElapsed >= SETTLE_GIVE_UP_MS) return;
|
||||
Cesium.Cartesian3.clone(camera.positionWC, lastPosition);
|
||||
Cesium.Cartesian3.clone(camera.directionWC, lastDirection);
|
||||
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
|
||||
};
|
||||
const startSettling = () => {
|
||||
stopSettling();
|
||||
settleElapsed = 0;
|
||||
restingSamples = 0;
|
||||
movedSinceCheck = true;
|
||||
Cesium.Cartesian3.clone(camera.positionWC, lastPosition);
|
||||
Cesium.Cartesian3.clone(camera.directionWC, lastDirection);
|
||||
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
|
||||
};
|
||||
const removeMoveEnd = camera.moveEnd.addEventListener(() => {
|
||||
if (recover()) stopSettling();
|
||||
// Deferred: keep sampling so the check runs once the flight or scene ends.
|
||||
else if (settleTimer === null) startSettling();
|
||||
});
|
||||
const removeMoveStart = camera.moveStart.addEventListener(startSettling);
|
||||
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
stopSettling();
|
||||
removeMoveEnd();
|
||||
removeMoveStart();
|
||||
for (const [target, type, listener] of listeners)
|
||||
target?.removeEventListener?.(type, listener);
|
||||
heldPointers.clear();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Cesium.Viewer options of the standard globe viewer. `showRenderLoopErrors`
|
||||
* false leaves render errors to the caller's own notice instead of Cesium's
|
||||
* panel.
|
||||
*/
|
||||
export function applicationViewerOptions(
|
||||
creditContainer,
|
||||
{ showRenderLoopErrors = true } = {},
|
||||
) {
|
||||
return {
|
||||
timeline: false,
|
||||
animation: false,
|
||||
baseLayerPicker: false,
|
||||
geocoder: false,
|
||||
homeButton: false,
|
||||
sceneModePicker: false,
|
||||
navigationHelpButton: false,
|
||||
fullscreenButton: false,
|
||||
vrButton: false,
|
||||
selectionIndicator: false,
|
||||
infoBox: false,
|
||||
baseLayer: false,
|
||||
// Replaces the blocky Tycho-2 default. An option, not `skyBox: false`,
|
||||
// which would also stop CesiumWidget from creating the Sun and Moon.
|
||||
skyBox: new StarrySky(),
|
||||
creditContainer,
|
||||
msaaSamples: 4,
|
||||
contextOptions: { webgl: { preserveDrawingBuffer: true } },
|
||||
showRenderLoopErrors,
|
||||
};
|
||||
}
|
||||
|
||||
/** Create the standard globe viewer in caller-owned, visible containers. */
|
||||
export function createApplicationViewer({
|
||||
container,
|
||||
creditContainer,
|
||||
showRenderLoopErrors,
|
||||
}) {
|
||||
if (!container || !creditContainer)
|
||||
throw new TypeError('Viewer and credit containers are required');
|
||||
const viewer = new Cesium.Viewer(
|
||||
container,
|
||||
applicationViewerOptions(creditContainer, { showRenderLoopErrors }),
|
||||
);
|
||||
try {
|
||||
// Until the render governor takes over (app/tools.js), tick at the idle
|
||||
// rate so the startup load does not compete with drawing at 240 fps.
|
||||
viewer.targetFrameRate = IDLE_FRAME_RATE;
|
||||
// A phone pinch spans fewer screen pixels than desktop zoom gestures.
|
||||
// Keep Cesium's distance-aware zoom and collision limits, with less travel
|
||||
// required on touch-first screens. Mouse/trackpad sensitivity stays native.
|
||||
if (globalThis.matchMedia?.('(pointer: coarse)').matches)
|
||||
viewer.scene.screenSpaceCameraController.zoomFactor *= 3;
|
||||
limitZoomOut(viewer);
|
||||
// Before any tile builds a draw command: Cesium's per-vertex model
|
||||
// atmosphere fails to LINK on Apple's Metal backend and kills the
|
||||
// render loop. See app/atmosphereCompat.js.
|
||||
applyModelAtmosphereWorkaround(viewer.scene);
|
||||
viewer.scene.globe.show = false;
|
||||
viewer.scene.skyAtmosphere.show = true;
|
||||
viewer.scene.skyAtmosphere.atmosphereLightIntensity = 18;
|
||||
viewer.scene.skyAtmosphere.saturationShift = -0.12;
|
||||
viewer.scene.skyAtmosphere.brightnessShift = -0.08;
|
||||
return viewer;
|
||||
} catch (error) {
|
||||
viewer.destroy();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
// A hand zooming out stops while the globe is still a fair share of the
|
||||
// screen, on any screen's shape, rather than leaving it a speck.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { limitZoomOut, zoomOutLimit } from './viewer.js';
|
||||
|
||||
// The share of the screen's height the globe spans from `altitude`.
|
||||
function globeShare(altitude, fovy) {
|
||||
const radius = Cesium.Ellipsoid.WGS84.maximumRadius;
|
||||
const angular = Math.asin(radius / (radius + altitude));
|
||||
return Math.tan(angular) / Math.tan(fovy / 2);
|
||||
}
|
||||
|
||||
test("zooming out stops with the globe 30% of the screen's height across", () => {
|
||||
for (const fovy of [Math.PI / 3, 0.4, 0.2]) {
|
||||
const limit = zoomOutLimit(fovy);
|
||||
assert.ok(Math.abs(globeShare(limit, fovy) - 0.3) < 1e-9, `fovy ${fovy}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('a wide screen, whose view is narrower, may zoom out farther', () => {
|
||||
assert.ok(zoomOutLimit(0.4) > zoomOutLimit(Math.PI / 3));
|
||||
assert.ok(zoomOutLimit(Math.PI / 3) > 20_000_000, 'past the views a link opens');
|
||||
});
|
||||
|
||||
function fakeViewer({ fovy = Math.PI / 3, height = 10_000_000 } = {}) {
|
||||
const scene = {
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
preRender: new Cesium.Event(),
|
||||
screenSpaceCameraController: { maximumZoomDistance: Infinity },
|
||||
};
|
||||
const camera = {
|
||||
frustum: { fovy },
|
||||
positionCartographic: { height },
|
||||
};
|
||||
return { scene, camera };
|
||||
}
|
||||
|
||||
test('the limit follows the screen, and holds a camera already past it', () => {
|
||||
const viewer = fakeViewer();
|
||||
const controller = viewer.scene.screenSpaceCameraController;
|
||||
const stop = limitZoomOut(viewer);
|
||||
viewer.scene.preRender.raiseEvent();
|
||||
assert.equal(controller.maximumZoomDistance, zoomOutLimit(Math.PI / 3));
|
||||
|
||||
// A wider screen narrows the view, and the globe may go farther.
|
||||
viewer.camera.frustum.fovy = 0.4;
|
||||
viewer.scene.preRender.raiseEvent();
|
||||
assert.equal(controller.maximumZoomDistance, zoomOutLimit(0.4));
|
||||
|
||||
// Flown past it, the next zoom out stops there instead of jumping in.
|
||||
viewer.camera.positionCartographic.height = zoomOutLimit(0.4) * 2;
|
||||
viewer.scene.preRender.raiseEvent();
|
||||
assert.equal(controller.maximumZoomDistance, zoomOutLimit(0.4) * 2);
|
||||
|
||||
stop();
|
||||
viewer.camera.positionCartographic.height = 0;
|
||||
viewer.scene.preRender.raiseEvent();
|
||||
assert.equal(controller.maximumZoomDistance, zoomOutLimit(0.4) * 2);
|
||||
});
|
||||
|
||||
test('flat maps keep zooming out unlimited', () => {
|
||||
const viewer = fakeViewer();
|
||||
const controller = viewer.scene.screenSpaceCameraController;
|
||||
limitZoomOut(viewer);
|
||||
viewer.scene.preRender.raiseEvent();
|
||||
assert.ok(Number.isFinite(controller.maximumZoomDistance));
|
||||
viewer.scene.mode = Cesium.SceneMode.SCENE2D;
|
||||
viewer.camera.frustum = {};
|
||||
viewer.scene.preRender.raiseEvent();
|
||||
assert.equal(controller.maximumZoomDistance, Infinity);
|
||||
});
|
||||
@@ -1,241 +0,0 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { governorRequestRender } from '../renderGovernor.js';
|
||||
|
||||
/** Whole-Earth input limit; explicit camera destinations can go farther. */
|
||||
export const MAXIMUM_ZOOM_DISTANCE_M = 40_000_000;
|
||||
/** Below this, oblique browsing is left alone. */
|
||||
export const PITCH_CLAMP_MIN_HEIGHT_M = 300_000;
|
||||
/** Look this far below the Earth's limb, so the globe stays on screen. */
|
||||
export const LIMB_MARGIN_RAD = Cesium.Math.toRadians(8);
|
||||
const PITCH_EASE = 0.35;
|
||||
const PITCH_SNAP_RAD = Cesium.Math.toRadians(0.1);
|
||||
const HEIGHT_EPSILON_M = 0.0001;
|
||||
const EARTH_RADIUS_M = 6_371_000;
|
||||
const INPUT_BINDINGS = Object.values(Cesium.CameraEventType).flatMap((type) =>
|
||||
[undefined, ...Object.values(Cesium.KeyboardEventModifier)].map(
|
||||
(modifier) => ({
|
||||
type,
|
||||
modifier,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* The shallowest pitch (radians, negative is down) that still keeps the Earth
|
||||
* framed from height `h`, or null where tilted views are left alone.
|
||||
* The limb sits acos(R / (R + h)) below the local horizontal.
|
||||
*/
|
||||
export function maxPitchForHeight(h) {
|
||||
if (!(h >= PITCH_CLAMP_MIN_HEIGHT_M)) return null;
|
||||
const limb = Math.acos(EARTH_RADIUS_M / (EARTH_RADIUS_M + h));
|
||||
return -Math.min(limb + LIMB_MARGIN_RAD, Cesium.Math.PI_OVER_TWO);
|
||||
}
|
||||
|
||||
function matchesZoomBinding(bindings, type, modifier) {
|
||||
if (Array.isArray(bindings))
|
||||
return bindings.some((binding) =>
|
||||
matchesZoomBinding(binding, type, modifier),
|
||||
);
|
||||
return typeof bindings === 'number'
|
||||
? bindings === type && modifier === undefined
|
||||
: bindings?.eventType === type && bindings?.modifier === modifier;
|
||||
}
|
||||
|
||||
function readInput(aggregator, bindings) {
|
||||
let outward = false;
|
||||
let cancel = false;
|
||||
for (const { type, modifier } of INPUT_BINDINGS) {
|
||||
if (!aggregator.isMoving(type, modifier)) continue;
|
||||
const movement = aggregator.getMovement(type, modifier);
|
||||
const pinch = type === Cesium.CameraEventType.PINCH;
|
||||
const distance = pinch ? movement.distance : movement;
|
||||
const delta = distance.endPosition.y - distance.startPosition.y;
|
||||
// Cesium tilts by the fingers' midpoint while zooming by their spacing,
|
||||
// both in the same quarter-pixel units. Fingers rarely keep a perfectly
|
||||
// even spacing, so the larger of the two movements decides the gesture.
|
||||
const tilt = pinch
|
||||
? movement.angleAndHeight.endPosition.y -
|
||||
movement.angleAndHeight.startPosition.y
|
||||
: 0;
|
||||
if (
|
||||
matchesZoomBinding(bindings, type, modifier) &&
|
||||
Math.abs(delta) > Math.abs(tilt)
|
||||
) {
|
||||
outward ||= delta < 0;
|
||||
cancel ||= delta > 0;
|
||||
} else {
|
||||
// Includes modifier-specific tilts and parallel two-finger movement.
|
||||
cancel = true;
|
||||
}
|
||||
}
|
||||
aggregator.reset();
|
||||
return { outward, cancel };
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep outward user zooms bounded and framed, without taking camera ownership
|
||||
* from tilts, tracked entities or flights. Returns an idempotent disposer.
|
||||
*/
|
||||
export function installZoomOutGuard(
|
||||
viewer,
|
||||
{
|
||||
requestRender = governorRequestRender,
|
||||
subscribeCameraHandoff,
|
||||
createAggregator = (canvas) => new Cesium.CameraEventAggregator(canvas),
|
||||
} = {},
|
||||
) {
|
||||
const scene = viewer?.scene;
|
||||
const controller = scene?.screenSpaceCameraController;
|
||||
const camera = viewer?.camera;
|
||||
const canvas = viewer?.canvas;
|
||||
if (
|
||||
!controller ||
|
||||
!camera ||
|
||||
!canvas ||
|
||||
!scene.preRender ||
|
||||
!scene.postUpdate
|
||||
)
|
||||
throw new TypeError('A complete Cesium viewer is required');
|
||||
|
||||
const aggregator = createAggregator(canvas);
|
||||
const originalMaximumZoomDistance = controller.maximumZoomDistance;
|
||||
const ownsCeiling = originalMaximumZoomDistance > MAXIMUM_ZOOM_DISTANCE_M;
|
||||
let maximumZoomDistance = Math.min(
|
||||
originalMaximumZoomDistance,
|
||||
MAXIMUM_ZOOM_DISTANCE_M,
|
||||
);
|
||||
controller.maximumZoomDistance = maximumZoomDistance;
|
||||
// Cesium clamps any zoom that starts above the limit to the limit, in either
|
||||
// direction. A camera placed higher by a flight or share link keeps its own
|
||||
// height as the limit, so it zooms in gradually and can't climb further.
|
||||
const followCeiling = () => {
|
||||
if (!ownsCeiling || controller.maximumZoomDistance !== maximumZoomDistance)
|
||||
return;
|
||||
// While tracking, Cesium measures zoom from the target, not the Earth, so
|
||||
// the camera's altitude would lift the ceiling with every outward step.
|
||||
const untracked =
|
||||
scene.mode === Cesium.SceneMode.SCENE3D &&
|
||||
Cesium.Matrix4.equals(camera.transform, Cesium.Matrix4.IDENTITY);
|
||||
const height = untracked ? camera.positionCartographic?.height : undefined;
|
||||
maximumZoomDistance =
|
||||
height > MAXIMUM_ZOOM_DISTANCE_M ? height : MAXIMUM_ZOOM_DISTANCE_M;
|
||||
controller.maximumZoomDistance = maximumZoomDistance;
|
||||
};
|
||||
followCeiling();
|
||||
|
||||
let lastHeight = camera.positionCartographic?.height;
|
||||
let lastPosition = Cesium.Cartesian3.clone(camera.position);
|
||||
let lastHeading = camera.heading;
|
||||
let lastPitch = camera.pitch;
|
||||
let lastRoll = camera.roll;
|
||||
let zoomingOut = false;
|
||||
let settling = false;
|
||||
const cancel = () => {
|
||||
zoomingOut = false;
|
||||
settling = false;
|
||||
};
|
||||
const guard = () => {
|
||||
const input = readInput(aggregator, controller.zoomEventTypes);
|
||||
const height = camera.positionCartographic?.height;
|
||||
const climbing = height > lastHeight + HEIGHT_EPSILON_M;
|
||||
const descending = height < lastHeight - HEIGHT_EPSILON_M;
|
||||
try {
|
||||
if (
|
||||
scene.mode !== Cesium.SceneMode.SCENE3D ||
|
||||
controller.enableInputs === false ||
|
||||
controller.enableZoom === false ||
|
||||
!Cesium.Matrix4.equals(camera.transform, Cesium.Matrix4.IDENTITY) ||
|
||||
// Cesium has no public running-flight flag.
|
||||
camera._currentFlight ||
|
||||
input.cancel ||
|
||||
(descending && !settling)
|
||||
) {
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
if (input.outward) {
|
||||
zoomingOut = true;
|
||||
// A genuine outward gesture can be blocked by the controller's ceiling.
|
||||
settling = true;
|
||||
}
|
||||
if (climbing) {
|
||||
if (!zoomingOut) return;
|
||||
settling = true;
|
||||
} else {
|
||||
zoomingOut = false;
|
||||
// Outward inertia can lower altitude when Cesium clamps slant range at
|
||||
// the ceiling. Finish that correction; fresh inward input cancels above.
|
||||
// A stationary correction owns only the pose it last produced.
|
||||
if (
|
||||
!input.outward &&
|
||||
((!descending &&
|
||||
!Cesium.Cartesian3.equals(camera.position, lastPosition)) ||
|
||||
Math.abs(Cesium.Math.negativePiToPi(camera.heading - lastHeading)) >
|
||||
1e-10 ||
|
||||
Math.abs(camera.pitch - lastPitch) > 1e-10 ||
|
||||
Math.abs(Cesium.Math.negativePiToPi(camera.roll - lastRoll)) >
|
||||
1e-10)
|
||||
)
|
||||
settling = false;
|
||||
if (!settling) return;
|
||||
}
|
||||
const maxPitch = maxPitchForHeight(height);
|
||||
if (maxPitch === null || !(camera.pitch > maxPitch)) {
|
||||
settling = false;
|
||||
} else {
|
||||
const error = maxPitch - camera.pitch;
|
||||
const easedPitch =
|
||||
Math.abs(error) <= PITCH_SNAP_RAD
|
||||
? maxPitch
|
||||
: camera.pitch + error * PITCH_EASE;
|
||||
// A large wheel step must not leave the view above the limb while easing.
|
||||
const limbPitch = -Math.acos(
|
||||
EARTH_RADIUS_M / (EARTH_RADIUS_M + height),
|
||||
);
|
||||
const pitch = Math.min(easedPitch, limbPitch);
|
||||
camera.setView({
|
||||
orientation: { heading: camera.heading, pitch, roll: camera.roll },
|
||||
});
|
||||
settling = pitch > maxPitch;
|
||||
}
|
||||
// Observe the end of inertia too; no arbitrary timeout cuts off a long zoom.
|
||||
if (zoomingOut || settling) requestRender('zoom-out-guard');
|
||||
} finally {
|
||||
lastHeight = camera.positionCartographic?.height;
|
||||
lastPosition = Cesium.Cartesian3.clone(camera.position, lastPosition);
|
||||
lastHeading = camera.heading;
|
||||
lastPitch = camera.pitch;
|
||||
lastRoll = camera.roll;
|
||||
}
|
||||
};
|
||||
const removePreRender = scene.preRender.addEventListener(guard);
|
||||
// Fires every frame, after Cesium has applied this frame's input, while
|
||||
// preRender fires only on frames that draw. Input that didn't move the camera
|
||||
// (such as wheel at the ceiling) would otherwise wait for an unrelated frame.
|
||||
const removePostUpdate = scene.postUpdate.addEventListener(() => {
|
||||
followCeiling();
|
||||
if (
|
||||
INPUT_BINDINGS.some(({ type, modifier }) =>
|
||||
aggregator.isMoving(type, modifier),
|
||||
)
|
||||
)
|
||||
requestRender('zoom-out-guard');
|
||||
});
|
||||
const removeCameraHandoff = subscribeCameraHandoff?.(() => {
|
||||
cancel();
|
||||
// Discard input queued before an explicit navigation action took ownership.
|
||||
aggregator.reset();
|
||||
});
|
||||
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
removeCameraHandoff?.();
|
||||
removePreRender?.();
|
||||
removePostUpdate?.();
|
||||
aggregator.destroy();
|
||||
if (controller.maximumZoomDistance === maximumZoomDistance)
|
||||
controller.maximumZoomDistance = originalMaximumZoomDistance;
|
||||
};
|
||||
}
|
||||
@@ -1,764 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
installZoomOutGuard,
|
||||
maxPitchForHeight,
|
||||
MAXIMUM_ZOOM_DISTANCE_M,
|
||||
} from './zoomOutGuard.js';
|
||||
|
||||
const deg = Cesium.Math.toDegrees;
|
||||
const { WHEEL, PINCH, RIGHT_DRAG, LEFT_DRAG, MIDDLE_DRAG } =
|
||||
Cesium.CameraEventType;
|
||||
const { CTRL, SHIFT, ALT } = Cesium.KeyboardEventModifier;
|
||||
|
||||
test('maxPitchForHeight leaves low-altitude tilt alone', () => {
|
||||
assert.equal(maxPitchForHeight(0), null);
|
||||
assert.equal(maxPitchForHeight(299_999), null);
|
||||
assert.equal(maxPitchForHeight(NaN), null);
|
||||
assert.equal(maxPitchForHeight(undefined), null);
|
||||
});
|
||||
|
||||
test('maxPitchForHeight looks 8 degrees below the limb', () => {
|
||||
assert.ok(Math.abs(deg(maxPitchForHeight(1_000_000)) + 38.19) < 0.01);
|
||||
assert.equal(deg(maxPitchForHeight(1e12)), -90);
|
||||
});
|
||||
|
||||
test('maxPitchForHeight steepens monotonically with height', () => {
|
||||
let previous = 0;
|
||||
for (let h = 300_000; h <= 100_000_000; h *= 1.5) {
|
||||
const pitch = maxPitchForHeight(h);
|
||||
assert.ok(pitch <= previous, `pitch at ${h} m`);
|
||||
previous = pitch;
|
||||
}
|
||||
});
|
||||
|
||||
function guardFixture({ maximumZoomDistance = Infinity } = {}) {
|
||||
const preRender = new Set();
|
||||
const postUpdate = new Set();
|
||||
const handoffs = new Set();
|
||||
const container = new EventTarget();
|
||||
const canvas = new EventTarget();
|
||||
const movements = new Map();
|
||||
const key = (type, modifier) => `${type}:${modifier}`;
|
||||
const aggregator = {
|
||||
resets: 0,
|
||||
destroys: 0,
|
||||
isMoving: (type, modifier) => movements.has(key(type, modifier)),
|
||||
getMovement: (type, modifier) => movements.get(key(type, modifier)),
|
||||
reset() {
|
||||
movements.clear();
|
||||
this.resets++;
|
||||
},
|
||||
destroy() {
|
||||
this.destroys++;
|
||||
movements.clear();
|
||||
},
|
||||
};
|
||||
const camera = {
|
||||
height: 170_000,
|
||||
longitude: 0,
|
||||
latitude: 0,
|
||||
heading: 0.4,
|
||||
pitch: Cesium.Math.toRadians(-25),
|
||||
roll: 0,
|
||||
transform: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
|
||||
views: [],
|
||||
get positionCartographic() {
|
||||
return {
|
||||
height: this.height,
|
||||
longitude: this.longitude,
|
||||
latitude: this.latitude,
|
||||
};
|
||||
},
|
||||
get position() {
|
||||
return this.positionWC;
|
||||
},
|
||||
get positionWC() {
|
||||
return Cesium.Cartesian3.fromRadians(
|
||||
this.longitude,
|
||||
this.latitude,
|
||||
this.height,
|
||||
);
|
||||
},
|
||||
setView({ orientation }) {
|
||||
this.views.push(orientation);
|
||||
this.heading = orientation.heading;
|
||||
this.pitch = orientation.pitch;
|
||||
this.roll = orientation.roll;
|
||||
},
|
||||
};
|
||||
const controller = {
|
||||
maximumZoomDistance,
|
||||
enableInputs: true,
|
||||
enableZoom: true,
|
||||
zoomEventTypes: [
|
||||
RIGHT_DRAG,
|
||||
WHEEL,
|
||||
PINCH,
|
||||
{ eventType: WHEEL, modifier: CTRL },
|
||||
],
|
||||
};
|
||||
const scene = {
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
screenSpaceCameraController: controller,
|
||||
preRender: {
|
||||
addEventListener(handler) {
|
||||
preRender.add(handler);
|
||||
return () => preRender.delete(handler);
|
||||
},
|
||||
},
|
||||
postUpdate: {
|
||||
addEventListener(handler) {
|
||||
postUpdate.add(handler);
|
||||
return () => postUpdate.delete(handler);
|
||||
},
|
||||
},
|
||||
};
|
||||
const renders = [];
|
||||
const dispose = installZoomOutGuard(
|
||||
{ camera, container, canvas, scene },
|
||||
{
|
||||
subscribeCameraHandoff(listener) {
|
||||
handoffs.add(listener);
|
||||
return () => handoffs.delete(listener);
|
||||
},
|
||||
createAggregator(element) {
|
||||
assert.equal(element, canvas);
|
||||
return aggregator;
|
||||
},
|
||||
requestRender: (reason) => renders.push(reason),
|
||||
},
|
||||
);
|
||||
// A frame Cesium skips drawing in request-render mode: no preRender.
|
||||
const idleFrame = () => {
|
||||
for (const handler of postUpdate) handler();
|
||||
};
|
||||
const frame = (height = camera.height) => {
|
||||
camera.height = height;
|
||||
idleFrame();
|
||||
for (const handler of preRender) handler();
|
||||
};
|
||||
const movement = (type, deltaY, { modifier, tiltDeltaY = 0 } = {}) => {
|
||||
const distance = {
|
||||
startPosition: new Cesium.Cartesian2(0, 0),
|
||||
endPosition: new Cesium.Cartesian2(0, deltaY),
|
||||
};
|
||||
movements.set(
|
||||
key(type, modifier),
|
||||
type === PINCH
|
||||
? {
|
||||
distance,
|
||||
angleAndHeight: {
|
||||
startPosition: new Cesium.Cartesian2(0, 0),
|
||||
endPosition: new Cesium.Cartesian2(0, tiltDeltaY),
|
||||
},
|
||||
}
|
||||
: distance,
|
||||
);
|
||||
// Also exercise the former raw DOM path when running against the PR head.
|
||||
const event = new Event(
|
||||
type === WHEEL ? 'wheel' : type === PINCH ? 'touchmove' : 'pointermove',
|
||||
);
|
||||
Object.assign(event, {
|
||||
buttons: type === RIGHT_DRAG ? 2 : type === MIDDLE_DRAG ? 4 : 1,
|
||||
ctrlKey: modifier === CTRL,
|
||||
shiftKey: modifier === SHIFT,
|
||||
altKey: modifier === ALT,
|
||||
touches: type === PINCH ? [1, 2] : [],
|
||||
});
|
||||
container.dispatchEvent(event);
|
||||
};
|
||||
return {
|
||||
camera,
|
||||
controller,
|
||||
scene,
|
||||
aggregator,
|
||||
preRender,
|
||||
postUpdate,
|
||||
handoffs,
|
||||
handoff: () => {
|
||||
for (const listener of handoffs) listener();
|
||||
},
|
||||
renders,
|
||||
dispose,
|
||||
frame,
|
||||
idleFrame,
|
||||
movement,
|
||||
};
|
||||
}
|
||||
|
||||
test('a tilted wheel zoom-out pitches down and preserves heading and roll', () => {
|
||||
const f = guardFixture();
|
||||
f.frame();
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(1_000_000);
|
||||
const target = maxPitchForHeight(1_000_000);
|
||||
assert.ok(f.camera.pitch < Cesium.Math.toRadians(-25));
|
||||
assert.ok(f.camera.pitch > target, 'eases rather than snapping');
|
||||
assert.equal(f.camera.heading, 0.4);
|
||||
assert.equal(f.camera.roll, 0);
|
||||
for (let i = 1; i <= 40; i++) f.frame(1_000_000 + i);
|
||||
assert.ok(
|
||||
Math.abs(f.camera.pitch - maxPitchForHeight(f.camera.height)) < 1e-3,
|
||||
);
|
||||
assert.ok(f.renders.length > 0);
|
||||
});
|
||||
|
||||
test('a large outward step immediately keeps the Earth limb in view', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(WHEEL, -100);
|
||||
f.frame(20_000_000);
|
||||
const limbPitch = -Math.acos(6_371_000 / (6_371_000 + 20_000_000));
|
||||
assert.ok(f.camera.pitch <= limbPitch);
|
||||
assert.ok(f.camera.pitch > maxPitchForHeight(20_000_000));
|
||||
});
|
||||
|
||||
test('pinch, right-drag and configured Ctrl+wheel can zoom out', () => {
|
||||
for (const [type, modifier] of [[PINCH], [RIGHT_DRAG], [WHEEL, CTRL]]) {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(type, -10, { modifier });
|
||||
f.frame(700_000);
|
||||
assert.equal(f.camera.views.length, 1, `${type}:${modifier}`);
|
||||
f.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('Ctrl+right-drag tilt is left at the pose chosen by Cesium', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(RIGHT_DRAG, 3, { modifier: CTRL });
|
||||
// Real Cesium's orbit tilt raises altitude with no zoom movement.
|
||||
f.camera.pitch = Cesium.Math.toRadians(-26.07722459498313);
|
||||
f.frame(529_392.3759876974);
|
||||
assert.equal(f.camera.views.length, 0);
|
||||
assert.equal(deg(f.camera.pitch), -26.07722459498313);
|
||||
});
|
||||
|
||||
test('parallel two-finger tilt is not mistaken for pinch zoom', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(PINCH, 0, { tiltDeltaY: 3 });
|
||||
f.frame(600_000);
|
||||
assert.equal(f.camera.views.length, 0);
|
||||
});
|
||||
|
||||
test('two-finger tilt with finger-spacing drift is left to Cesium', () => {
|
||||
for (const [spacing, tilt] of [
|
||||
[-0.01, 3],
|
||||
[-2, 3],
|
||||
[-3, -3],
|
||||
]) {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(PINCH, spacing, { tiltDeltaY: tilt });
|
||||
// Real Cesium's two-finger tilt climbs and picks its own pitch.
|
||||
f.camera.pitch = Cesium.Math.toRadians(-26.07746);
|
||||
f.frame(529_406);
|
||||
assert.equal(f.camera.views.length, 0, `${spacing}, ${tilt}`);
|
||||
f.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('a pinch that closes the fingers more than it moves them still zooms out', () => {
|
||||
// One finger still, the other sliding towards it: the midpoint moves half as far.
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(PINCH, -10, { tiltDeltaY: -5 });
|
||||
f.frame(700_000);
|
||||
assert.equal(f.camera.views.length, 1);
|
||||
f.dispose();
|
||||
});
|
||||
|
||||
test('unconfigured wheel modifiers and one-finger drag do not enable the guard', () => {
|
||||
for (const [type, modifier] of [[WHEEL, SHIFT], [WHEEL, ALT], [LEFT_DRAG]]) {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(type, -10, { modifier });
|
||||
f.frame(600_000);
|
||||
assert.equal(f.camera.views.length, 0, `${type}:${modifier}`);
|
||||
f.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('current controller zoom bindings are honored', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.controller.zoomEventTypes = { eventType: MIDDLE_DRAG, modifier: ALT };
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(600_000);
|
||||
assert.equal(f.camera.views.length, 0);
|
||||
f.movement(MIDDLE_DRAG, -10, { modifier: ALT });
|
||||
f.frame(700_000);
|
||||
assert.equal(f.camera.views.length, 1);
|
||||
});
|
||||
|
||||
test('programmatic height changes alone never activate the guard', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(170_000);
|
||||
f.frame(2_000_000);
|
||||
f.frame(3_000_000);
|
||||
assert.equal(f.camera.views.length, 0);
|
||||
});
|
||||
|
||||
test('inward zoom does not activate the guard even when altitude rises', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(WHEEL, 10);
|
||||
f.frame(600_000);
|
||||
assert.equal(f.camera.views.length, 0);
|
||||
});
|
||||
|
||||
test('outward input with falling height does not alter pitch', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(2_000_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(1_500_000);
|
||||
f.frame(1_500_000);
|
||||
assert.equal(f.camera.views.length, 0);
|
||||
});
|
||||
|
||||
test('pitch finishes settling when the zoom stops changing height', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(2_000_000);
|
||||
const firstPitch = f.camera.pitch;
|
||||
for (let i = 0; i < 40; i++) f.frame();
|
||||
assert.ok(f.camera.pitch < firstPitch);
|
||||
assert.ok(Math.abs(f.camera.pitch - maxPitchForHeight(2_000_000)) < 1e-10);
|
||||
const views = f.camera.views.length;
|
||||
f.frame();
|
||||
assert.equal(
|
||||
f.camera.views.length,
|
||||
views,
|
||||
'settled pose does not keep rendering',
|
||||
);
|
||||
});
|
||||
|
||||
test('completed settling does not authorize a later programmatic climb', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(700_000);
|
||||
for (let i = 0; i < 40; i++) f.frame();
|
||||
const views = f.camera.views.length;
|
||||
f.frame(3_000_000);
|
||||
assert.equal(f.camera.views.length, views);
|
||||
});
|
||||
|
||||
test('a fresh inward zoom or unrelated gesture cancels pending correction', () => {
|
||||
for (const [type, delta, options] of [
|
||||
[WHEEL, 10, {}],
|
||||
[RIGHT_DRAG, 3, { modifier: CTRL }],
|
||||
[LEFT_DRAG, 3, {}],
|
||||
[MIDDLE_DRAG, 3, {}],
|
||||
[PINCH, 0, { tiltDeltaY: 3 }],
|
||||
]) {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(700_000);
|
||||
const views = f.camera.views.length;
|
||||
f.movement(type, delta, options);
|
||||
f.frame(800_000);
|
||||
f.frame(900_000);
|
||||
assert.equal(f.camera.views.length, views, `${type}:${options.modifier}`);
|
||||
f.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('an external pose change at fixed height cancels pending correction', () => {
|
||||
for (const field of ['heading', 'pitch', 'roll', 'longitude', 'latitude']) {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(700_000);
|
||||
const views = f.camera.views.length;
|
||||
f.camera[field] += 0.1;
|
||||
f.frame();
|
||||
f.frame(900_000);
|
||||
assert.equal(f.camera.views.length, views, field);
|
||||
f.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('disabled controls, flights, tracked transforms and non-3D scenes cancel intent', () => {
|
||||
const cases = [
|
||||
(f) => {
|
||||
f.controller.enableInputs = false;
|
||||
return () => {
|
||||
f.controller.enableInputs = true;
|
||||
};
|
||||
},
|
||||
(f) => {
|
||||
f.controller.enableZoom = false;
|
||||
return () => {
|
||||
f.controller.enableZoom = true;
|
||||
};
|
||||
},
|
||||
(f) => {
|
||||
f.camera._currentFlight = {};
|
||||
return () => {
|
||||
delete f.camera._currentFlight;
|
||||
};
|
||||
},
|
||||
(f) => {
|
||||
f.camera.transform = Cesium.Matrix4.fromTranslation(
|
||||
new Cesium.Cartesian3(1, 2, 3),
|
||||
);
|
||||
return () => {
|
||||
f.camera.transform = Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY);
|
||||
};
|
||||
},
|
||||
(f) => {
|
||||
f.scene.mode = Cesium.SceneMode.SCENE2D;
|
||||
return () => {
|
||||
f.scene.mode = Cesium.SceneMode.SCENE3D;
|
||||
};
|
||||
},
|
||||
];
|
||||
for (const block of cases) {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(700_000);
|
||||
const views = f.camera.views.length;
|
||||
const restore = block(f);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(800_000);
|
||||
restore();
|
||||
f.frame(900_000);
|
||||
assert.equal(f.camera.views.length, views);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(1_000_000);
|
||||
assert.equal(f.camera.views.length, views + 1);
|
||||
f.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('installer sets the ceiling and disposer releases aggregator and frame listener', () => {
|
||||
const f = guardFixture();
|
||||
assert.equal(f.controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
|
||||
assert.equal(f.preRender.size, 1);
|
||||
assert.equal(f.postUpdate.size, 1);
|
||||
f.frame();
|
||||
assert.ok(f.aggregator.resets > 0);
|
||||
f.dispose();
|
||||
f.dispose();
|
||||
assert.equal(f.controller.maximumZoomDistance, Infinity);
|
||||
assert.equal(f.aggregator.destroys, 1);
|
||||
assert.equal(f.preRender.size, 0);
|
||||
assert.equal(f.postUpdate.size, 0);
|
||||
assert.equal(f.handoffs.size, 0);
|
||||
});
|
||||
|
||||
test('installer preserves a stricter host zoom ceiling', () => {
|
||||
const f = guardFixture({ maximumZoomDistance: 123 });
|
||||
assert.equal(f.controller.maximumZoomDistance, 123);
|
||||
f.dispose();
|
||||
assert.equal(f.controller.maximumZoomDistance, 123);
|
||||
});
|
||||
|
||||
test('disposer keeps a ceiling someone else changed later', () => {
|
||||
const f = guardFixture();
|
||||
f.controller.maximumZoomDistance = 5;
|
||||
f.dispose();
|
||||
assert.equal(f.controller.maximumZoomDistance, 5);
|
||||
});
|
||||
|
||||
test('installer rejects an incomplete viewer', () => {
|
||||
assert.throws(() => installZoomOutGuard({}), TypeError);
|
||||
});
|
||||
|
||||
test('outward input at the ceiling reframes a deliberately tilted camera', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(MAXIMUM_ZOOM_DISTANCE_M);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame();
|
||||
for (let i = 0; i < 40; i++) f.frame();
|
||||
assert.ok(
|
||||
Math.abs(f.camera.pitch - maxPitchForHeight(MAXIMUM_ZOOM_DISTANCE_M)) <
|
||||
1e-10,
|
||||
);
|
||||
f.dispose();
|
||||
});
|
||||
|
||||
test('input that leaves the camera still requests a frame to read it', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(MAXIMUM_ZOOM_DISTANCE_M);
|
||||
f.idleFrame();
|
||||
assert.deepEqual(f.renders, [], 'an idle scene stays idle');
|
||||
// At the ceiling Cesium doesn't move the camera, so nothing would draw.
|
||||
f.movement(WHEEL, -10);
|
||||
f.idleFrame();
|
||||
assert.deepEqual(f.renders, ['zoom-out-guard']);
|
||||
f.frame();
|
||||
assert.ok(f.camera.pitch < Cesium.Math.toRadians(-25), 'read that frame');
|
||||
f.dispose();
|
||||
});
|
||||
|
||||
test('equivalent heading and roll wraps do not cancel stationary settling', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(500_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(2_000_000);
|
||||
f.camera.heading += Cesium.Math.TWO_PI;
|
||||
f.camera.roll += Cesium.Math.TWO_PI;
|
||||
for (let i = 0; i < 40; i++) f.frame();
|
||||
assert.ok(Math.abs(f.camera.pitch - maxPitchForHeight(2_000_000)) < 1e-10);
|
||||
f.dispose();
|
||||
});
|
||||
|
||||
test('a real Cesium camera settles across the north heading wrap at Istanbul', () => {
|
||||
const scene = {
|
||||
canvas: { clientWidth: 1200, clientHeight: 800, width: 1200, height: 800 },
|
||||
drawingBufferWidth: 1200,
|
||||
drawingBufferHeight: 800,
|
||||
mapProjection: new Cesium.GeographicProjection(),
|
||||
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
|
||||
mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL,
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
pixelRatio: 1,
|
||||
preRender: new Cesium.Event(),
|
||||
postUpdate: new Cesium.Event(),
|
||||
screenSpaceCameraController: {
|
||||
maximumZoomDistance: Infinity,
|
||||
enableInputs: true,
|
||||
zoomEventTypes: [WHEEL],
|
||||
},
|
||||
};
|
||||
const camera = new Cesium.Camera(scene);
|
||||
scene.camera = camera;
|
||||
const setHeight = (height) =>
|
||||
camera.setView({
|
||||
destination: Cesium.Cartesian3.fromDegrees(28.9784, 41.0082, height),
|
||||
orientation: { heading: 0, pitch: Cesium.Math.toRadians(-25), roll: 0 },
|
||||
});
|
||||
setHeight(1_000_000);
|
||||
let outward = false;
|
||||
const dispose = installZoomOutGuard(
|
||||
{ scene, camera, canvas: scene.canvas },
|
||||
{
|
||||
createAggregator: () => ({
|
||||
isMoving: (type, modifier) =>
|
||||
outward && type === WHEEL && modifier === undefined,
|
||||
getMovement: () => ({
|
||||
startPosition: { y: 0 },
|
||||
endPosition: { y: -10 },
|
||||
}),
|
||||
reset: () => {
|
||||
outward = false;
|
||||
},
|
||||
destroy() {},
|
||||
}),
|
||||
requestRender() {},
|
||||
},
|
||||
);
|
||||
try {
|
||||
setHeight(MAXIMUM_ZOOM_DISTANCE_M);
|
||||
outward = true;
|
||||
for (let i = 0; i < 40; i++) scene.preRender.raiseEvent(scene);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
camera.pitch - maxPitchForHeight(camera.positionCartographic.height),
|
||||
) < 1e-8,
|
||||
);
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('an outward inertia ceiling adjustment can descend while pitch settles', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(39_000_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(39_999_999);
|
||||
const before = f.camera.pitch;
|
||||
// Cesium limits slant range on an inertial pick, slightly below the altitude cap.
|
||||
f.frame(39_997_258);
|
||||
for (let i = 0; i < 40; i++) f.frame();
|
||||
assert.ok(f.camera.pitch < before);
|
||||
assert.ok(
|
||||
Math.abs(f.camera.pitch - maxPitchForHeight(f.camera.height)) < 1e-10,
|
||||
);
|
||||
f.dispose();
|
||||
});
|
||||
|
||||
test('a descending programmatic tilt cancels pending correction', () => {
|
||||
const f = guardFixture();
|
||||
f.frame(39_000_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(39_999_999);
|
||||
const count = f.camera.views.length;
|
||||
f.camera.pitch += 0.1;
|
||||
f.frame(39_997_258);
|
||||
for (let i = 0; i < 40; i++) f.frame();
|
||||
assert.equal(f.camera.views.length, count);
|
||||
f.dispose();
|
||||
});
|
||||
|
||||
test('explicit navigation cancels outward inertia before a climbing UI tilt', () => {
|
||||
const f = guardFixture();
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(1_000_000);
|
||||
f.movement(WHEEL, -10);
|
||||
f.handoff();
|
||||
const writes = f.camera.views.length;
|
||||
f.camera.pitch = Cesium.Math.toRadians(-25);
|
||||
f.frame(1_100_000);
|
||||
f.frame(1_200_000);
|
||||
assert.equal(f.camera.views.length, writes);
|
||||
assert.equal(deg(f.camera.pitch), -25);
|
||||
// A subsequent user zoom starts a new correction normally.
|
||||
f.movement(WHEEL, -10);
|
||||
f.frame(1_300_000);
|
||||
assert.ok(f.camera.views.length > writes);
|
||||
f.dispose();
|
||||
});
|
||||
|
||||
// A real Cesium camera and controller, fed by DOM wheel events on the canvas.
|
||||
function realControllerScene(startHeight) {
|
||||
const canvas = Object.assign(new EventTarget(), {
|
||||
clientWidth: 1200,
|
||||
clientHeight: 800,
|
||||
width: 1200,
|
||||
height: 800,
|
||||
style: {},
|
||||
// Keep Cesium's input handler off the missing `document`.
|
||||
disableRootEvents: true,
|
||||
onwheel: null,
|
||||
getBoundingClientRect: () => ({
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: 1200,
|
||||
height: 800,
|
||||
}),
|
||||
});
|
||||
const scene = {
|
||||
canvas,
|
||||
drawingBufferWidth: 1200,
|
||||
drawingBufferHeight: 800,
|
||||
mapProjection: new Cesium.GeographicProjection(),
|
||||
ellipsoid: Cesium.Ellipsoid.WGS84,
|
||||
mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL,
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
pixelRatio: 1,
|
||||
verticalExaggeration: 1,
|
||||
verticalExaggerationRelativeHeight: 0,
|
||||
preRender: new Cesium.Event(),
|
||||
postUpdate: new Cesium.Event(),
|
||||
};
|
||||
const camera = new Cesium.Camera(scene);
|
||||
scene.camera = camera;
|
||||
const controller = new Cesium.ScreenSpaceCameraController(scene);
|
||||
controller.inertiaZoom = 0;
|
||||
scene.screenSpaceCameraController = controller;
|
||||
const setHeight = (h) =>
|
||||
camera.setView({
|
||||
destination: Cesium.Cartesian3.fromDegrees(28.9784, 41.0082, h),
|
||||
orientation: { heading: 0, pitch: -Cesium.Math.PI_OVER_TWO, roll: 0 },
|
||||
});
|
||||
setHeight(startHeight);
|
||||
const dispose = installZoomOutGuard(
|
||||
{ scene, camera, canvas },
|
||||
{ requestRender() {} },
|
||||
);
|
||||
// Scene.render order: the controller applies input, then postUpdate, then
|
||||
// preRender on frames that draw.
|
||||
const frame = () => {
|
||||
controller.update();
|
||||
scene.postUpdate.raiseEvent(scene);
|
||||
scene.preRender.raiseEvent(scene);
|
||||
};
|
||||
const wheel = (deltaY) =>
|
||||
canvas.dispatchEvent(
|
||||
Object.assign(new Event('wheel'), {
|
||||
deltaY,
|
||||
deltaMode: 0,
|
||||
clientX: 600,
|
||||
clientY: 400,
|
||||
}),
|
||||
);
|
||||
const height = () => camera.positionCartographic.height;
|
||||
return {
|
||||
scene,
|
||||
camera,
|
||||
controller,
|
||||
setHeight,
|
||||
frame,
|
||||
wheel,
|
||||
height,
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
|
||||
test('a camera placed above the ceiling cannot zoom out and zooms in without a jump', () => {
|
||||
const s = realControllerScene(60_000_000);
|
||||
try {
|
||||
s.frame();
|
||||
s.wheel(1);
|
||||
s.frame();
|
||||
assert.ok(Math.abs(s.height() - 60_000_000) < 1, `${s.height()} m`);
|
||||
s.wheel(-1);
|
||||
s.frame();
|
||||
const firstStep = s.height();
|
||||
assert.ok(firstStep < 60_000_000, 'zooms in');
|
||||
assert.ok(firstStep > 50_000_000, `${firstStep} m is gradual`);
|
||||
// The camera can no longer climb back above where it has descended to.
|
||||
s.wheel(1);
|
||||
s.frame();
|
||||
assert.ok(Math.abs(s.height() - firstStep) < 1, `${s.height()} m`);
|
||||
for (let i = 0; i < 40; i++) {
|
||||
s.wheel(-100);
|
||||
s.frame();
|
||||
}
|
||||
assert.ok(s.height() < MAXIMUM_ZOOM_DISTANCE_M);
|
||||
assert.equal(s.controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
|
||||
for (let i = 0; i < 80; i++) {
|
||||
s.wheel(100);
|
||||
s.frame();
|
||||
}
|
||||
assert.ok(Math.abs(s.height() - MAXIMUM_ZOOM_DISTANCE_M) < 1_000);
|
||||
} finally {
|
||||
s.dispose();
|
||||
}
|
||||
assert.equal(s.controller.maximumZoomDistance, Infinity);
|
||||
});
|
||||
|
||||
test('a share-link view restored above the ceiling is honoured by later frames', () => {
|
||||
const s = realControllerScene(1_000_000);
|
||||
try {
|
||||
s.frame();
|
||||
s.setHeight(97_679_259);
|
||||
s.frame();
|
||||
s.wheel(100);
|
||||
s.frame();
|
||||
assert.ok(Math.abs(s.height() - 97_679_259) < 1, `${s.height()} m`);
|
||||
} finally {
|
||||
s.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('a tracked camera cannot climb past the ceiling from its target', () => {
|
||||
const s = realControllerScene(1_000_000);
|
||||
try {
|
||||
s.frame();
|
||||
// In look-at mode Cesium measures zoom from the target, not the Earth.
|
||||
s.camera.lookAt(
|
||||
Cesium.Cartesian3.fromDegrees(0, 0, 35_786_000),
|
||||
new Cesium.HeadingPitchRange(0, -0.5, 5_000_000),
|
||||
);
|
||||
for (let i = 0; i < 20; i++) {
|
||||
s.wheel(100);
|
||||
s.frame();
|
||||
}
|
||||
const range = Cesium.Cartesian3.magnitude(s.camera.position);
|
||||
assert.ok(range <= MAXIMUM_ZOOM_DISTANCE_M + 1_000, `${range} m`);
|
||||
assert.equal(s.controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
|
||||
} finally {
|
||||
s.dispose();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user