/** Camera placement, ground acquisition and motion correction for the Cockpit controller. */ import { cameraOf, findFrame, findQuery } from '../render/rendererOf.js'; import { heightsOf } from '../queries/heights.js'; import { followedPosition, isFollowing } from '../data/followed.js'; import { readEntityRecord } from '../data/entityRecords.js'; import { trackedEntityDrawn } from './cockpitTrackingController.js'; import { add, clone, eastNorthUp, frameVector, fromDegrees, fromRadians, magnitude, normalize, scale, sub, toCartographicRadians, toDegrees, toRadians, vec, } from '../geo/index.js'; import { cockpitAnchorCorrectionStep, cockpitGroundSafeHeight, easeCockpitLift, cockpitSubjectStepSec, cockpitSurfaceWaitExpired, cockpitUiUpdateDue, slewHeading, } from '../cockpitMath.js'; import { VESSEL_DEAD_RECKON_MAX_S, VESSEL_WATERLINE_REFRESH_MS, deadReckonVesselFix, vesselCameraProfile, vesselWaterlineM, waterlineProbePoints, } from '../cockpitSubjects.js'; import { easeLook } from '../cockpitLook.js'; import { cockpitSubjectFrame } from '../cockpitSubjectProviders.js'; import { COCKPIT_HEADING_SLEW_DPS, COCKPIT_FORWARD_OFFSET_M, COCKPIT_UP_OFFSET_M, COCKPIT_MIN_GROUND_CLEARANCE_M, COCKPIT_VIEW_PITCH_DEG, COCKPIT_CAMERA_UPDATE_MS, COCKPIT_HUD_UPDATE_MS, COCKPIT_GROUND_PROBE_MS, COCKPIT_GROUND_WAIT_TIMEOUT_MS, } from './cockpitPresentation.js'; /** * Where the aircraft Cockpit flies is now: its follow target's position at * scene time (what the drawn entity's position reads), or, for a target * with none, where it is shown. */ export function trackedPositionNow(viewer, followed) { if (typeof followed?.position === 'function') return followed.position(findFrame(viewer)?.time() ?? Date.now()); return followedPosition(viewer, followed); } /** The aircraft eye: just ahead of and above the reported position. */ const AIRCRAFT_CAMERA_PROFILE = Object.freeze({ forwardM: COCKPIT_FORWARD_OFFSET_M, upM: COCKPIT_UP_OFFSET_M, pitchDeg: COCKPIT_VIEW_PITCH_DEG, minClearanceM: COCKPIT_MIN_GROUND_CLEARANCE_M, }); export function update() { if (this.destroyed) return false; if (!this.active) { // Entry availability changes on a human timescale (tracking start/stop, // info arriving after a poll) — polling it every rendered frame ran // readAircraftInfo() + DOM pokes at display rate in plain map mode. // 250 ms keeps the chip imperceptibly fresh; trackedEntityChanged still // fires syncEntry immediately on the events that matter. (perf item 9) const nowMs = performance.now(); if (nowMs - (this._lastEntrySyncMs || 0) >= 250) { this._lastEntrySyncMs = nowMs; this.syncEntry(); } return; } const nowMs = performance.now(); if (this.subjectProvider) { updateSubject.call(this, nowMs); return; } if (this.subjectKind === 'vessel') { updateVessel.call(this, nowMs); return; } if (this.subjectKind === 'satellite') { this.updateOrbital(nowMs); return; } const info = this.readAircraftInfo(); // Adopt a newly selected track before the camera cadence gate. A context // NEXT/PREV selection can otherwise spend one frame driving the old // aircraft with the new aircraft's metadata. this._adoptTrackedEntity(nowMs, info); if ( !info || !this.trackedEntity || !trackedEntityDrawn.call(this, this.trackedEntity) ) { if (nowMs < this.contextNavigationDeadlineMs) return; this.exit({ restoreTracking: false }); return; } if ( !cockpitUiUpdateDue( nowMs, this.lastCameraUpdateMs, COCKPIT_CAMERA_UPDATE_MS, ) ) return; this.lastCameraUpdateMs = nowMs; const target = trackedPositionNow(this.viewer, this.trackedFollow); if (!target) return; const dtSec = Math.min(0.1, Math.max(0, (nowMs - this.lastFrameMs) / 1000)); this.lastFrameMs = nowMs; if (Number.isFinite(info.track)) { this.heading = slewHeading( this.heading ?? info.track, info.track, COCKPIT_HEADING_SLEW_DPS * dtSec, ); } placeCamera.call(this, target, info, nowMs, dtSec, AIRCRAFT_CAMERA_PROFILE); } /** * The surface the ridden ship floats on: the layer's geoid sea surface, or * the water read off the rendered scene when that sits higher (a river or * lake above sea level). The read runs in the background every * VESSEL_WATERLINE_REFRESH_MS. The full-detail read can take many seconds * from cold tiles, so a new ship's first read starts from the tiles already * on screen; until any read lands the sea surface stands. Only one * full-detail read runs at a time (each is nine picks Cesium traverses * every frame until it settles): while one is still running, a refresh * reads the loaded tiles instead, and the slow read applies whenever it * lands. Once a full-detail read has answered, only full-detail reads * change the height; before then a loaded-tile read may find raised water * but never takes a raised height back to the sea. One coarse probe cannot * drop a river bridge to the sea, and a read that sampled nothing keeps * the height it had. * @param {{latitude: number, longitude: number}} [at] Where to read the * water: the dead-reckoned position the camera rides. * @returns {number} Ellipsoidal metres. */ function vesselSurfaceM(info, nowMs, at = info) { const seaM = Number.isFinite(info.seaSurfaceHeightM) ? info.seaSurfaceHeightM : 0; const query = findQuery(this.viewer) ? heightsOf(this.viewer) : null; let read = this.vesselWaterline?.vesselId === info.id ? this.vesselWaterline : null; if ( query && (!read || nowMs - read.sampledMs >= VESSEL_WATERLINE_REFRESH_MS) ) { const probes = waterlineProbePoints(at.latitude, at.longitude).map( ({ lat, lon }) => ({ lon, lat }), ); if (!read) { read = { vesselId: info.id, heightM: loadedWaterlineM(query, probes, seaM), sampledMs: nowMs, // Whether a full-detail read has answered for this ship. landed: false, inFlight: false, }; this.vesselWaterline = read; } else { read.sampledMs = nowMs; if (read.inFlight && !read.landed) { const loadedM = loadedWaterlineM(query, probes, seaM); // Taking a river back to the sea is the full-detail read's to say. const lowers = Number.isFinite(read.heightM) && read.heightM > seaM && !(loadedM > seaM); if (Number.isFinite(loadedM) && !lowers) read.heightM = loadedM; } } if (!read.inFlight) readWaterline.call(this, read, query, probes, seaM); } return read && Number.isFinite(read.heightM) ? Math.max(seaM, read.heightM) : seaM; } /** Start one full-detail water read for `read`; its answer lands on it. */ function readWaterline(read, query, probes, seaM) { read.inFlight = true; // An async read: a failure arrives as a rejection, never a throw here. // The drawn surface, globe included, as the scene's own sample read it: // a lake on a globe map stands on its terrain. query.batch(probes).then( (samples) => { if (this.vesselWaterline !== read) return; read.inFlight = false; // However late it lands, it applies; one that sampled nothing (tiles // not loaded yet) is no answer and keeps the height already read. const heights = samples || []; if (!heights.some(Number.isFinite)) return; read.landed = true; read.heightM = vesselWaterlineM(seaM, heights); }, () => { if (this.vesselWaterline === read) read.inFlight = false; }, ); } /** * The waterline from the tiles already loaded, read at once: a first answer * while the full-detail read loads. Null when the scene cannot sample or no * probe met loaded geometry: nothing sampled is no answer, not the sea, so it * never undoes a river height a full read set. */ function loadedWaterlineM(query, probes, seaM) { try { const heights = probes.map((probe) => query.now(probe)); if (!heights.some(Number.isFinite)) return null; return vesselWaterlineM(seaM, heights); } catch { return null; } } /** * Drive the bridge camera from the selected vessel. The vessel layer redraws * a ship only when its feed refreshes, so the target is the last fix advanced * along course over ground; the shared anchor smoothing then absorbs the * correction each new fix brings. */ function updateVessel(nowMs) { // Tracking anything from the bridge (an aircraft, a satellite, a site) // takes the camera: entry stopped every follow, so any follow now is // another's. End the bridge and leave the camera following it. if (isFollowing(this.viewer)) { this.exit({ restoreTracking: false }); return; } const info = this.readVesselInfo(); if (!info || info.id !== this.subjectId) { this.exit({ restoreTracking: false }); return; } if ( !cockpitUiUpdateDue( nowMs, this.lastCameraUpdateMs, COCKPIT_CAMERA_UPDATE_MS, ) ) return; this.lastCameraUpdateMs = nowMs; const fix = deadReckonVesselFix( { latitude: info.latitude, longitude: info.longitude, courseDeg: info.motionCourse, speedMps: info.velocityMps, fixEpochMs: info.fixEpochMs, receivedAtMs: info.receivedAtMs, feedEpochMs: info.feedEpochMs, }, Date.now(), ); // The radar centres here too, so it agrees with the view out the window. this.vesselFix = fix; const target = fromDegrees( fix.longitude, fix.latitude, // Read the water where the ship is now, not at its last report. vesselSurfaceM.call(this, info, nowMs, fix), ); // The target advances in wall-clock time, so the anchor must too: the // aircraft path's 0.1 s step cap would leave a slow-frame or hitching bridge // falling ever further behind its own ship. const dtSec = Math.min( VESSEL_DEAD_RECKON_MAX_S, Math.max(0, (nowMs - this.lastFrameMs) / 1000), ); this.lastFrameMs = nowMs; if (Number.isFinite(info.track)) { this.heading = slewHeading( this.heading ?? info.track, info.track, COCKPIT_HEADING_SLEW_DPS * dtSec, ); } // Past the projection limit the target stops advancing; hold on it rather // than let the inertial anchor sail on alone. const projectionExpired = Number.isFinite(fix.ageSec) && fix.ageSec > VESSEL_DEAD_RECKON_MAX_S; // The look eases on its own clock: the anchor's step is capped differently. this.lookView = easeLook( this.lookView, this.lookTarget, nowMs - (this.lookLastMs || nowMs), ); this.lookLastMs = nowMs; // A ship reporting neither course nor heading has no direction to move // in: its anchor stays on the fix, as the dead reckoning does. const ridden = Number.isFinite(info.motionCourse) ? info : { ...info, velocityMps: 0 }; placeCamera.call( this, target, projectionExpired ? { ...ridden, stale: true } : ridden, nowMs, dtSec, vesselCameraProfile(info), this.lookView, ); } /** * Drive the camera from an application provider's subject: read its frame, * stand the eye `eye.upM` above `heightM` (the shared floor where the frame * gives none) and slew toward its heading. A frame that is null, malformed or * for another subject ends the view, as an aircraft tracked meanwhile does. * The update runs on the provider's `cameraIntervalMs` (0: every frame), and * its rates advance by the time that interval spans (cockpitSubjectStepSec). */ function updateSubject(nowMs) { const provider = this.subjectProvider; if (isFollowing(this.viewer)) { this.exit({ restoreTracking: false }); return; } const intervalMs = provider.cameraIntervalMs ?? COCKPIT_CAMERA_UPDATE_MS; if (!cockpitUiUpdateDue(nowMs, this.lastCameraUpdateMs, intervalMs)) return; this.lastCameraUpdateMs = nowMs; const frame = cockpitSubjectFrame( this.callSubject(provider, 'read', [nowMs, this.subjectContext()], null), this.subjectId, ); if (!frame) { this.exit({ restoreTracking: false }); return; } this.lastSubjectFrame = frame; let heightM = frame.heightM; if (heightM === null) { this.services.warmGroundFloor?.([ { lat: frame.latitude, lon: frame.longitude }, ]); const floorM = this.services.cachedGroundFloor?.( frame.latitude, frame.longitude, ); // A frame with no height stands on the shared floor; while that is cold // it keeps the height it last stood at. heightM = Number.isFinite(floorM) ? floorM : this.subjectHeightM; } if (!Number.isFinite(heightM)) { // Nothing to stand on yet, from the first frame: the camera stays where // it is while the floor is acquired, its HUD saying so, rather than // standing on the ellipsoid (kilometres underground on a plateau). The // wait is bounded as the built-in views' is. Unlike a parked aircraft, // whose fallback is its own reported altitude, such a subject has no // height at all to fall back to: any number would be a guess, so the // view ends and the provider gets its subject back. if (!this.surfaceWaitStartedMs) this.surfaceWaitStartedMs = nowMs; if ( cockpitSurfaceWaitExpired( nowMs, this.surfaceWaitStartedMs, COCKPIT_GROUND_WAIT_TIMEOUT_MS, ) ) { this.exit({ restoreTracking: false }); return; } this.surfaceAcquiring = true; if ( cockpitUiUpdateDue(nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS) ) { this.lastHudUpdateMs = nowMs; this.updateHud(this.subjectInfo(frame), nowMs); } return; } this.surfaceWaitStartedMs = 0; this.surfaceAcquiring = false; this.subjectHeightM = heightM; const target = fromDegrees(frame.longitude, frame.latitude, heightM); const dtSec = cockpitSubjectStepSec(nowMs - this.lastFrameMs, intervalMs); this.lastFrameMs = nowMs; if (frame.headingDeg !== null) { const rate = provider.headingSlewDps ?? COCKPIT_HEADING_SLEW_DPS; this.heading = rate === Infinity ? frame.headingDeg : slewHeading( this.heading ?? frame.headingDeg, frame.headingDeg, rate * dtSec, ); } let look = null; if (provider.look) { this.lookView = easeLook( this.lookView, this.lookTarget, nowMs - (this.lookLastMs || nowMs), ); this.lookLastMs = nowMs; look = this.lookView; } placeCamera.call( this, target, this.subjectInfo(frame), nowMs, dtSec, { forwardM: frame.eye.forwardM, upM: frame.eye.upM, pitchDeg: frame.eye.pitchDeg, minClearanceM: frame.eye.minClearanceM, }, look, ); } /** * Place the camera for one update: advance the inertial anchor, clamp it and * the eye against the rendered surface, and look along the slewed heading. * A subject with `anchor: 'exact'` keeps the anchor on its target (its layer * already moves it smoothly), and one with `groundClamp: false` (inside a * structure, say) is never pushed up to the floor: a lift it had eases out. * @param {{x: number, y: number, z: number}} target Authoritative subject position. * @param {object} info Subject info; `motionCourse` (when present) is the * direction the subject moves, otherwise it moves where it faces. * @param {number} nowMs Frame time. * @param {number} dtSec Seconds since the previous camera update. * @param {{forwardM: number, upM: number, pitchDeg: number, * minClearanceM: number}} profile Eye offsets for the subject kind. * @param {?{yawDeg: number, pitchDeg: number}} [look] A bridge view turned * off the bow: yaw relative to the heading and absolute pitch. It turns * only the view; the eye and its motion keep the heading and course. * Aircraft pass none and look along the heading at the profile pitch. */ function placeCamera(target, info, nowMs, dtSec, profile, look = null) { if (!this.cockpitAnchorValid) { this.cockpitAnchor = clone(target); this.cockpitAnchorValid = true; this.subjectLiftM = null; } // First-person motion cannot use the delayed feed correction as a raw // camera destination: a harmless icon re-anchor becomes a whole-world // surge/reversal in cockpit view. Advance the camera anchor inertially // from the reported course/speed and converge on the authoritative layer // display position at a bounded rate. This preserves the layer's required // 15/30-second interpolation and per-frame cache without exposing its // sample-boundary corrections to the camera. const headingRad = toRadians(this.heading ?? 0); const courseRad = Number.isFinite(info.motionCourse) ? toRadians(info.motionCourse) : headingRad; const pitchRad = toRadians(look ? look.pitchDeg : profile.pitchDeg); const viewHeadingRad = look ? toRadians((this.heading ?? 0) + look.yawDeg) : headingRad; const speedMps = Number.isFinite(info.velocityMps) ? Math.max(0, info.velocityMps) : 0; const groundClamp = info.groundClamp !== false; if (info.stale || info.anchor === 'exact') { // A feed backoff has no authoritative velocity epoch to advance from. // Hold the cockpit on the exact layer-rendered position so the camera // cannot coast away while the icon correctly remains fixed. this.cockpitAnchor = clone(target); } else { const horizontal = normalize( frameVector( eastNorthUp(this.cockpitAnchor), vec(Math.sin(courseRad), Math.cos(courseRad), 0), ), ); this.cockpitAnchor = add( this.cockpitAnchor, scale(horizontal, speedMps * dtSec), ); const correction = sub(target, this.cockpitAnchor); const correctionDistanceM = magnitude(correction); // An application subject's step is already bounded by its own update // interval (cockpitSubjectStepSec); the built-in views keep the 0.1 s. const correctionStepM = cockpitAnchorCorrectionStep( correctionDistanceM, speedMps, dtSec, info.generic === true ? dtSec : undefined, ); if (correctionStepM > 0 && correctionDistanceM > 0) { this.cockpitAnchor = add( this.cockpitAnchor, scale(correction, correctionStepM / correctionDistanceM), ); } } // The inertial anchor is independent of the layer's render-floor clamp and // can otherwise coast into a photoreal mesh while a landing contact is // between fixes. Clamp it against the same mesh-first shared floor used by // aircraft rendering. For a slow contact whose floor cell is still cold, // its already-clamped render position is a conservative temporary floor. const anchorCartographic = toCartographicRadians(this.cockpitAnchor); const targetCartographic = toCartographicRadians(target); // A bridge's target is its fix dead-reckoned up to minutes ahead: read // the floor where the ship is now, as its water is. const floorAt = info.kind === 'vessel' && targetCartographic ? { latitude: toDegrees(targetCartographic.lat), longitude: toDegrees(targetCartographic.lon), } : info; let cockpitFloorM = this.services.cachedGroundFloor( floorAt.latitude, floorAt.longitude, ); if (info.onGround === true) { const groundPoint = [{ lat: info.latitude, lon: info.longitude }]; this.services.warmGroundFloor(groundPoint); const meshFloorM = this.services.cachedMeshFloor( info.latitude, info.longitude, ); if (this.services.meshFloorPreferred() && !Number.isFinite(meshFloorM)) { if ( cockpitUiUpdateDue( nowMs, this.lastGroundProbeMs, COCKPIT_GROUND_PROBE_MS, ) ) { this.lastGroundProbeMs = nowMs; const eye = cameraOf(this.viewer).pose(); this.services.sampleMeshFloorCells(this.viewer, groundPoint, { sets: readEntityRecord(this.trackedEntity)?.groundSets?.() ?? [], viewerLat: eye.lat, viewerLon: eye.lon, }); } cockpitFloorM = this.services.cachedMeshFloor( info.latitude, info.longitude, ); if (!Number.isFinite(cockpitFloorM)) { if (!this.surfaceWaitStartedMs) this.surfaceWaitStartedMs = nowMs; if ( !cockpitSurfaceWaitExpired( nowMs, this.surfaceWaitStartedMs, COCKPIT_GROUND_WAIT_TIMEOUT_MS, ) ) { // Keep the already-safe map camera in place while the photoreal // surface under a parked aircraft is acquired. The bounded wait // prevents a permanently cold mesh cell from freezing cockpit. this.surfaceAcquiring = true; this.surfaceFallback = false; if ( cockpitUiUpdateDue( nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS, ) ) { this.lastHudUpdateMs = nowMs; this.updateHud(info, nowMs); } return; } this.surfaceAcquiring = false; this.surfaceFallback = true; } else { this.surfaceWaitStartedMs = 0; this.surfaceAcquiring = false; this.surfaceFallback = false; } } } else { this.surfaceWaitStartedMs = 0; this.surfaceAcquiring = false; this.surfaceFallback = false; } if ( !Number.isFinite(cockpitFloorM) && speedMps < 90 && Number.isFinite(targetCartographic?.height) ) { cockpitFloorM = targetCartographic.height - this.services.GROUND_FLOOR_LIFT_M; } // An application subject's anchor is where its provider puts it; only its // eye is kept out of the floor, below. if ( groundClamp && info.generic !== true && anchorCartographic && Number.isFinite(cockpitFloorM) ) { const minimumAnchorHeightM = cockpitGroundSafeHeight( anchorCartographic.height, cockpitFloorM, profile.minClearanceM - profile.upM, ); if (minimumAnchorHeightM !== anchorCartographic.height) { this.cockpitAnchor = fromRadians( anchorCartographic.lon, anchorCartographic.lat, minimumAnchorHeightM, ); } } // Rebuild the local frame at the stabilized anchor after advancing it. const enu = eastNorthUp(this.cockpitAnchor); const horizontal = normalize( frameVector(enu, vec(Math.sin(headingRad), Math.cos(headingRad), 0)), ); const forward = normalize( frameVector( enu, vec( Math.sin(viewHeadingRad) * Math.cos(pitchRad), Math.cos(viewHeadingRad) * Math.cos(pitchRad), Math.sin(pitchRad), ), ), ); const up = normalize( frameVector( enu, vec( -Math.sin(viewHeadingRad) * Math.sin(pitchRad), -Math.cos(viewHeadingRad) * Math.sin(pitchRad), Math.cos(pitchRad), ), ), ); let eye = add( add(this.cockpitAnchor, scale(horizontal, profile.forwardM)), scale(normalize(enu.origin), profile.upM), ); // Recheck at the final forward-offset camera coordinate because a taxiing // aircraft can cross into an adjacent coarse floor cell between updates. const cameraCartographic = toCartographicRadians(eye); if (groundClamp && cameraCartographic) { const cameraLat = toDegrees(cameraCartographic.lat); const cameraLon = toDegrees(cameraCartographic.lon); const cameraFloorM = this.services.cachedGroundFloor(cameraLat, cameraLon); if (Number.isFinite(cameraFloorM)) { cockpitFloorM = Math.max( cockpitFloorM ?? Number.NEGATIVE_INFINITY, cameraFloorM, ); } let safeHeightM = cockpitGroundSafeHeight( cameraCartographic.height, cockpitFloorM, profile.minClearanceM, ); // An application subject's eye rides its provider's smoothed height: // the clearance over the coarse, refining floor eases in and out // rather than jumping at each cell (easeCockpitLift). if (info.generic === true) { const hardM = cockpitGroundSafeHeight(cameraCartographic.height, cockpitFloorM, 0) - cameraCartographic.height; this.subjectLiftM = easeCockpitLift( this.subjectLiftM, safeHeightM - cameraCartographic.height, hardM, dtSec, ); safeHeightM = cameraCartographic.height + this.subjectLiftM; } if (safeHeightM !== cameraCartographic.height) { eye = fromRadians( cameraCartographic.lon, cameraCartographic.lat, safeHeightM, ); } } else if (info.generic === true) { // Inside a structure the floor holds the eye up no more: the lift it gave // goes at the rate it came (easeCockpitLift), never at once. this.subjectLiftM = easeCockpitLift(this.subjectLiftM, 0, 0, dtSec); if (cameraCartographic && this.subjectLiftM > 0) eye = fromRadians( cameraCartographic.lon, cameraCartographic.lat, cameraCartographic.height + this.subjectLiftM, ); } cameraOf(this.viewer).setView({ destination: eye, orientation: { direction: forward, up }, }); if (cockpitUiUpdateDue(nowMs, this.lastHudUpdateMs, COCKPIT_HUD_UPDATE_MS)) { this.lastHudUpdateMs = nowMs; this.updateHud(info, nowMs); } }