diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 85ccddf5e..382b2c71a 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -107,6 +107,20 @@ optional, so a renderer written before it still conforms: its image fill turns with it. The Cesium port drapes image fills too, each on a ground primitive of its own. A renderer that predates it draws the rectangle unturned. +- `camera.controls.keepEarthFramed` (capability `keepEarthFramed`) stops + the user's outward zooms at a whole-Earth view (about 40,000 km, or + higher where a camera command left the eye) and, from high up, turns the + view down toward the globe so the whole Earth stays in frame; camera + commands are not held to it and end its turn. The Cesium port eases the + view until the Earth's limb is 8° below its centre line above 300 km + (`zoomOutGuard.js`). The application turns it on where a renderer has it. +- `query.occlusionTest()` (capability `occlusionTest`) tests many points + against the depth of the frames drawn without waiting for the GPU; the + detection overlay leaves out the street vehicles it finds hidden. +- `RendererPlugin.applicationHooks(renderer)` hands the application what + only some renderers have (`ApplicationHooks`); see + [The application and its renderer](#the-application-and-its-renderer). +- `frame.renderNow()` throws when the frame fails to draw. The Cesium port also draws `pattern` line styles (the image repeated `repeat` times along the line, in the translucent pass), lines in the @@ -213,20 +227,27 @@ on (no `renderer.id`, no engine type, no engine object's presence). - **What only the Cesium renderer needs at startup** is done in its `create`: for Cesium, the free-look height limit and keyboard access to its credits' expand link (`src/render/cesium/appRenderer.js`). -- **What a plugin may hand the application beside the contract** goes through - `provideApplicationHooks(renderer, hooks)` (`src/render/applicationHooks.js`), - each hook optional and used only where given: a map engine of its own, - stale command trimming, inline panel rendering, whether an entity is its - own, the zoom-out guard, whether it shows its credits in a display of - its own (`ownCreditDisplay`; otherwise the application's own line, - `src/ui/creditsView.js`, shows the credits port's list), a probe that - tests street vehicles against the frame's depth for the detection overlay - (`createOcclusionProbe`; Cesium's is `src/render/cesium/sceneOcclusionProbe.js`, - and without one every such vehicle's bracket shows), and what QA - scripts read from - `window.__godsEyeView` (Cesium's viewer there, for the scripts that drive - it). None is a contract member, and a renderer without them runs the - application without that behaviour. +- **What a plugin may hand the application beside the contract** is its + `applicationHooks(renderer)` (`ApplicationHooks`, + `src/render/contract/renderer.d.ts`), asked once as the scene creates the + renderer and recorded for the application (`src/render/applicationHooks.js`): + a map engine of its own, stale command trimming, whether an entity is its + own, whether it shows its credits in a display of its own + (`ownCreditDisplay`; otherwise the application's own line, + `src/ui/creditsView.js`, shows the credits port's list), and what QA + scripts read from `window.__godsEyeView` (Cesium's viewer there, for the + scripts that drive it). Each is optional, none is a contract member, and + a renderer without them runs the application without that behaviour. +- **What the renderer should do is in the ports**, each through the + application's own code: outward zooms stop at a whole-Earth view that + stays framed (`camera.controls.keepEarthFramed`, which the scene turns + on; Cesium's is `src/render/cesium/zoomOutGuard.js`); the detection + overlay leaves out street vehicles something stands in front of through + `query.occlusionTest()` under the `occlusionTest` capability (Cesium's is + `src/render/cesium/sceneOcclusionProbe.js`; without it every such + vehicle's bracket shows); and an inline panel whose host stops animation + frames keeps drawing through `resize` and `frame.renderNow()` + (`src/app/panelRendering.js`), stopping at a frame that throws. - **The map stacks** switch through the renderer's own map engine when its plugin hands one, else through its globe port (`src/maps/globeEngine.js`); see `docs/CURRENT-STATE.md` § Map source factories and coordination. diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 0d362e799..33c16fb9c 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1156,9 +1156,9 @@ "src/view/index.test.mjs", "src/tools/views.test.mjs", "src/app/embed.test.mjs", - "src/render/cesium/panelRendering.js", + "src/app/panelRendering.js", "src/render/cesium/application.js", - "src/render/cesium/panelRendering.test.mjs", + "src/app/panelRendering.test.mjs", "src/tools/globePanel.test.mjs", "src/costEndpointThrottle.test.mjs", "src/sources/gbfsStations.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 4f59afd30..6e6e93068 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -60,7 +60,10 @@ "src/render/color.js", "src/geo/sphere.js", "src/geo/rhumb.js", - "src/geo/frustum.js" + "src/geo/frustum.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -1101,7 +1104,10 @@ "src/cockpitLook.js", "src/cockpitOrbital.js", "src/cockpitOrbitalFocus.js", - "src/geoDistance.js" + "src/geoDistance.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -1433,8 +1439,6 @@ "src/render/input/router.js", "src/sky/icrf.js", "src/data/firmsIntensity.js", - "src/ui/layerPanel/RowSwitch.vue", - "src/ui/layerPanel/RowSlider.vue", "src/ui/kit/UiSegmented.vue", "src/ui/wildlifeSightingCard.js", "src/layers/wildlifeSightings/records.js", @@ -1470,7 +1474,10 @@ "src/render/cesium/viewers.js", "src/render/applicationHooks.js", "src/maps/globeEngine.js", - "src/maps/engine.js" + "src/maps/engine.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium", "vue", "pinia", "vue-i18n"] }, @@ -1651,7 +1658,10 @@ "src/render/cesium/input.js", "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", - "src/render/input/router.js" + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium", "vue", "pinia", "vue-i18n"] }, @@ -1794,7 +1804,10 @@ "src/data/firmsIntensity.js", "src/time/worldClock.js", "src/data/satelliteClassMask.js", - "src/data/planespottersPhoto.js" + "src/data/planespottersPhoto.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -1914,7 +1927,10 @@ "src/data/firmsIntensity.js", "src/ui/unitLabels.js", "src/time/worldClock.js", - "src/data/satelliteClassMask.js" + "src/data/satelliteClassMask.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -2047,7 +2063,10 @@ "src/render/cesium/cameraControls.js", "src/render/input/router.js", "src/layers/vessels/cockpitSubject.js", - "src/geoDistance.js" + "src/geoDistance.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -2125,7 +2144,10 @@ "src/render/cesium/starrySky.js", "src/render/applicationHooks.js", "src/maps/globeEngine.js", - "src/render/cesium/viewers.js" + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -2262,7 +2284,10 @@ "src/data/firmsIntensity.js", "src/data/firmsHeatRaster.js", "src/layers/firms/heatImagery.js", - "src/render/color.js" + "src/render/color.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -2360,7 +2385,10 @@ "src/data/ucsSatellites.js", "src/data/imagingSensors.js", "src/data/bundledJson.js", - "src/data/retryableLoad.js" + "src/data/retryableLoad.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium", "satellite.js"] }, @@ -2454,7 +2482,10 @@ "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", - "src/time/worldClock.js" + "src/time/worldClock.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -2556,7 +2587,10 @@ "src/render/cesium/input.js", "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", - "src/render/input/router.js" + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium", "@mapbox/vector-tile", "pbf"] }, @@ -2632,7 +2666,8 @@ "src/data/feedState.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", - "src/ui/layerNames.js" + "src/ui/layerNames.js", + "src/render/cesium/zoomOutGuard.js" ], "external": ["cesium"] }, @@ -2742,7 +2777,10 @@ "src/render/input/router.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/input.js", - "src/render/cesium/viewers.js" + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium", "pbf", "@mapbox/vector-tile"] }, @@ -2798,7 +2836,8 @@ "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js", - "src/queries/heights.js" + "src/queries/heights.js", + "src/render/cesium/zoomOutGuard.js" ], "external": ["cesium"] }, @@ -2914,7 +2953,10 @@ "src/render/cesium/input.js", "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", - "src/render/input/router.js" + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["hls.js", "cesium"] }, @@ -2965,7 +3007,6 @@ "src/render/cesium/common.js", "src/layers/streetLevel/marker.js", "src/layers/streetLevel/view.js", - "src/geo/horizon.js", "src/layers/streetLevel/uiState.js", "src/layers/streetLevel/pickRouter.js", "src/data/idSwitches.js", @@ -3033,7 +3074,10 @@ "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", "src/queries/heights.js", - "src/time/worldClock.js" + "src/time/worldClock.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium", "pbf", "@mapbox/vector-tile", "mapillary-js"] }, @@ -3110,7 +3154,10 @@ "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", - "src/queries/heights.js" + "src/queries/heights.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium", "@mapbox/vector-tile", "pbf"] }, @@ -3213,7 +3260,10 @@ "src/render/input/router.js", "src/render/cesium/internals.js", "src/data/firmsIntensity.js", - "src/data/satelliteClassMask.js" + "src/data/satelliteClassMask.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -3280,7 +3330,10 @@ "src/render/cesium/input.js", "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", - "src/render/input/router.js" + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -3404,7 +3457,10 @@ "src/maps/engine.js", "src/render/applicationHooks.js", "src/maps/globeEngine.js", - "src/render/cesium/viewers.js" + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -4089,7 +4145,6 @@ "src/styles/thermal.js", "src/ui/applicationShell.js", "src/ui/mobileShell.js", - "src/exclusiveSurfaces.js", "src/ui/localePicker.js", "src/ui/cyberSonarControls.js", "src/ui/locationNavigation.js", @@ -4563,7 +4618,6 @@ "src/ui/stores/cockpit.js", "src/ui/stores/locale.js", "src/ui/stores/providerSettings.js", - "src/ui/stores/sceneSharing.js", "src/ui/stores/voice.js", "src/ui/stores/location.js", "src/ui/stores/display.js", @@ -4621,7 +4675,7 @@ "src/maps/attribution.js", "src/render/cesium/mapEngine.js", "src/sky/icrf.js", - "src/render/cesium/panelRendering.js", + "src/app/panelRendering.js", "src/render/cesium/application.js", "src/sources/osmFeatures.js", "src/voice/imageryActions.js", @@ -4641,8 +4695,6 @@ "src/data/firmsIntensity.js", "src/data/firmsHeatRaster.js", "src/layers/firms/heatImagery.js", - "src/ui/layerPanel/RowSwitch.vue", - "src/ui/layerPanel/RowSlider.vue", "src/data/rioRouteNames.js", "src/globeInView.js", "src/app/globeInViewRecovery.js", @@ -5475,7 +5527,8 @@ "src/render/applicationHooks.js", "src/maps/globeEngine.js", "src/maps/engine.js", - "src/data/planespottersPhoto.js" + "src/data/planespottersPhoto.js", + "src/render/cesium/zoomOutGuard.js" ], "external": [ "hls.js", @@ -5611,7 +5664,10 @@ "src/render/input/router.js", "src/render/cesium/nativeClick.js", "src/render/cesium/input.js", - "src/render/cesium/viewers.js" + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": [ "cesium", @@ -5646,7 +5702,8 @@ "src/data/inputOwnership.js", "src/data/pickRegistry.js", "src/data/scenePick.js", - "src/render/rendererOf.js" + "src/render/rendererOf.js", + "src/render/cesium/zoomOutGuard.js" ], "external": ["cesium"] }, @@ -5708,7 +5765,10 @@ "src/render/cesium/follow.js", "src/render/cesium/internals.js", "src/render/cesium/common.js", - "src/data/entityRecords.js" + "src/data/entityRecords.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, @@ -5968,7 +6028,8 @@ "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", - "src/render/input/router.js" + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js" ], "external": ["cesium"] }, @@ -6394,7 +6455,10 @@ "src/data/rioRouteNames.js", "src/overlays/worldOverlayChrome.js", "src/time/worldClock.js", - "src/render/cesium/viewers.js" + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium", "egm96-universal", "pbf"] }, @@ -6503,7 +6567,10 @@ "src/render/cesium/nativeClick.js", "src/data/rioRouteNames.js", "src/time/worldClock.js", - "src/render/cesium/viewers.js" + "src/render/cesium/viewers.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium", "pbf"] }, @@ -6586,7 +6653,8 @@ "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", - "src/render/input/router.js" + "src/render/input/router.js", + "src/render/cesium/zoomOutGuard.js" ], "external": ["cesium"] }, @@ -6745,7 +6813,10 @@ "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js", - "src/queries/heights.js" + "src/queries/heights.js", + "src/render/cesium/zoomOutGuard.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/data/detectionOcclusion.js" ], "external": ["cesium"] }, diff --git a/src/app/controls.js b/src/app/controls.js index 8365d6144..36d25651a 100644 --- a/src/app/controls.js +++ b/src/app/controls.js @@ -11,13 +11,7 @@ import { t } from '../i18n/index.js'; * picker, for a page that does not initialize the app's locale. */ export function createApplicationControls({ - scene: { - viewer, - mapStackController, - operations, - viewerDrawsEntity, - installZoomOutGuard, - }, + scene: { viewer, mapStackController, operations, viewerDrawsEntity }, loaderStatus, Controls = StyleManager, services, @@ -49,15 +43,6 @@ export function createApplicationControls({ defer(() => styleManager.orbitController.stop()); defer(() => styleManager.hud.destroy()); defer(() => styleManager.dispose()); - // The scene's renderer bounds the user's outward zooms (a scene whose - // renderer has no such guard gives none). - if (installZoomOutGuard) - defer( - installZoomOutGuard({ - 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. diff --git a/src/app/controls.test.mjs b/src/app/controls.test.mjs index 06184061d..638e0765a 100644 --- a/src/app/controls.test.mjs +++ b/src/app/controls.test.mjs @@ -11,55 +11,7 @@ before(() => { }); after(() => uninstallDom()); -test("application controls install the scene's zoom-out guard and remove it on teardown", () => { - const handoffs = new Set(); - class Controls { - hasShareState = true; - orbitController = { stop() {} }; - hud = { destroy() {} }; - dispose() {} - subscribeCameraHandoff(listener) { - handoffs.add(listener); - return () => handoffs.delete(listener); - } - } - const cleanups = []; - // The guard the scene's renderer gives: installed once, with the controls' - // camera handoff, and disposed with the application. - const guard = { installs: 0, disposals: 0 }; - createApplicationControls({ - scene: { - viewer: {}, - mapStackController: {}, - operations: { - surface: { controlServices: {} }, - searchAndFlyTo() {}, - requests: { regional: {}, weather: {} }, - }, - installZoomOutGuard({ subscribeCameraHandoff }) { - guard.installs += 1; - const unsubscribe = subscribeCameraHandoff(() => {}); - return () => { - guard.disposals += 1; - unsubscribe(); - }; - }, - }, - loaderStatus: {}, - Controls, - catalog: { get: (id) => ({ id }) }, - defer: (cleanup) => cleanups.push(cleanup), - }); - - assert.equal(guard.installs, 1); - assert.equal(handoffs.size, 1); - - for (const cleanup of cleanups.reverse()) cleanup(); - assert.equal(guard.disposals, 1); - assert.equal(handoffs.size, 0); -}); - -test('a scene without a zoom-out guard starts its controls without one', () => { +test('the application controls start and stop', () => { class Controls { hasShareState = true; orbitController = { stop() {} }; diff --git a/src/app/data.js b/src/app/data.js index 45ce29b6d..7e20f1315 100644 --- a/src/app/data.js +++ b/src/app/data.js @@ -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 render/cesium/panelRendering.js). + // keep polling (see keepPanelRendering in app/panelRendering.js). visibilityTarget: panelAwareVisibility(document), getSourceAvailability: catalog?.getSourceAvailability, }); diff --git a/src/render/cesium/panelRendering.js b/src/app/panelRendering.js similarity index 59% rename from src/render/cesium/panelRendering.js rename to src/app/panelRendering.js index 2d16b3848..66b3305ea 100644 --- a/src/render/cesium/panelRendering.js +++ b/src/app/panelRendering.js @@ -1,7 +1,7 @@ /** - * @module render/cesium/panelRendering - * @description Keeping the Cesium viewer drawing in an inline panel whose - * host stops animation frames (`src/app/embed.js`, embed mode). The + * @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`). */ @@ -22,13 +22,17 @@ function describeError(error) { } /** - * Keep the globe drawing in an inline panel. Some hosts report a panel on + * 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 - * Cesium's render loop; while frames stop arriving, draw from a timer. - * Returns a function that stops it. + * the renderer's own loop; while frames stop arriving, draw from a timer + * (`resize`, then `frame.renderNow()`). 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( - viewer, + renderer, { windowRef = globalThis.window, now = () => performance.now() } = {}, ) { let lastFrame = now(); @@ -38,32 +42,24 @@ export function keepPanelRendering( frameRequest = windowRef.requestAnimationFrame(onFrame); }; frameRequest = windowRef.requestAnimationFrame(onFrame); - // Cesium stops drawing after a render error, and so does the timer. - // Report the error in full: workers report plain objects, which Cesium - // prints as [object Object]. let failed = false; - const removeErrorListener = viewer.scene?.renderError?.addEventListener( - (_scene, error) => { + const timer = windowRef.setInterval(() => { + if (failed || now() - lastFrame < MISSED_FRAMES_MS) return; + try { + renderer.resize(); + renderer.frame.renderNow(); + } catch (error) { + // 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), ); - }, - ); - const timer = windowRef.setInterval(() => { - if ( - failed || - now() - lastFrame < MISSED_FRAMES_MS || - viewer.isDestroyed?.() - ) - return; - viewer.resize(); - viewer.render(); + } }, PANEL_FRAME_MS); return () => { windowRef.clearInterval(timer); windowRef.cancelAnimationFrame(frameRequest); - removeErrorListener?.(); }; } diff --git a/src/app/panelRendering.test.mjs b/src/app/panelRendering.test.mjs new file mode 100644 index 000000000..bab5b5a1e --- /dev/null +++ b/src/app/panelRendering.test.mjs @@ -0,0 +1,73 @@ +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: () => drawn.push('render') }, + }; + 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(); + assert.deepEqual(drawn, ['resize', 'render']); + 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; + } +}); diff --git a/src/app/scene.js b/src/app/scene.js index b5be51a81..aa84960bd 100644 --- a/src/app/scene.js +++ b/src/app/scene.js @@ -15,7 +15,11 @@ import { describeError } from './errors.js'; import { worldClock, worldTimeFor } from '../time/worldClock.js'; import { followWorldTime } from '../time/viewerClock.js'; import { t } from '../i18n/index.js'; -import { applicationHooksOf } from '../render/applicationHooks.js'; +import { + applicationHooksOf, + provideApplicationHooks, +} from '../render/applicationHooks.js'; +import { keepPanelRendering } from './panelRendering.js'; import { createSceneHost } from '../render/rendererOf.js'; let defaultLoad = null; @@ -95,7 +99,6 @@ export async function createApplicationScene({ // bound to the renderer. const scene = createSceneHost(renderer, { container }); const viewer = scene.host; - const hooks = applicationHooksOf(renderer); // 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. @@ -112,6 +115,14 @@ export async function createApplicationScene({ } } }); + // 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()); @@ -126,6 +137,13 @@ export async function createApplicationScene({ 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; + }); + } defer( followWorldTime(viewer, worldTimeFor('sky'), { subscribe: worldClock.subscribe, @@ -214,14 +232,15 @@ export async function createApplicationScene({ 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, keeps an inline panel - // drawing, says whether an entity is the renderer's own, installs the - // zoom-out guard, and what QA scripts read (render/applicationHooks.js). + // 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, - keepPanelRendering: hooks.keepPanelRendering, viewerDrawsEntity: hooks.viewerDrawsEntity, - installZoomOutGuard: hooks.installZoomOutGuard, qaHandles: hooks.qaHandles, }; } diff --git a/src/app/scene.test.mjs b/src/app/scene.test.mjs index b32377bf5..b19dac0f8 100644 --- a/src/app/scene.test.mjs +++ b/src/app/scene.test.mjs @@ -46,14 +46,15 @@ test('the scene runs on a renderer with only the required members', async (t) => 'isDestroyed', ]); // No hooks: each is left out, not faked. - for (const name of [ - 'trimStaleCommands', - 'keepPanelRendering', - 'viewerDrawsEntity', - 'installZoomOutGuard', - 'qaHandles', - ]) + 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'); @@ -91,6 +92,39 @@ test('the scene runs on a renderer with only the required members', async (t) => 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'], diff --git a/src/app/tools.js b/src/app/tools.js index 6edf8382c..80b306d36 100644 --- a/src/app/tools.js +++ b/src/app/tools.js @@ -188,7 +188,7 @@ 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 render/cesium/panelRendering.js). + // keeps drawing itself (see keepPanelRendering in app/panelRendering.js). const hidden = document.hidden && !isEmbeddedInline(); renderer.frame.suspend(hidden); cockpitCloudEffects?.setSuspended?.(hidden); diff --git a/src/data/detection.js b/src/data/detection.js index c471beca6..c976455e6 100644 --- a/src/data/detection.js +++ b/src/data/detection.js @@ -51,7 +51,6 @@ import { import { detectionBracketOpacity } from './detectionPresentation.js'; import { SurfaceOcclusion } from './detectionOcclusion.js'; import { rendererOf } from '../render/rendererOf.js'; -import { applicationHooksOf } from '../render/applicationHooks.js'; import { createCyberSonarSampler, cyberSonarFrameDelay, @@ -287,7 +286,7 @@ const NO_OCCLUSION_PROBE = Object.freeze({ * Hides the bracket and callout of a depth-tested contact (a street vehicle) * that the scene drew something in front of. `_occlusionProbe` asks the GPU * about each such contact without waiting for the answer (the renderer's - * `createOcclusionProbe` application hook, `render/applicationHooks.js`); + * `query.occlusionTest()`, where it has the `occlusionTest` capability); * `_surfaceOcclusion` remembers the answers and decides, every frame, who is * drawn. */ @@ -297,8 +296,10 @@ const _surfaceOcclusion = new SurfaceOcclusion(_occlusionProbe); /** Use the occlusion probe of `viewer`'s renderer, or none. */ function _useOcclusionProbe(viewer) { _occlusionProbe.destroy(); + const renderer = rendererOf(viewer); _occlusionProbe = - applicationHooksOf(rendererOf(viewer)).createOcclusionProbe?.() ?? + (renderer?.capabilities?.has('occlusionTest') && + renderer.query.occlusionTest?.()) || NO_OCCLUSION_PROBE; _surfaceOcclusion.clear(); _surfaceOcclusion.probe = _occlusionProbe; diff --git a/src/data/detectionHost.test.mjs b/src/data/detectionHost.test.mjs index 24ec3f448..9a8df9c97 100644 --- a/src/data/detectionHost.test.mjs +++ b/src/data/detectionHost.test.mjs @@ -43,8 +43,7 @@ import { depthImage, viewDistanceToDepth, } from '../render/cesium/fixtures/fakeDepthScene.mjs'; -import { createViewerOcclusionProbe } from '../render/cesium/sceneOcclusionProbe.js'; -import { provideApplicationHooks } from '../render/applicationHooks.js'; +import { createSceneOcclusionTest } from '../render/cesium/sceneOcclusionProbe.js'; import { rendererOf } from '../render/rendererOf.js'; test('detection diagnostics count rendered fading rows instead of absent selected identities', () => { @@ -1418,10 +1417,11 @@ function installDepthScene(env, surfaceDistance, { webgl2 = true } = {}) { const image = paint(); const scene = createFakeDepthScene({ gl, ranges: [{ near, far, image }] }); Object.assign(env.viewer.scene, scene, { camera }); - // The renderer's occlusion probe, as the Cesium renderer hands it over. - provideApplicationHooks(rendererOf(env.viewer), { - createOcclusionProbe: () => createViewerOcclusionProbe(env.viewer), - }); + // The renderer's occlusion test, as the Cesium query port gives it. + const renderer = rendererOf(env.viewer); + renderer.capabilities = new Set(['occlusionTest']); + renderer.query.occlusionTest = () => + createSceneOcclusionTest(env.viewer.scene); return { gl, /** Draw the next frame's depth. */ diff --git a/src/hud.js b/src/hud.js index 79b34703a..35b83aef1 100644 --- a/src/hud.js +++ b/src/hud.js @@ -446,7 +446,7 @@ export class IntelHUD { // Camera-derived data — 4 updates/second (250ms). Skipped in a hidden // page, except an inline panel, whose host may report it hidden while it - // is on screen (see keepPanelRendering in render/cesium/panelRendering.js). + // is on screen (see keepPanelRendering in app/panelRendering.js). this._updateInterval = setInterval(() => { if (!this._visible || (document.hidden && !isEmbeddedInline())) return; this._updateCameraData(); diff --git a/src/render/applicationHooks.js b/src/render/applicationHooks.js index 148267d78..44cbf38e9 100644 --- a/src/render/applicationHooks.js +++ b/src/render/applicationHooks.js @@ -11,21 +11,20 @@ * (`src/maps/globeEngine.js`). * - `trimStaleCommands()`: drops the draw commands a renderer keeps for a * while after it stops drawing them; run after a layer turns off. - * - `keepPanelRendering(options)`: keeps the globe drawing in an inline panel - * whose host stops animation frames (embed mode); returns its disposer. * - `viewerDrawsEntity(entity)`: whether an entity is one the renderer draws * itself (Cockpit asks whether the aircraft it flies still draws). - * - `installZoomOutGuard(options)`: keeps outward user zooms bounded and the - * Earth framed; returns its disposer. - * - `createOcclusionProbe()`: a probe that tests depth-tested contacts - * (street vehicles) against what the frame drew, so the detection overlay - * leaves out those something stands in front of (`SurfaceOcclusion` in - * `src/data/detectionOcclusion.js` says what it answers); without one, - * every such contact is drawn. * - `qaHandles`: values QA scripts read from `window.__godsEyeView`. * - `ownCreditDisplay`: true when the renderer shows its credits in a * display of its own; otherwise the application shows what its credits * port lists (`src/ui/creditsView.js`). + * + * A plugin hands them as its `applicationHooks(renderer)` + * (`ApplicationHooks`, `contract/renderer.d.ts`); the application scene + * records them here as it creates the renderer. What the renderer should + * do is in the contract instead: keeping the Earth framed on zooming out is + * `camera.controls.keepEarthFramed`, the detection overlay's depth test is + * `query.occlusionTest`, and an inline panel keeps drawing through the frame + * port (`src/app/panelRendering.js`). */ const hooks = new WeakMap(); diff --git a/src/render/cesium/appRenderer.js b/src/render/cesium/appRenderer.js index 48260cf37..3ca4ab39b 100644 --- a/src/render/cesium/appRenderer.js +++ b/src/render/cesium/appRenderer.js @@ -9,16 +9,16 @@ * and it has every member of the contract. The application's base (the * photoreal tiles, the map stack's imagery and terrain) is still loaded * through the Cesium map engine (`mapEngine.js`), which the plugin hands - * the application with the renderer (`../applicationHooks.js`); the globe + * the application with the renderer (its `applicationHooks`); the globe * port drapes its imagery on that base as drawn (see `globe.js`). * `whenSettled` waits for the globe, the scene's 3D tiles and what the draw * sets hold. * * What only this renderer needs at startup is set up here: the free-look * height limit, keyboard access to the credits' expand link (in the page's - * language), and the hooks the application uses where a renderer has - * them (stale command trimming, inline panel rendering, whether an entity - * is the viewer's own, the zoom-out guard, the viewer QA scripts read). + * language). The plugin's `applicationHooks` are what the application + * uses where a renderer has them: the map engine, stale command trimming, + * whether an entity is the viewer's own, and the viewer QA scripts read. * Adapter code reaches the viewer behind a renderer through * `cesiumViewerOf` (`viewers.js`), never through a renderer member, so no * engine type crosses the contract. @@ -26,16 +26,12 @@ import { createApplicationViewer } from './applicationViewer.js'; import { CONTRACT_VERSION } from '../contract/index.js'; import { bindRenderer } from '../rendererOf.js'; -import { provideApplicationHooks } from '../applicationHooks.js'; import { FREE_LOOK_MAX_HEIGHT_METERS } from '../../globeInView.js'; import { createCesiumInput } from './input.js'; import { cesiumCapabilities, createCesiumPorts } from './ports.js'; import { cesiumMapEngine } from './mapEngine.js'; import { installFreeLookHeightLimit } from './freeLookLimit.js'; -import { keepPanelRendering } from './panelRendering.js'; import { trimStaleSceneCommands } from './sceneCommandRelease.js'; -import { installZoomOutGuard } from './zoomOutGuard.js'; -import { createViewerOcclusionProbe } from './sceneOcclusionProbe.js'; import { configureCreditKeyboardAccess } from './creditKeyboard.js'; import { onLocaleChange } from '../../i18n/index.js'; import { cesiumViewerOf, recordViewer } from './viewers.js'; @@ -168,29 +164,27 @@ export function createCesiumRendererPlugin({ }); recordViewer(renderer, viewer); unbind = bindRenderer(viewer, renderer); - provideApplicationHooks(renderer, { + return renderer; + }, + /** + * @param {TransitionalRenderer} renderer + * @returns {import('../contract/renderer').ApplicationHooks} + */ + applicationHooks(renderer) { + const viewer = cesiumViewerOf(renderer); + return { mapEngine: cesiumMapEngine, // Cesium's credit display (#cesium-credits) shows the credits. ownCreditDisplay: true, // Drops the draw commands the scene keeps after it stops drawing // them; run after a drawn frame (see sceneCommandRelease.js). trimStaleCommands: () => trimStaleSceneCommands(viewer.scene), - // Keeps the globe drawing in an inline panel whose host stops - // animation frames (embed mode, src/app/embed.js). - keepPanelRendering: (options) => keepPanelRendering(viewer, options), // Whether an entity is one of the viewer's own (Cockpit asks whether // the aircraft it flies still draws). viewerDrawsEntity: (entity) => viewer.entities.contains(entity), - // Keeps outward user zooms bounded and the Earth framed; returns its - // disposer (see zoomOutGuard.js). - installZoomOutGuard: (options) => installZoomOutGuard(viewer, options), - // Tests depth-tested contacts (street vehicles) against the frame's - // own depth, for the detection overlay (see sceneOcclusionProbe.js). - createOcclusionProbe: () => createViewerOcclusionProbe(viewer), // QA scripts drive and read the viewer itself. qaHandles: { viewer }, - }); - return renderer; + }; }, }); } diff --git a/src/render/cesium/appRenderer.test.mjs b/src/render/cesium/appRenderer.test.mjs index a1689fca7..f88a25a75 100644 --- a/src/render/cesium/appRenderer.test.mjs +++ b/src/render/cesium/appRenderer.test.mjs @@ -3,7 +3,6 @@ import test from 'node:test'; import * as Cesium from 'cesium'; import { CONTRACT_VERSION, checkRendererShape } from '../contract/index.js'; import { rendererOf } from '../rendererOf.js'; -import { applicationHooksOf } from '../applicationHooks.js'; import { cesiumMapEngine } from './mapEngine.js'; import { ReadonlySet, @@ -142,17 +141,13 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async false, 'free look is limited to low heights from the start', ); - const hooks = applicationHooksOf(renderer); + const hooks = plugin.applicationHooks(renderer); assert.equal(hooks.mapEngine, cesiumMapEngine, 'the map stacks use Cesium'); + assert.equal(hooks.ownCreditDisplay, true, 'Cesium shows its own credits'); assert.equal(hooks.qaHandles.viewer, viewer, 'QA scripts read the viewer'); assert.equal(hooks.viewerDrawsEntity({ own: true }), true); assert.equal(hooks.viewerDrawsEntity({}), false); - for (const name of [ - 'trimStaleCommands', - 'keepPanelRendering', - 'installZoomOutGuard', - ]) - assert.equal(typeof hooks[name], 'function', name); + assert.equal(typeof hooks.trimStaleCommands, 'function'); assert.ok(viewer.listeners.size > 0, 'the ports follow the frame phases'); assert.equal(typeof renderer.draw.icons, 'function'); diff --git a/src/render/cesium/applicationViewer.test.mjs b/src/render/cesium/applicationViewer.test.mjs index 3b5cf60a2..2ebbbe54f 100644 --- a/src/render/cesium/applicationViewer.test.mjs +++ b/src/render/cesium/applicationViewer.test.mjs @@ -21,7 +21,10 @@ test("zooming out stops with the globe 30% of the screen's height across", () => 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'); + 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 } = {}) { diff --git a/src/render/cesium/camera.js b/src/render/cesium/camera.js index efb25ed92..96528f28c 100644 --- a/src/render/cesium/camera.js +++ b/src/render/cesium/camera.js @@ -117,12 +117,16 @@ export function createCesiumCamera({ }) : null; - const controlsPart = createCesiumControls({ scene, widget }); - // Camera commands: hooks run before each one, so an owner can yield. const commandHooks = listenerList(report); const command = (kind) => commandHooks.fire({ kind }); + const controlsPart = createCesiumControls({ + scene, + widget, + onCommand: (cb) => commandHooks.on(cb), + }); + // The flight this port started, while it is in progress. Cesium cancels // a flight in progress when another starts, including one started on // its camera directly, and runs the callbacks inside the call or frame diff --git a/src/render/cesium/cameraControls.js b/src/render/cesium/cameraControls.js index 7e1c69941..aebee39a5 100644 --- a/src/render/cesium/cameraControls.js +++ b/src/render/cesium/cameraControls.js @@ -26,11 +26,16 @@ * contract has no name for is kept as it is when they are set. While * they hold `ctrlWheel`, trackpad pinches (small pixel-mode Ctrl+wheel * events) are relayed at a usable speed (`ctrlWheelZoom.js`). + * - `keepEarthFramed` installs the zoom-out guard (`zoomOutGuard.js`) on + * the widget, which reads the controller's own input; a camera command + * (`onCommand`) ends its easing. Without a widget whose scene has a + * controller, it only reads back. */ import * as Cesium from 'cesium'; import { acquireCameraInput } from './cameraInput.js'; import { installTrackpadPinchRelay } from './ctrlWheelZoom.js'; import { followZoomBase, setFollowZoomBase } from './follow.js'; +import { installZoomOutGuard } from './zoomOutGuard.js'; const HALF_PI = Math.PI / 2; const { WHEEL, PINCH, RIGHT_DRAG } = Cesium.CameraEventType; @@ -88,9 +93,12 @@ export const controllerDefaults = () => ({ /** * @param {{scene: {screenSpaceCameraController?: object}, widget?: object, - * pinchRelay?: typeof installTrackpadPinchRelay}} options `widget`, the - * Viewer or CesiumWidget, takes the trackpad pinch relay; without one - * `ctrlWheel` binds Ctrl+wheel alone. + * pinchRelay?: typeof installTrackpadPinchRelay, + * onCommand?: (cb: () => void) => () => void, + * zoomOutGuard?: typeof installZoomOutGuard}} options `widget`, the + * Viewer or CesiumWidget, takes the trackpad pinch relay and the zoom-out + * guard; without one `ctrlWheel` binds Ctrl+wheel alone. `onCommand` + * subscribes to the camera port's commands. * @returns {{controls: import('../contract/camera').CameraControls, * dispose: () => void}} */ @@ -98,6 +106,8 @@ export function createCesiumControls({ scene, widget, pinchRelay = installTrackpadPinchRelay, + onCommand, + zoomOutGuard = installZoomOutGuard, }) { const ownController = scene.screenSpaceCameraController; const controller = ownController ?? controllerDefaults(); @@ -125,6 +135,13 @@ export function createCesiumControls({ // The pitch range as last set, read back while the controller still has // the tilt limit it was given. let pitchSet = null; + // `keepEarthFramed`, and the guard's disposer while it is installed. + let framed = false; + let releaseGuard = null; + const guardable = () => + Boolean( + ownController && widget?.camera && widget?.canvas && scene.preRender, + ); const controls = { // Read without taking over `enableInputs`: once any user holds input, @@ -249,6 +266,27 @@ export function createCesiumControls({ ]; relayPinches(value.includes('ctrlWheel')); }, + get keepEarthFramed() { + return framed; + }, + set keepEarthFramed(value) { + framed = Boolean(value); + if (framed && !releaseGuard && !disposed && guardable()) + releaseGuard = zoomOutGuard(widget, { + requestRender: () => scene.requestRender?.(), + // A command that places the eye ends the guard's easing; the + // step views a held key sends every frame do not (the guard + // lets go of a pose it did not make on its own). + subscribeCameraHandoff: (listener) => + onCommand?.((command) => { + if (command?.kind !== 'setView') listener(command); + }), + }); + else if (!framed && releaseGuard) { + releaseGuard(); + releaseGuard = null; + } + }, }; // A controller that already binds Ctrl+wheel relays pinches from the start. relayPinches(controls.zoomInputs.includes('ctrlWheel')); @@ -257,6 +295,8 @@ export function createCesiumControls({ controls, dispose() { relayPinches(false); + releaseGuard?.(); + releaseGuard = null; disposed = true; cameraInput?.release(); cameraInput = null; diff --git a/src/render/cesium/cameraControls.test.mjs b/src/render/cesium/cameraControls.test.mjs index e211e5058..bda965298 100644 --- a/src/render/cesium/cameraControls.test.mjs +++ b/src/render/cesium/cameraControls.test.mjs @@ -225,3 +225,46 @@ test('a scene without a controller still has settings', () => { assert.equal(controls.zoomFactor, 9); assert.deepEqual(controls.zoomInputs, ['rightDrag', 'wheel', 'pinch']); }); + +test('keepEarthFramed installs the zoom-out guard, which placing commands cancel', () => { + const scene = { ...sceneWithController(), preRender: {}, requestRender() {} }; + const widget = { scene, camera: {}, canvas: {} }; + const commands = new Set(); + const installed = []; + const { controls, dispose } = createCesiumControls({ + scene, + widget, + onCommand: (cb) => (commands.add(cb), () => commands.delete(cb)), + zoomOutGuard(viewer, { subscribeCameraHandoff }) { + const guard = { viewer, cancels: 0, released: false }; + const off = subscribeCameraHandoff(() => (guard.cancels += 1)); + installed.push(guard); + return () => { + guard.released = true; + off(); + }; + }, + }); + assert.equal(controls.keepEarthFramed, false); + controls.keepEarthFramed = true; + controls.keepEarthFramed = true; + assert.equal(installed.length, 1, 'installed once'); + assert.equal(installed[0].viewer, widget); + // A held key's step views do not cancel it; a flight does. + for (const cb of commands) cb({ kind: 'setView' }); + assert.equal(installed[0].cancels, 0); + for (const cb of commands) cb({ kind: 'flyTo' }); + assert.equal(installed[0].cancels, 1); + controls.keepEarthFramed = false; + assert.equal(installed[0].released, true); + assert.equal(commands.size, 0); + controls.keepEarthFramed = true; + dispose(); + assert.equal(installed[1].released, true, 'released on dispose'); +}); + +test('keepEarthFramed only reads back without a controller to guard', () => { + const { controls } = createCesiumControls({ scene: {} }); + controls.keepEarthFramed = true; + assert.equal(controls.keepEarthFramed, true); +}); diff --git a/src/render/cesium/creditKeyboard.test.mjs b/src/render/cesium/creditKeyboard.test.mjs index 01d27f6e5..ebf5c51b0 100644 --- a/src/render/cesium/creditKeyboard.test.mjs +++ b/src/render/cesium/creditKeyboard.test.mjs @@ -10,8 +10,12 @@ function fakeElement() { dataset: {}, focused: false, id: '', - setAttribute(name, value) { attributes.set(name, String(value)); }, - getAttribute(name) { return attributes.get(name) ?? null; }, + setAttribute(name, value) { + attributes.set(name, String(value)); + }, + getAttribute(name) { + return attributes.get(name) ?? null; + }, addEventListener(type, listener) { if (!listeners.has(type)) listeners.set(type, []); listeners.get(type).push(listener); @@ -22,8 +26,12 @@ function fakeElement() { target: this, defaultPrevented: false, propagationStopped: false, - preventDefault() { this.defaultPrevented = true; }, - stopPropagation() { this.propagationStopped = true; }, + preventDefault() { + this.defaultPrevented = true; + }, + stopPropagation() { + this.propagationStopped = true; + }, ...event, }; for (const listener of listeners.get(type) || []) listener(dispatched); @@ -33,8 +41,12 @@ function fakeElement() { this.onclick?.(); this.dispatch('click'); }, - focus() { this.focused = true; }, - listenerCount(type) { return listeners.get(type)?.length || 0; }, + focus() { + this.focused = true; + }, + listenerCount(type) { + return listeners.get(type)?.length || 0; + }, }; } @@ -48,7 +60,8 @@ function fixture() { lightbox.parentElement = overlay; const root = { querySelector(selector) { - if (selector === '#cesium-credits .cesium-credit-expand-link') return expand; + if (selector === '#cesium-credits .cesium-credit-expand-link') + return expand; if (selector === '.cesium-credit-lightbox') return lightbox; return null; }, @@ -72,8 +85,12 @@ test('Enter opens and closes attribution on initial keydown', () => { const f = fixture(); let opened = 0; let closed = 0; - f.expand.onclick = () => { opened++; }; - f.close.onclick = () => { closed++; }; + f.expand.onclick = () => { + opened++; + }; + f.close.onclick = () => { + closed++; + }; configureCreditKeyboardAccess(f.root); const openEvent = f.expand.dispatch('keydown', { key: 'Enter' }); assert.equal(openEvent.defaultPrevented, true); @@ -91,8 +108,12 @@ test('Space opens and closes attribution only on key release', () => { const f = fixture(); let opened = 0; let closed = 0; - f.expand.onclick = () => { opened++; }; - f.close.onclick = () => { closed++; }; + f.expand.onclick = () => { + opened++; + }; + f.close.onclick = () => { + closed++; + }; configureCreditKeyboardAccess(f.root); const openDown = f.expand.dispatch('keydown', { key: ' ' }); @@ -118,7 +139,9 @@ test('Space opens and closes attribution only on key release', () => { test('held activation keys do not repeat open or close actions', () => { const f = fixture(); let opened = 0; - f.expand.onclick = () => { opened++; }; + f.expand.onclick = () => { + opened++; + }; configureCreditKeyboardAccess(f.root); f.expand.dispatch('keydown', { key: ' ' }); @@ -132,7 +155,9 @@ test('held activation keys do not repeat open or close actions', () => { const g = fixture(); let enterOpened = 0; - g.expand.onclick = () => { enterOpened++; }; + g.expand.onclick = () => { + enterOpened++; + }; configureCreditKeyboardAccess(g.root); g.expand.dispatch('keydown', { key: 'Enter' }); g.expand.dispatch('keydown', { key: 'Enter', repeat: true }); @@ -142,7 +167,9 @@ test('held activation keys do not repeat open or close actions', () => { test('losing focus during a Space hold cancels release activation', () => { const f = fixture(); let opened = 0; - f.expand.onclick = () => { opened++; }; + f.expand.onclick = () => { + opened++; + }; configureCreditKeyboardAccess(f.root); f.expand.dispatch('keydown', { key: ' ' }); @@ -156,10 +183,15 @@ test('losing focus during a Space hold cancels release activation', () => { test('Escape and backdrop dismissal close attribution and restore its disclosure', () => { const f = fixture(); let closed = 0; - f.close.onclick = () => { closed++; }; + f.close.onclick = () => { + closed++; + }; configureCreditKeyboardAccess(f.root); f.expand.click(); - const escape = f.lightbox.dispatch('keydown', { key: 'Escape', target: f.close }); + const escape = f.lightbox.dispatch('keydown', { + key: 'Escape', + target: f.close, + }); assert.equal(escape.defaultPrevented, true); assert.equal(escape.propagationStopped, true); assert.equal(closed, 1); @@ -185,7 +217,10 @@ test('credit keyboard setup is idempotent and safely declines incomplete markup' assert.equal(f.close.listenerCount('blur'), 1); assert.equal(f.lightbox.listenerCount('keydown'), 1); assert.equal(f.overlay.listenerCount('click'), 1); - assert.equal(configureCreditKeyboardAccess({ querySelector: () => null }), false); + assert.equal( + configureCreditKeyboardAccess({ querySelector: () => null }), + false, + ); }); function textFixture() { diff --git a/src/render/cesium/frame.js b/src/render/cesium/frame.js index 159bc1357..91340b1be 100644 --- a/src/render/cesium/frame.js +++ b/src/render/cesium/frame.js @@ -102,6 +102,26 @@ export function willDraw(scene, time) { ); } +/** + * The contract's `renderNow` on `scene`: draw a frame at `time` even when + * nothing asked for one, and throw the error Cesium caught and raised on + * `renderError` when the frame failed. + * @param {object} scene + * @param {object} [time] A Cesium JulianDate. + */ +export function renderNow(scene, time) { + let failure = null; + const off = scene.renderError?.addEventListener((_scene, error) => { + failure ??= { error }; + }); + try { + scene.forceRender(time); + } finally { + off?.(); + } + if (failure) throw failure.error; +} + /** * @param {object} viewer A Cesium `Viewer` or `CesiumWidget`. * @returns {{port: import('../contract/frame').FramePort, @@ -239,7 +259,7 @@ export function createSceneFrame(viewer) { viewer.useDefaultRenderLoop = suspended ? false : ownLoop; if (!suspended && !gone()) scene.requestRender(); }, - renderNow: () => scene.forceRender(viewer.clock?.currentTime), + renderNow: () => renderNow(scene, viewer.clock?.currentTime), renderOnce({ timeoutMs } = {}) { if (gone()) return Promise.resolve(); return new Promise((resolve, reject) => { diff --git a/src/render/cesium/frame.test.mjs b/src/render/cesium/frame.test.mjs index a00837e8b..f191512ca 100644 --- a/src/render/cesium/frame.test.mjs +++ b/src/render/cesium/frame.test.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import test from 'node:test'; import { bindRenderer, findFrame, frameOf } from '../rendererOf.js'; -import './frame.js'; +import { renderNow } from './frame.js'; /** A viewer whose scene raises its phases when `tick` is called. */ function fakeViewer() { @@ -189,3 +189,21 @@ test('a built frame port counts holds per reason, times out a wait, and settles await waiting; unbind(); }); + +test('renderNow throws the error Cesium raises on renderError', () => { + const listeners = new Set(); + const failure = new Error('worker failed'); + let fail = false; + const scene = { + renderError: { + addEventListener: (cb) => (listeners.add(cb), () => listeners.delete(cb)), + }, + forceRender() { + if (fail) for (const cb of listeners) cb(scene, failure); + }, + }; + renderNow(scene); + fail = true; + assert.throws(() => renderNow(scene), failure); + assert.equal(listeners.size, 0, 'it stops listening either way'); +}); diff --git a/src/render/cesium/panelRendering.test.mjs b/src/render/cesium/panelRendering.test.mjs deleted file mode 100644 index 0b3b7a34f..000000000 --- a/src/render/cesium/panelRendering.test.mjs +++ /dev/null @@ -1,70 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { keepPanelRendering } from './panelRendering.js'; - -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 reports a render error in full and stops drawing', () => { - let listener = null; - let tick = null; - const windowRef = { - requestAnimationFrame: () => 1, - cancelAnimationFrame() {}, - setInterval: (fn) => ((tick = fn), 1), - clearInterval() {}, - }; - const drawn = []; - const viewer = { - resize() {}, - render: () => drawn.push('render'), - scene: { - renderError: { - addEventListener: (fn) => ((listener = fn), () => (listener = null)), - }, - }, - }; - const logged = []; - const original = console.error; - console.error = (...args) => logged.push(args.join(' ')); - try { - let clock = 0; - const stop = keepPanelRendering(viewer, { windowRef, now: () => clock }); - listener(viewer.scene, { name: 'RuntimeError', message: 'worker failed' }); - assert.match(logged[0], /render error: .*"message":"worker failed"/); - clock = 1000; - tick(); - assert.deepEqual(drawn, []); - stop(); - assert.equal(listener, null); - } finally { - console.error = original; - } -}); diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 13f687428..fdb777505 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -19,7 +19,7 @@ import { createCesiumCredits } from './credits.js'; import { createCesiumDraw } from './draw.js'; import { GPU_ICON_CAPABILITIES } from './gpuIcons.js'; import { createCesiumEffects } from './effects.js'; -import { willDraw } from './frame.js'; +import { renderNow, willDraw } from './frame.js'; import { createCesiumGlobe } from './globe.js'; import { createCesiumQuery, queryCapabilities } from './query.js'; import { createCesiumQuality } from './quality.js'; @@ -70,6 +70,10 @@ export function cesiumCapabilities(scene, only) { 'fields', 'followFrame', 'cameraChangeThreshold', + // The zoom-out guard reads the scene's own controller and frame events. + ...(scene?.screenSpaceCameraController && scene?.preRender + ? ['keepEarthFramed'] + : []), ...GPU_ICON_CAPABILITIES, 'styles', 'bloom', @@ -294,8 +298,8 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) { widget.useDefaultRenderLoop = !suspended; if (!suspended) scene.requestRender(); }, - // Draws even when nothing asked for a frame. - renderNow: () => scene.forceRender(widget.clock.currentTime), + // Draws even when nothing asked for a frame; throws when it fails. + renderNow: () => renderNow(scene, widget.clock.currentTime), renderOnce: (options) => nextPostRender(options), setTargetFps(fps) { targetFps = fps > 0 ? fps : 0; diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index 96b0f2109..6feaf38f1 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -41,6 +41,7 @@ test('capabilities follow what the scene supports', () => { ...draw, ...effects, 'pickPosition', + 'occlusionTest', ]); assert.deepEqual( cesiumCapabilities({ @@ -53,6 +54,7 @@ test('capabilities follow what the scene supports', () => { ...effects, 'globeVisibility', 'pickPosition', + 'occlusionTest', 'sampleHeight', 'finestHeights', 'rayCast', @@ -67,6 +69,14 @@ test('a caller can ask for fewer capabilities, never more', () => { 'rayCast', ]); assert.deepEqual(cesiumCapabilities({}, new Set(['sampleHeight'])), []); + // The zoom-out guard needs the scene's own controller and frame events. + assert.ok( + cesiumCapabilities({ + screenSpaceCameraController: {}, + preRender: {}, + }).includes('keepEarthFramed'), + ); + assert.ok(!cesiumCapabilities({ preRender: {} }).includes('keepEarthFramed')); }); test('a listener list keeps the listener rules', () => { diff --git a/src/render/cesium/query.js b/src/render/cesium/query.js index 1e301c208..4005e01d5 100644 --- a/src/render/cesium/query.js +++ b/src/render/cesium/query.js @@ -18,6 +18,7 @@ import { toCartesian } from './common.js'; import { unboundDrawPart } from './draw.js'; import { drawHitOf } from './drawHit.js'; import { rememberPick } from './pickMemo.js'; +import { createSceneOcclusionTest } from './sceneOcclusionProbe.js'; /** The fewest things a bounded drill looks through (`QueryPort.drillPick`). */ const DRILL_DEPTH = 16; @@ -31,7 +32,8 @@ const DRILL_DEPTH = 16; */ export function queryCapabilities(scene) { const found = []; - if (scene.pickPositionSupported) found.push('pickPosition'); + // The occlusion test reads the same depth a depth pick does. + if (scene.pickPositionSupported) found.push('pickPosition', 'occlusionTest'); if (scene.sampleHeightSupported) found.push('sampleHeight', 'finestHeights', 'rayCast'); return found; @@ -460,6 +462,9 @@ export function createCesiumQuery({ : null; }, }; + // Only where the scene keeps the depth it tests against. + if (can('occlusionTest')) + query.occlusionTest = () => createSceneOcclusionTest(scene); return query; } diff --git a/src/render/cesium/sceneOcclusionProbe.js b/src/render/cesium/sceneOcclusionProbe.js index 8171706bb..4eaf22512 100644 --- a/src/render/cesium/sceneOcclusionProbe.js +++ b/src/render/cesium/sceneOcclusionProbe.js @@ -805,13 +805,13 @@ export class SceneOcclusionProbe { } /** - * A probe bound to `viewer`'s scene: what the application's detection - * overlay is handed (the `createOcclusionProbe` application hook). Its - * `beginFrame(now)` reads the scene itself; the rest is the probe's. - * @param {Cesium.Viewer} viewer - * @returns {object} + * The query port's `occlusionTest()` on `scene`: a probe whose + * `beginFrame(now)` reads the scene itself (none once it is destroyed); the + * rest is the probe's. + * @param {object} scene A Cesium scene. + * @returns {import('../contract/query').OcclusionTest} */ -export function createViewerOcclusionProbe(viewer) { +export function createSceneOcclusionTest(scene) { const probe = new SceneOcclusionProbe(); return { get mode() { @@ -827,9 +827,9 @@ export function createViewerOcclusionProbe(viewer) { return probe.lastFrameTests; }, beginFrame(now) { - probe.beginFrame(viewer.isDestroyed?.() ? null : viewer.scene, now); + probe.beginFrame(scene.isDestroyed?.() ? null : scene, now); }, - add: (contact, position) => probe.add(contact, position), + add: (point, position) => probe.add(point, position), endFrame: () => probe.endFrame(), reset: () => probe.reset(), destroy: () => probe.destroy(), diff --git a/src/render/cesium/zoomOutGuard.js b/src/render/cesium/zoomOutGuard.js index e53ee5e9c..b16bf6c95 100644 --- a/src/render/cesium/zoomOutGuard.js +++ b/src/render/cesium/zoomOutGuard.js @@ -1,12 +1,11 @@ /** * @module render/cesium/zoomOutGuard * @description Keeps the user's outward zooms bounded and the Earth framed - * on the Cesium camera controller. It reads that controller's own input, so - * it lives in the adapter; the application installs it through the scene's - * viewer hooks (`application.js`). + * on the Cesium camera controller: the camera port's + * `controls.keepEarthFramed` (`cameraControls.js`). It reads that + * controller's own input, so it lives in the adapter. */ import * as Cesium from 'cesium'; -import { governorRequestRender } from '../../renderGovernor.js'; import { cameraFlightActive } from './internals.js'; /** Whole-Earth input limit; explicit camera destinations can go farther. */ @@ -87,7 +86,7 @@ function readInput(aggregator, bindings) { export function installZoomOutGuard( viewer, { - requestRender = governorRequestRender, + requestRender = () => viewer?.scene?.requestRender?.(), subscribeCameraHandoff, createAggregator = (canvas) => new Cesium.CameraEventAggregator(canvas), } = {}, diff --git a/src/render/conformance/checks/camera.js b/src/render/conformance/checks/camera.js index a6819b528..9ad7a51f5 100644 --- a/src/render/conformance/checks/camera.js +++ b/src/render/conformance/checks/camera.js @@ -335,6 +335,13 @@ export function cameraChecks() { ['ctrlWheel', 'wheel'], 'zoomInputs are settable', ); + if (r.capabilities.has('keepEarthFramed')) { + equal(c.keepEarthFramed, false, 'keepEarthFramed is off at first'); + c.keepEarthFramed = true; + equal(c.keepEarthFramed, true, 'keepEarthFramed is settable'); + c.keepEarthFramed = false; + equal(c.keepEarthFramed, false, 'keepEarthFramed turns off'); + } r.destroy(); }, }, diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index 67b85a1fc..22c3bcf8d 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -2899,6 +2899,33 @@ export function portChecks() { } }, ), + check( + 'query.occlusionTest', + 'an occlusion test takes points and leaves the unanswered pending', + async (h) => { + const r = await h.create({ viewport: SCRIPT_VIEWPORT }); + try { + const test = r.query.occlusionTest(); + ok( + ['async', 'sync', 'off'].includes(test.mode), + 'mode is async, sync or off', + ); + ok(test.maxPerFrame > 0, 'takes at least one point a frame'); + const point = { pending: false, answered: false, lastHiddenAt: 0 }; + test.beginFrame(0); + const taken = test.add(point, h.toEcef({ ...AUSTIN, height: 10 })); + equal(typeof taken, 'boolean', 'add says whether it took the point'); + if (taken && test.mode === 'async') + ok(point.pending || point.answered, 'a point taken is under test'); + test.endFrame(); + test.reset(); + test.destroy(); + } finally { + r.destroy(); + } + }, + { capability: 'occlusionTest' }, + ), // --- Input ------------------------------------------------------------- check( diff --git a/src/render/contract/camera.d.ts b/src/render/contract/camera.d.ts index 2e3956a6c..e2a1967e8 100644 --- a/src/render/contract/camera.d.ts +++ b/src/render/contract/camera.d.ts @@ -201,6 +201,16 @@ export interface CameraControls { * the page. */ zoomInputs: Array<'wheel' | 'pinch' | 'rightDrag' | 'ctrlWheel'>; + /** + * `keepEarthFramed`: keep the whole Earth in reach and in frame as the + * user zooms out. An outward user zoom goes no farther than about + * 40,000 km, or than the height a camera command left the eye at when + * that is higher (the user then zooms in from there), and from high up + * it turns the view down toward the globe so the whole Earth stays in + * frame. A camera command, a follow and a flight are not held to it, and + * a camera command ends any turn under way. Off by default. + */ + keepEarthFramed?: boolean; } export type CameraEvent = diff --git a/src/render/contract/common.d.ts b/src/render/contract/common.d.ts index 22ddf327d..be18fc2e9 100644 --- a/src/render/contract/common.d.ts +++ b/src/render/contract/common.d.ts @@ -170,6 +170,10 @@ export type Capability = | 'gpuTiming' /** Depth picks against tiles and terrain. */ | 'pickPosition' + /** Points tested against the frame's depth (`query.occlusionTest`). */ + | 'occlusionTest' + /** Outward user zooms that keep the Earth framed (`controls.keepEarthFramed`). */ + | 'keepEarthFramed' /** Height sampling against tiles and terrain. */ | 'sampleHeight' /** Ray casts against tiles and terrain. */ diff --git a/src/render/contract/frame.d.ts b/src/render/contract/frame.d.ts index 4f5de2fbd..77b038a1d 100644 --- a/src/render/contract/frame.d.ts +++ b/src/render/contract/frame.d.ts @@ -72,7 +72,7 @@ export interface FramePort { diagnostics(): FrameDiagnostics; /** Stop ticking while the page is hidden; resume on `false`. */ suspend(hidden: boolean): void; - /** Draw a frame now, synchronously. */ + /** Draw a frame now, synchronously; throws when the frame fails to draw. */ renderNow(): void; /** Resolves after the next frame has been drawn and presented. */ renderOnce(options?: { timeoutMs?: number }): Promise; diff --git a/src/render/contract/index.js b/src/render/contract/index.js index 84c69b9d1..590500fdf 100644 --- a/src/render/contract/index.js +++ b/src/render/contract/index.js @@ -45,6 +45,8 @@ export const CAPABILITIES = Object.freeze([ 'globeVisibility', 'followFrame', 'cameraChangeThreshold', + 'occlusionTest', + 'keepEarthFramed', ]); /** @type {readonly import('./frame').FrameStep[]} */ @@ -199,9 +201,10 @@ export const PORTS = deepFreeze({ 'matrices', ), ['followFrame', 'followFrame'], + ['controls.keepEarthFramed', 'keepEarthFramed'], ]), - query: Object.fromEntries( - required( + query: Object.fromEntries([ + ...required( 'pick', 'drillPick', 'pickPosition', @@ -216,7 +219,8 @@ export const PORTS = deepFreeze({ 'clampToSurface', 'rayCast', ), - ), + ['occlusionTest', 'occlusionTest'], + ]), input: Object.fromEntries( required( 'on', diff --git a/src/render/contract/query.d.ts b/src/render/contract/query.d.ts index 445345d9a..d2309f66b 100644 --- a/src/render/contract/query.d.ts +++ b/src/render/contract/query.d.ts @@ -92,6 +92,12 @@ export interface QueryPort { projectMany(source: Float64Array, out: Float32Array): void; /** Hidden by the ellipsoid's horizon from the current eye. */ isOccluded(position: Ecef): boolean; + /** + * `occlusionTest`: a test of many points against the depth of the frames + * drawn, for overlays that leave out what something stands in front of. + * Each call makes a new one; its owner destroys it. + */ + occlusionTest?(): OcclusionTest; /** `sampleHeight`: cached height now, or null when not loaded. */ sampleHeightNow(point: LonLat, options?: HeightOptions): number | null; /** @@ -113,3 +119,47 @@ export interface QueryPort { options?: HeightOptions & { maxDistance?: number }, ): Promise; } + +/** + * One point under test (`OcclusionTest.add`): the test's owner keeps it and + * reads the answer from it. The test sets `pending` when it takes the point, + * and when the answer comes clears `pending`, sets `answered` and, when + * something drawn stood in front of the point, sets `lastHiddenAt` to + * `OcclusionTest`'s clock as of the frame it was tested against. + */ +export interface OcclusionPoint { + pending: boolean; + answered: boolean; + lastHiddenAt: number; + /** When the owner queued it, on the same clock. */ + queuedAt: number; +} + +/** + * Tests points against the depth of the frames as drawn, without waiting + * for the GPU: an answer may come a frame or two after its test. + */ +export interface OcclusionTest { + /** + * `'async'` while answers come a frame or two after their test, `'sync'` + * while they come at once, `'off'` while nothing can be tested (no depth + * to test against): every point is then to be taken as seen. + */ + readonly mode: 'async' | 'sync' | 'off'; + /** How many points it takes in one frame; Infinity when unbounded. */ + readonly maxPerFrame: number; + /** Open a frame, collecting the answers that have come; `now` dates them. */ + beginFrame(now: number): void; + /** + * Test `point`, at `position`, against this frame: hidden when a surface + * drawn stands in front of it by more than a small margin, which grows as + * the view looks along the ground rather than down on it. False when it + * cannot take one more this frame. + */ + add(point: OcclusionPoint, position: Ecef): boolean; + /** Close the frame: start the tests taken. */ + endFrame(): void; + /** Drop every test under way. */ + reset(): void; + destroy(): void; +} diff --git a/src/render/contract/renderer.d.ts b/src/render/contract/renderer.d.ts index 33313ba3b..2c10f017e 100644 --- a/src/render/contract/renderer.d.ts +++ b/src/render/contract/renderer.d.ts @@ -25,6 +25,39 @@ export interface RendererPlugin { /** Stable id, recorded with each session (`'cesium'`, ...). */ id: string; create(options: CreateOptions): Promise; + /** + * What the plugin hands the application beside the contract for a + * renderer it made, asked once, right after `create` resolves. Omitted: + * none. + */ + applicationHooks?(renderer: Renderer): ApplicationHooks; +} + +/** + * What only some renderers have and the application uses where given, does + * application uses each where given and does without where not. None is a + * do is in the ports. + */ +export interface ApplicationHooks { + /** + * The renderer's own map engine, which the map stacks switch through in + * place of the globe port (`src/maps/engine.js`). + */ + mapEngine?: unknown; + /** + * True when the renderer shows its credits in a display of its own; + * otherwise the application shows what the credits port lists. + */ + ownCreditDisplay?: boolean; + /** + * Drop the draw commands the renderer keeps for a while after it stops + * drawing them; run after a layer turns off. + */ + trimStaleCommands?(): void; + /** Whether an entity is one the renderer draws itself. */ + viewerDrawsEntity?(entity: unknown): boolean; + /** Values QA scripts read from the page's debug handle. */ + qaHandles?: Readonly>; } export interface CreateOptions { diff --git a/src/render/stub/camera.js b/src/render/stub/camera.js index 1bb3b03ad..95a849401 100644 --- a/src/render/stub/camera.js +++ b/src/render/stub/camera.js @@ -75,7 +75,8 @@ const ONE_DEGREE = Math.PI / 180; * @param {(reason: string) => void} options.requestRender * @param {(error: Error) => void} options.report * @param {boolean} [options.thresholds] `cameraChangeThreshold`: each - * `changed` listener's own threshold (default true). + * `changed` listener's own threshold (default true). `framing`: whether + * the controls have `keepEarthFramed` (default false). */ export function createStubCamera({ viewport, @@ -85,6 +86,7 @@ export function createStubCamera({ report, drawnPosition = () => null, thresholds = true, + framing = false, }) { // Local frame values; world values are `frame` applied to them. let frame = IDENTITY; @@ -147,6 +149,9 @@ export function createStubCamera({ pitchRange: [-Math.PI / 2, 0], zoomInputs: ['wheel', 'pinch', 'rightDrag'], }; + // The stub takes no user input: there is nothing to keep framed, and the + // setting only reads back. + if (framing) controls.keepEarthFramed = false; function aspectRatio() { const { width, height } = viewport(); diff --git a/src/render/stub/index.js b/src/render/stub/index.js index aefd1f0eb..31cf36e94 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -234,6 +234,7 @@ export function createStubRenderer(options = {}) { report, drawnPosition: (ref, aheadMs) => drawnPosition(ref, aheadMs), thresholds: capabilities.has('cameraChangeThreshold'), + framing: capabilities.has('keepEarthFramed'), }); camera.setViewRectangle(viewRectangle); if (capabilities.has('followFrame')) @@ -1064,6 +1065,28 @@ export function createStubRenderer(options = {}) { return rayEllipsoid(ray); }, }; + // The stub's only surface is the ellipsoid: a point is hidden behind its + // horizon, answered at once. + if (capabilities.has('occlusionTest')) + query.occlusionTest = () => { + let now = 0; + return { + mode: 'sync', + maxPerFrame: Number.POSITIVE_INFINITY, + beginFrame(t) { + now = t; + }, + add(point, position) { + point.pending = false; + point.answered = true; + if (isOccluded(position)) point.lastHiddenAt = now; + return true; + }, + endFrame() {}, + reset() {}, + destroy() {}, + }; + }; // --- Input -----------------------------------------------------------------