Move geo import, voice capture, visual settings, scope mask and recent imagery onto the renderer ports

Geo import asks the frame port for renders, the camera port for moveEnd and
the globe port's progress for the terrain queue running dry; its data sources
are added, removed and shown by the listed geoImportPins module. Voice capture
waits on the frame port's postRender. Visual settings toggle the infrared fog
through the globe sky port, and the anime style dims the Milky Way through a
sky getter it is given. The scope mask reads the camera height and listens on
the frame and camera ports. Recent imagery picks the view centre, reads the
view rectangle and the field of view through the query and camera ports.
Installations claim camera sensitivity from their rendering module. The
application shell loads the unbound globe factory.
This commit is contained in:
Sameh Khamis committed 2026-11-07 18:10:39 -08:00
1 parent b19fa56565
commit 81d8e3a4a7
20 files changed
+308 -119

No files matched your search

+30
View File
@@ -509,3 +509,33 @@ export function dataSourcePoints(dataSource, time = Cesium.JulianDate.now()) {
}
return points;
}
/**
* Draw an imported file's data source on `viewer`: resolves once the viewer
* has taken it.
* @param {object} viewer
* @param {object} dataSource
* @returns {Promise<void>}
*/
export async function addImportedSource(viewer, dataSource) {
await viewer.dataSources.add(dataSource);
}
/**
* Take an imported file's data source off `viewer` and destroy it; nothing
* when the viewer has no data sources left.
* @param {object} viewer
* @param {object} dataSource
*/
export function removeImportedSource(viewer, dataSource) {
viewer.dataSources?.remove?.(dataSource, true);
}
/**
* Show or hide an imported file's data source (its entities and pins).
* @param {object} dataSource
* @param {boolean} show
*/
export function showImportedSource(dataSource, show) {
dataSource.show = show;
}
+2 -10
View File
@@ -1,9 +1,5 @@
import { cameraOf } from '../../render/rendererOf.js';
import { CAMERA_CHANGED_THRESHOLD, LAYER_ID } from './policy.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
export function createLifecycle({
state: layerState,
@@ -52,11 +48,7 @@ export function createLifecycle({
});
parts.namedMarkers?.enable();
parts.namedMarkers?.sync(layerState.records || []);
claimCameraSensitivity(
layerState.viewer.camera,
LAYER_ID,
CAMERA_CHANGED_THRESHOLD,
);
parts.rendering.claimCameraChanges?.();
registerPickOwner(LAYER_ID, (id) => layerState.recordById.has(id));
layerState.dataSource.show = true;
// DataLayerManager invokes update() immediately after enable(), which owns
@@ -67,7 +59,7 @@ export function createLifecycle({
layerState.enabled = false;
services.credits?.hideOsmCredit?.(layerState.viewer, LAYER_ID);
parts.namedMarkers?.hide();
releaseCameraSensitivity(layerState.viewer?.camera, LAYER_ID);
parts.rendering.releaseCameraChanges?.();
layerState.contextAnchor = null;
layerState.contextPosition = null;
layerState.coverage = { kind: 'viewport' };
+27 -1
View File
@@ -4,7 +4,16 @@ import * as Cesium from 'cesium';
// factory its other parts reach the renderer through.
import '../../render/cesium/camera.js';
import { t } from '../../i18n/index.js';
import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from './policy.js';
import {
CAMERA_CHANGED_THRESHOLD,
LAYER_ID,
MAX_RENDERED,
COLOR_BY_CLASS,
} from './policy.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
import { entityRecord } from '../../data/entityRecords.js';
import { installationMarkers } from './markerState.js';
@@ -382,9 +391,26 @@ export function createRendering({
renderRecords();
});
}
/**
* While the layer is on, the Cesium camera reports changes at the layer's
* threshold to its own `changed` listeners too (the camera port measures
* each listener's threshold itself).
*/
function claimCameraChanges() {
claimCameraSensitivity(
layerState.viewer.camera,
LAYER_ID,
CAMERA_CHANGED_THRESHOLD,
);
}
function releaseCameraChanges() {
releaseCameraSensitivity(layerState.viewer?.camera, LAYER_ID);
}
return {
attach,
detach,
claimCameraChanges,
releaseCameraChanges,
installationSurfaceHeightM,
clearSelectionFill,
syncSelectionFill,
+23 -36
View File
@@ -20,7 +20,7 @@ import {
PRODUCTS,
boxCentre,
boxFromPin,
boxFromRectangle,
boxFromDegrees,
boxSideKm,
dequantizeBox,
fitViewHeightM,
@@ -33,8 +33,14 @@ import {
viewTooLargeMessage,
} from './model.js';
import { msg, t } from '../../i18n/index.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { READOUT_WORDS, displayDay, displayMetres } from './display.js';
import { findCamera, findGlobe } from '../../render/rendererOf.js';
import {
canvasOf,
findCamera,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
/**
* Quiet time after the last arrow key before the focused day previews, so a
@@ -67,10 +73,6 @@ const clampUnit = (value, fallback) => {
const boxSignature = (box) =>
box ? BOX_EDGES.map((edge) => Number(box[edge]).toFixed(6)).join(',') : '';
const sourceOf = (product) => PRODUCTS[product]?.source || null;
const toDegrees = (radians) => (radians * 180) / Math.PI;
const toRadians = (degrees) => (degrees * Math.PI) / 180;
const ellipsoidOf = (viewer) =>
viewer?.scene?.ellipsoid || viewer?.scene?.globe?.ellipsoid || null;
/**
* The ground under the canvas centre, in degrees; null when the centre is
@@ -79,20 +81,14 @@ const ellipsoidOf = (viewer) =>
* @returns {{ lon: number, lat: number } | null}
*/
function viewCentre(viewer) {
const ellipsoid = ellipsoidOf(viewer);
const canvas = viewer?.scene?.canvas;
const query = findQuery(viewer);
const canvas = canvasOf(viewer);
const width = Number(canvas?.clientWidth);
const height = Number(canvas?.clientHeight);
if (!ellipsoid?.cartesianToCartographic || !(width > 0) || !(height > 0))
return null;
const hit = viewer.camera?.pickEllipsoid?.(
{ x: width / 2, y: height / 2 },
ellipsoid,
);
const ground = hit ? ellipsoid.cartesianToCartographic(hit) : null;
return ground
? { lon: toDegrees(ground.longitude), lat: toDegrees(ground.latitude) }
: null;
if (!query || !(width > 0) || !(height > 0)) return null;
const hit = query.pickEllipsoid(width / 2, height / 2);
const ground = hit ? toLonLatH(hit) : null;
return ground ? { lon: ground.lon, lat: ground.lat } : null;
}
const modeFrom = (value) =>
MODES.includes(value)
@@ -963,10 +959,10 @@ export function createRecentImageryLayer({
* @returns {boolean}
*/
useCurrentView(viewer = _viewer) {
const rectangle = viewer?.camera?.computeViewRectangle?.();
const rectangle = findCamera(viewer)?.viewRectangle();
if (!rectangle)
return refuseBox('Point the camera at the ground to use the view');
const box = boxFromRectangle(rectangle);
const box = boxFromDegrees(rectangle);
if (validateBox(box).reason === 'too-large') {
const { width, height } = boxSideKm(box);
return refuseBox(
@@ -985,29 +981,20 @@ export function createRecentImageryLayer({
*/
zoomToFit() {
const target = _boxError ? _refusalTarget : null;
const camera = _viewer?.camera;
const ellipsoid = ellipsoidOf(_viewer);
// No camera port: a viewer of the caller's own whose renderer did not
// bring the camera factory (GEV's own imagery renderer does).
const port = findCamera(_viewer);
if (!target || !port || !ellipsoid?.cartographicToCartesian) return null;
const canvas = _viewer.scene?.canvas;
if (!target || !port) return null;
const canvas = canvasOf(_viewer);
const height = fitViewHeightM({
width: canvas?.clientWidth,
height: canvas?.clientHeight,
fovy: camera?.frustum?.fovy,
fovy: port.pose().fovy,
});
port.flyTo(fromDegrees(target.lon, target.lat, height), {
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
durationS: ZOOM_FIT_SECONDS,
});
port.flyTo(
ellipsoid.cartographicToCartesian({
longitude: toRadians(target.lon),
latitude: toRadians(target.lat),
height,
}),
{
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
durationS: ZOOM_FIT_SECONDS,
},
);
return height;
},
+19 -12
View File
@@ -27,6 +27,7 @@ import {
settle,
} from './testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
import { fakeSceneQuery } from '../../testSupport/fakeCesiumScene.mjs';
const NOW = new Date('2026-09-21T15:00:00Z');
const LINK_BOX = {
@@ -116,6 +117,7 @@ function fixture({
controller = fakeController(),
viirs = true,
globeOf,
ports = () => ({}),
} = {}) {
const renderer = fakeRenderer();
const thumbnails = fakeThumbnails();
@@ -138,7 +140,7 @@ function fixture({
});
if (viirs) layer.setSources({ viirs: true });
const viewer = { camera: {} };
bindFakeCesiumCamera(viewer);
bindFakeCesiumCamera(viewer, ports(viewer));
const reasons = [];
layer.subscribe((snapshot, reason) => reasons.push(reason));
layer.init(viewer);
@@ -996,7 +998,8 @@ test('USE VIEW takes the camera rectangle and refuses a view over the cap instea
});
test('ZOOM IN: an oversized box or view flies top-down to its centre at the height whose view is 400 km wide', () => {
const f = fixture();
// The renderer's query port picks the ellipsoid through the camera's own.
const f = fixture({ ports: (viewer) => ({ query: fakeSceneQuery(viewer) }) });
const flights = [];
const landing = (i) =>
Cesium.Ellipsoid.WGS84.cartesianToCartographic(flights[i].destination);
@@ -1007,21 +1010,25 @@ test('ZOOM IN: an oversized box or view flies top-down to its centre at the heig
const expected = 400_000 / (2 * Math.tan(Math.PI / 6));
let centreHit = null;
Object.assign(f.viewer, {
scene: {
canvas: { clientWidth: 1000, clientHeight: 500 },
ellipsoid: {
cartographicToCartesian: (c) =>
Cesium.Ellipsoid.WGS84.cartographicToCartesian(c),
cartesianToCartographic: (c) => c && { ...c },
},
},
canvas: { clientWidth: 1000, clientHeight: 500 },
});
Object.assign(f.viewer.camera, {
frustum: { fovy },
flyTo: (options) => flights.push(options),
pickEllipsoid: (position) => {
assert.deepEqual(position, { x: 500, y: 250 }, 'the canvas centre');
return centreHit;
assert.deepEqual(
[position.x, position.y],
[500, 250],
'the canvas centre',
);
return (
centreHit &&
Cesium.Cartesian3.fromRadians(
centreHit.longitude,
centreHit.latitude,
centreHit.height,
)
);
},
});
f.layer.enable();
+5
View File
@@ -237,6 +237,11 @@ function mapBox(box, fn) {
});
}
/** Degrees box from a degrees rectangle (the camera port's `viewRectangle`). */
export function boxFromDegrees(rectangle) {
return mapBox(rectangle, (degrees) => degrees);
}
/** Degrees box from a radians rectangle (Cesium `Rectangle` shape). */
export function boxFromRectangle(rectangle) {
return mapBox(rectangle, (radians) => (Number(radians) * 180) / Math.PI);
+8 -7
View File
@@ -1,5 +1,6 @@
import { getKeyholeGeometry } from './celestialRing.js';
import { SCOPE_FEATHER_RATIO_MAX } from './scopeMaskPolicy.js';
import { findCamera, findFrame } from './render/rendererOf.js';
/**
* Scope mask — the app's signature circular viewport treatment, made real.
@@ -446,7 +447,7 @@ export function installScopeMask(viewer) {
/** @returns {number} Live camera height above the ellipsoid, or +Inf if unknown. */
function currentCameraHeightM() {
const height = _viewer?.camera?.positionCartographic?.height;
const height = findCamera(_viewer)?.pose().height;
return Number.isFinite(height) ? height : Number.POSITIVE_INFINITY;
}
@@ -460,9 +461,9 @@ function currentCameraHeightM() {
* @returns {void}
*/
function watchCameraHeight(viewer) {
const preRender = viewer?.scene?.preRender;
if (preRender?.addEventListener) {
_cameraSampleRemover = preRender.addEventListener(() => {
const frame = findFrame(viewer);
if (frame) {
_cameraSampleRemover = frame.on('preRender', () => {
// SCOPE OFF paints nothing, so it samples nothing: no height read, no
// throttle bookkeeping, no quantize — the listener is a single compare.
// setScopeMaskEnabled(true) re-syncs the alpha it skipped.
@@ -474,9 +475,9 @@ function watchCameraHeight(viewer) {
updateScopeTerminusForHeight(currentCameraHeightM());
});
}
const moveEnd = viewer?.camera?.moveEnd;
if (moveEnd?.addEventListener) {
_cameraMoveEndRemover = moveEnd.addEventListener(() => {
const camera = findCamera(viewer);
if (camera) {
_cameraMoveEndRemover = camera.on('moveEnd', () => {
if (!_enabled) return;
updateScopeTerminusForHeight(currentCameraHeightM());
});
+12 -6
View File
@@ -27,6 +27,7 @@ import {
_resetScopeMaskForTest,
} from './scopeMask.js';
import { KEYHOLE_OUTER_RADIUS } from './celestialRing.js';
import { bindFakeCesiumScene } from './testSupport/fakeCesiumScene.mjs';
import { SCOPE_FEATHER_RATIO_MAX, clampScopeFeatherPct } from './scopeMaskPolicy.js';
beforeEach(() => _resetScopeMaskForTest());
@@ -412,7 +413,10 @@ test('one quantum is the smallest step that can repaint', () => {
// ~8 Hz through the altitude band and draw() performed the full backing-store
// resize + clear BEFORE checking whether the scope was even enabled.
/** A viewer stub with the two camera signals the terminus sampler listens on. */
/**
* A viewer stub with the two camera signals the terminus sampler listens on,
* read through the renderer's frame and camera ports as the app's are.
*/
function stubScopeViewer(container, heightM) {
const preRenderListeners = new Set();
const moveEndListeners = new Set();
@@ -421,12 +425,14 @@ function stubScopeViewer(container, heightM) {
set.add(listener);
return () => set.delete(listener);
};
const viewer = {
container,
scene: { preRender: { addEventListener: addTo(preRenderListeners) } },
camera: { positionCartographic, moveEnd: { addEventListener: addTo(moveEndListeners) } },
};
bindFakeCesiumScene(viewer);
return {
viewer: {
container,
scene: { preRender: { addEventListener: addTo(preRenderListeners) } },
camera: { positionCartographic, moveEnd: { addEventListener: addTo(moveEndListeners) } },
},
viewer,
setHeight(next) { positionCartographic.height = next; },
raisePreRender(times = 1) {
for (let i = 0; i < times; i += 1) for (const fn of [...preRenderListeners]) fn();
+1
View File
@@ -37,6 +37,7 @@ import { cameraOf, findCamera } from '../render/cesium/camera.js';
// and asking the viewer's entities whether Cockpit's aircraft still draws,
// keep this module on the Cesium allow-list.
import '../render/cesium/effects.js';
import '../render/cesium/globe.js';
import { aircraftTrackingTarget } from '../cockpitTracking.js';
+34 -17
View File
@@ -4,9 +4,20 @@ import {
MAX_IMPORTED_FILES,
loadGeoFile,
} from '../data/geoFileImport.js';
import { dataSourcePoints } from '../data/geoImportPins.js';
import {
addImportedSource,
dataSourcePoints,
removeImportedSource,
showImportedSource,
} from '../data/geoImportPins.js';
import { formatNumber, t, tn, translateKnown } from '../i18n/index.js';
import { flyToFootprint } from './flyToDataSource.js';
import {
canvasOf,
findCamera,
findFrame,
findGlobe,
} from '../render/rendererOf.js';
/** Fly to the whole footprint of one imported file's data source. */
const flyToDataSource = (viewer, dataSource, options) =>
@@ -73,7 +84,7 @@ export function initGeoFileImport({
hint = text || '';
present();
};
const render = () => viewer.scene?.requestRender?.();
const render = () => findFrame(viewer)?.requestRender('geo-import');
let groundTimer,
groundQueued = false,
groundAgain = false;
@@ -114,14 +125,20 @@ export function initGeoFileImport({
}, 200);
};
removeMapSource = subscribeMapSource?.(scheduleGround);
const ownEvent = (event, listener) => {
const remove = event?.addEventListener?.(listener);
if (remove) groundRemovers.push(remove);
};
ownEvent(viewer.camera?.moveEnd, scheduleGround);
ownEvent(viewer.scene?.globe?.tileLoadProgressEvent, (pending) => {
if (!pending) scheduleGround();
});
const camera = findCamera(viewer);
if (camera) groundRemovers.push(camera.on('moveEnd', scheduleGround));
// Terrain tiles finishing loading: the queue running dry, once each time.
let terrainPending = null;
const globe = findGlobe(viewer);
if (globe)
groundRemovers.push(
globe.on('progress', (progress) => {
const pending = progress.terrainPending;
if (pending === terrainPending) return;
terrainPending = pending;
if (!pending) scheduleGround();
}),
);
/** Publish the file list and hint; the view renders them. */
function present() {
@@ -171,7 +188,7 @@ export function initGeoFileImport({
const item = find(id);
if (!item) return false;
item.visible = Boolean(visible);
item.dataSource.show = item.visible;
showImportedSource(item.dataSource, item.visible);
if (item.visible) scheduleGround();
present();
render();
@@ -219,7 +236,7 @@ export function initGeoFileImport({
const at = imports.findIndex((item) => item.id === id);
if (at < 0) return false;
const [item] = imports.splice(at, 1);
viewer.dataSources?.remove?.(item.dataSource, true);
removeImportedSource(viewer, item.dataSource);
item.revoke?.();
present();
render();
@@ -298,9 +315,9 @@ export function initGeoFileImport({
revoke: loaded.revoke,
refreshGround: loaded.refreshGround,
};
await viewer.dataSources.add(item.dataSource);
await addImportedSource(viewer, item.dataSource);
if (destroyed) {
viewer.dataSources.remove?.(item.dataSource, true);
removeImportedSource(viewer, item.dataSource);
item.revoke?.();
break;
}
@@ -341,10 +358,10 @@ export function initGeoFileImport({
const gesture = () => {
cameraIntent += 1;
};
listen(viewer.scene?.canvas || container, 'pointerdown', gesture, {
listen(canvasOf(viewer) || container, 'pointerdown', gesture, {
passive: true,
});
listen(viewer.scene?.canvas || container, 'wheel', gesture, {
listen(canvasOf(viewer) || container, 'wheel', gesture, {
passive: true,
});
const hasFiles = (event) =>
@@ -407,7 +424,7 @@ export function initGeoFileImport({
clearTimeout(groundTimer);
for (const remove of groundRemovers) remove();
for (const item of imports.splice(0)) {
viewer.dataSources?.remove?.(item.dataSource, true);
removeImportedSource(viewer, item.dataSource);
item.revoke?.();
}
for (const [target, type, listener, options] of listeners.splice(0))
+65 -1
View File
@@ -9,6 +9,7 @@ import assert from 'node:assert/strict';
import fs from 'node:fs';
import { initGeoFileImport, summarize } from './geoFileImport.js';
import { GeoImportError, MAX_IMPORTED_FILES } from '../data/geoFileImport.js';
import { bindRenderer } from '../render/rendererOf.js';
class FakeClassList {
constructor() {
@@ -59,7 +60,13 @@ class FakeElement {
}
}
function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
function setup({
load,
navigation,
flyToSource,
subscribeMapSource,
ports,
} = {}) {
const els = {
'geo-import-button': new FakeElement('button', 'geo-import-button'),
};
@@ -90,6 +97,9 @@ function setup({ load, navigation, flyToSource, subscribeMapSource } = {}) {
},
flyTo: (target) => flights.push(target),
};
// The renderer's ports, when the test gives them, bound before the import
// starts as the application binds its renderer.
if (ports) bindRenderer(viewer, ports);
const revoked = [];
const loads = [];
const defaultLoad = async (file, opts) => {
@@ -471,6 +481,60 @@ test('ground refresh coalesces map changes and releases its subscription on tear
assert.equal(unsubscribed, 1);
});
test('the camera settling and the terrain queue running dry refresh the ground, through the ports', async () => {
const listeners = { moveEnd: new Set(), progress: new Set() };
const on = (name) => (event, cb) => {
assert.equal(event, name);
listeners[name].add(cb);
return () => listeners[name].delete(cb);
};
const reasons = [];
let refreshed = 0;
const t = setup({
ports: {
camera: { on: on('moveEnd') },
globe: { on: on('progress') },
frame: { requestRender: (reason) => reasons.push(reason) },
},
load: async () => ({
name: 'point.geojson',
format: 'geojson',
entityCount: 1,
dataSource: {},
refreshGround: async () => refreshed++,
}),
});
const settle = () => new Promise((resolve) => setTimeout(resolve, 300));
const progress = (terrainPending) => {
for (const cb of [...listeners.progress])
cb({ tilesPending: 0, imageryPending: 0, terrainPending });
};
await t.tool.importFiles([file('point.geojson')]);
assert.ok(reasons.length > 0 && reasons.every((r) => r === 'geo-import'));
for (const cb of [...listeners.moveEnd]) cb();
await settle();
assert.equal(refreshed, 1, 'the camera settling refreshes once');
// The first report of an empty terrain queue counts, then only the queue
// running dry again, once each time it does; progress that leaves the
// terrain count where it was (imagery only) does not.
progress(0);
await settle();
assert.equal(refreshed, 2);
progress(0);
await settle();
assert.equal(refreshed, 2);
progress(3);
progress(1);
await settle();
assert.equal(refreshed, 2);
progress(0);
await settle();
assert.equal(refreshed, 3);
t.tool.destroy();
assert.equal(listeners.moveEnd.size, 0);
assert.equal(listeners.progress.size, 0);
});
test('Fly to is an immediate navigation that Cockpit can refuse', async () => {
const flown = [];
const nav = navigationDouble({ immediate: false });
+2 -2
View File
@@ -27,7 +27,7 @@ import {
import { displayDay, displayMetres } from '../layers/recentImagery/display.js';
import { formatQuantity } from './unitLabels.js';
import { pointerOwnerName } from '../data/pointerOwnerNames.js';
import { canvasOf, findGlobe } from '../render/rendererOf.js';
import { canvasOf, findFrame, findGlobe } from '../render/rendererOf.js';
const PANEL_ID = 'recent-imagery-panel';
const OVERVIEW_MIN_BOX_KM = 25;
@@ -206,7 +206,7 @@ export function createRecentImageryPanel({
fetchImpl = globalThis.fetch?.bind(globalThis),
createObjectUrl = (blob) => URL.createObjectURL(blob),
revokeObjectUrl = (url) => URL.revokeObjectURL(url),
requestRender = () => viewer?.scene?.requestRender?.(),
requestRender = () => findFrame(viewer)?.requestRender('recent-imagery'),
} = {}) {
const document = container?.ownerDocument;
if (!document?.createElement || !layer) return null;
+13
View File
@@ -117,6 +117,19 @@ test('visual teardown restores owned fog and aircraft sensor state once', async
});
const calls = [];
const viewer = { scene: { fog: { enabled: false } } };
// The fog is the globe port's sky, which writes the scene's, as the
// renderer's does.
const { bindRenderer } = await import('../render/rendererOf.js');
bindRenderer(viewer, {
globe: {
sky: {
get: () => ({ fog: viewer.scene.fog.enabled }),
set(settings) {
if ('fog' in settings) viewer.scene.fog.enabled = settings.fog;
},
},
},
});
const owner = new VisualSettings({
viewer,
elements: {},
+5 -6
View File
@@ -40,13 +40,15 @@ export function styleDefinition(name, shader) {
export class VisualEffects {
/**
* @param {object} options - The renderer's effects port (null: records
* only), the viewer whose sky the anime style dims, render ownership
* only), the viewer, a getter for the globe's sky port the anime
* style dims (null: the sky is left alone), render ownership
* callbacks and optional clocks. Construction is inert;
* initStyles/initPostProcess retain startup ordering.
*/
constructor({
effects = null,
viewer,
sky = null,
requestRender,
holdRender,
releaseRender,
@@ -56,6 +58,7 @@ export class VisualEffects {
}) {
this.effects = effects;
this.viewer = viewer;
this.sky = sky;
this.requestRender = requestRender;
this.holdRender = holdRender;
this.releaseRender = releaseRender;
@@ -164,11 +167,7 @@ export class VisualEffects {
stage.enabled = value > OFF;
// Anime's bands turn the faint Milky Way into blotches, and depth cannot
// tell the sky from far geometry, so the glow fades with the style.
if (
stage === this.stages.anime &&
this.viewer?.scene?.skyBox?.milkyWayVisibility !== undefined
)
this.viewer.scene.skyBox.milkyWayVisibility = 1 - value;
if (stage === this.stages.anime) this.sky?.()?.set({ milkyWay: 1 - value });
this.requestRender('style-stage');
}
+9 -1
View File
@@ -3,6 +3,7 @@ import test from 'node:test';
import { VisualEffects } from './visualEffects.js';
import { createCesiumEffects } from '../render/cesium/effects.js';
import { styleStagesOf } from '../styles/styleStages.js';
import { createCesiumGlobe } from '../render/cesium/globe.js';
import { MILKY_WAY_INTENSITY, StarrySky } from '../sky/starrySky.js';
import {
GLOBAL_POST_DEFAULTS,
@@ -63,9 +64,16 @@ function fixture() {
},
createStage: (options) => ({ ...options, enabled: true }),
});
// The sky the anime style dims is the globe port's, over the scene.
const viewer = { scene };
const globe = createCesiumGlobe(viewer, {
capabilities: new Set(),
requestRender() {},
}).port;
const effects = new VisualEffects({
effects: renderer.port,
viewer: { scene },
viewer,
sky: () => globe.sky,
requestRender: (reason) => requests.push(reason),
holdRender: (reason) => holds.add(reason),
releaseRender: (reason) => holds.delete(reason),
+17 -10
View File
@@ -5,7 +5,12 @@ import { useDisplayStore } from './stores/display.js';
import { applicationPinia } from './vueRuntime.js';
import { onLocaleChange, t } from '../i18n/index.js';
import { UiLifetime } from './uiLifetime.js';
import { findEffects, releaseUnboundEffects } from '../render/rendererOf.js';
import {
findEffects,
findFrame,
findGlobe,
releaseUnboundEffects,
} from '../render/rendererOf.js';
import {
VisualEffects,
STYLES,
@@ -198,6 +203,7 @@ export class VisualSettings {
this._visualEffects = new VisualEffects({
effects: findEffects(viewer),
viewer,
sky: () => findGlobe(viewer)?.sky,
requestRender: services.governorRequestRender,
holdRender: services.holdContinuousRender,
releaseRender: services.releaseContinuousRender,
@@ -424,17 +430,17 @@ export class VisualSettings {
// (owner cockpit-FLIR field rounds, 2026-08-16). IR sensors see through
// haze, so the boost styles simply turn fog off; the prior state restores
// on exit. Transition-guarded so repeated syncs don't clobber the saved value.
const scene = this.viewer?.scene;
if (scene?.fog && irBoost !== this._irBoostActive) {
// The globe's sky draws the fog; setting it asks for a frame.
const sky = findGlobe(this.viewer)?.sky;
if (sky && irBoost !== this._irBoostActive) {
this._irBoostActive = irBoost;
if (irBoost) {
this._irFogWasEnabled = scene.fog.enabled;
scene.fog.enabled = false;
this._irFogWasEnabled = sky.get().fog;
sky.set({ fog: false });
} else if (this._irFogWasEnabled != null) {
scene.fog.enabled = this._irFogWasEnabled;
sky.set({ fog: this._irFogWasEnabled });
this._irFogWasEnabled = null;
}
scene.requestRender?.();
}
}
@@ -623,7 +629,7 @@ export class VisualSettings {
fadeRatio: this._detectionFadePct / 100,
outsideOpacity: this._detectionOutsidePct / 100,
});
this.viewer.scene.requestRender?.();
findFrame(this.viewer)?.requestRender('detection-tuning');
}
_setDetectionAllocation(strategy, { syncShare = true, persist = true } = {}) {
@@ -1610,8 +1616,9 @@ export class VisualSettings {
}
releaseIrBoost() {
if (!this._irBoostActive) return;
if (this._irFogWasEnabled != null && this.viewer?.scene?.fog)
this.viewer.scene.fog.enabled = this._irFogWasEnabled;
const sky = findGlobe(this.viewer)?.sky;
if (this._irFogWasEnabled != null && sky)
sky.set({ fog: this._irFogWasEnabled });
this._dataManager?.setLayerParams('flights', { irBoost: false });
this._dataManager?.setLayerParams('military', { irBoost: false });
this._irBoostActive = false;
+13 -3
View File
@@ -2,6 +2,8 @@
// These helpers are DOM/WebRTC-free so they pin the screenshot down-scaling and
// payload-byte estimation that keep an oversized dc.send from stranding a turn.
import { test } from 'node:test';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs';
import assert from 'node:assert/strict';
import { DataLayerManager } from '../data/manager.js';
import { controlRadio as runControlRadio, createGevActionRunner as createActionRunner } from './gevActions.js';
@@ -36,6 +38,14 @@ import {
import { createVoiceCostTracker } from './voiceCost.js';
import { createTestVoiceUi } from '../testSupport/voiceUi.mjs';
/** A viewer over `scene` whose renderer's frame port is the scene's own loop. */
function framed(scene) {
const viewer = { scene };
bindRenderer(viewer, { frame: fakeSceneFrame(viewer) });
return viewer;
}
test('push-to-talk recognizes Space by code or key', () => {
assert.equal(PUSH_TO_TALK_HOLD_DELAY_MS, 500);
assert.equal(isPushToTalkKey({ code: 'Space', key: 'Unidentified' }), true);
@@ -2811,7 +2821,7 @@ test('hidden document yields no fresh frame — capture must not label a stale c
};
try {
globalThis.document = { hidden: true };
const fresh = await renderFreshCesiumFrame({ scene });
const fresh = await renderFreshCesiumFrame(framed(scene));
assert.equal(fresh, false, 'hidden capture reports non-fresh');
assert.equal(requested, 0, 'no secret render restart while hidden');
} finally {
@@ -2828,7 +2838,7 @@ test('visible document with a rendering scene reports a fresh frame', async () =
postRender: { addEventListener(listener) { fire = listener; return () => { fire = null; }; } },
requestRender() { queueMicrotask(() => fire?.()); },
};
const fresh = await renderFreshCesiumFrame({ scene });
const fresh = await renderFreshCesiumFrame(framed(scene));
assert.equal(fresh, true);
} finally {
globalThis.document = originalDocument;
@@ -2845,7 +2855,7 @@ test('a tab switch during the bounded render wait invalidates freshness', async
postRender: { addEventListener(listener) { fire = listener; return () => { fire = null; }; } },
requestRender() { doc.hidden = true; queueMicrotask(() => fire?.()); },
};
const fresh = await renderFreshCesiumFrame({ scene });
const fresh = await renderFreshCesiumFrame(framed(scene));
assert.equal(fresh, false, 'freshness rechecked after the await');
} finally {
globalThis.document = originalDocument;
+12 -2
View File
@@ -1,4 +1,6 @@
import assert from 'node:assert/strict';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs';
import test from 'node:test';
import {
RealtimeViewport,
@@ -6,6 +8,14 @@ import {
renderFreshPointerFrame,
} from './realtimeViewport.js';
/** A viewer over `scene` whose renderer's frame port is the scene's own loop. */
function framed(scene) {
const viewer = { scene };
bindRenderer(viewer, { frame: fakeSceneFrame(viewer) });
return viewer;
}
test('crop: a square around the pointer, clamped inside the canvas, in buffer pixels', () => {
assert.deepEqual(
pointerCropRect({
@@ -110,7 +120,7 @@ test('crop: a slow render gets one bounded fresh-frame recovery request', async
if (requests === 2) queueMicrotask(() => listener?.());
},
};
assert.equal(await renderFreshPointerFrame({ scene }), true);
assert.equal(await renderFreshPointerFrame(framed(scene)), true);
assert.equal(requests, 2, 'only the pointer path retries once');
assert.equal(listener, null, 'the successful listener is removed');
} finally {
@@ -129,7 +139,7 @@ test('crop: a hidden document never starts the recovery request', async () => {
requests += 1;
},
};
assert.equal(await renderFreshPointerFrame({ scene }), false);
assert.equal(await renderFreshPointerFrame(framed(scene)), false);
assert.equal(requests, 0);
} finally {
globalThis.document = originalDocument;
+5 -5
View File
@@ -3,7 +3,7 @@ import {
hasStructuredViewIdentity,
} from './realtimeProtocol.js';
import { cameraPoseKey } from './pointerContext.js';
import { canvasOf } from '../render/rendererOf.js';
import { canvasOf, findFrame } from '../render/rendererOf.js';
/** The live viewer's camera pose identity (Cesium-free read). */
function readViewerCameraKey() {
@@ -230,8 +230,8 @@ export function estimateDataUrlBytes(dataUrl) {
* canvas as current. (perf wave 2)
*/
export async function renderFreshCesiumFrame(viewer) {
const scene = viewer?.scene;
if (!scene) return false;
const frame = findFrame(viewer);
if (!frame) return false;
// While the document is hidden the render loop is suspended — don't
// secretly restart rendering for an optional screenshot, and don't pass
// the stale preserved frame off as current.
@@ -241,7 +241,7 @@ export async function renderFreshCesiumFrame(viewer) {
// necessarily draw — request a frame and await its postRender (bounded),
// which also covers the just-became-visible race.
const rendered = new Promise((resolve) => {
const remove = scene.postRender.addEventListener(() => {
const remove = frame.on('postRender', () => {
remove();
resolve(true);
});
@@ -250,7 +250,7 @@ export async function renderFreshCesiumFrame(viewer) {
resolve(false);
}, 400);
});
scene.requestRender?.();
frame.requestRender('voice-capture');
const fresh = await rendered;
// A tab switch during the bounded wait invalidates freshness.
if (typeof document !== 'undefined' && document.hidden) return false;