Files
gods-eye-view/src/ui/locationNavigation.js
T
German Khokhlov 35e70ec280 Draw the aircraft family, Wildlife Sightings and the Cockpit through the contract
The layers that still had one Cesium and one Navara implementation, or
drew on Cesium only, now draw through engine.movers, engine.lines and
engine.camera on both engines, and application code holds the engine
instead of guessing it from a viewer.

- Aircraft family: flights, military and local ADS-B share one display
  (src/layers/aircraft/render/display.js). The Cesium and Navara
  renderers are gone. Where they differed, the display follows Cesium:
  - attach and visibility tracking, live disableDepthTestDistance
    changes, the tracked glyph's distance scale, model ids that change,
    local ADS-B markers hidden until shown and its UAT ring as a point;
  - the trail head's hidden alpha is 0.45, the contract's
    depthFailAlpha scaled by the head's 0.9.
  The tracked glyph stays over the fleet, as on Navara. The movers
  contract reports readiness per model and reads model axes as the
  glTF's own on every engine. Cesium's follow takes any native target
  through a proxy entity in the ENU frame and mirrors its readout fields.
- Wildlife Sightings draws badges and the density glow as sprite sets
  and its privacy cells as line outlines (no fill yet). It takes clicks
  from engine.input and its card anchors to the engine's canvas and
  camera, so the layer is in both engines' catalogs again and a switch
  keeps the session's layer set.
- Cockpit: cockpitHost takes the engine only. The ridden aircraft is the
  engine follow's target, hidden through its sprite; only the Cesium
  Viewer's stock double-click is still routed around.
- About forty camera, navigation, share-link, HUD, voice, detection and
  layer-lifecycle callers take the engine. isGlobeEngine and
  engineFromViewer calls outside src/globe fall from 51 to 14.

The coupling baseline drops accordingly: layer renderer lines from
5239/12331 to 4546/11106 (Cesium/Navara), `viewer` lines from 2424 to
2209, Cesium-importing files from 69 to 66.
2026-11-07 02:34:34 +04:00

497 lines
16 KiB
JavaScript

import * as geo from '../geo/index.js';
import { t } from '../i18n/index.js';
import { createStateChannel } from '../app/stateChannel.js';
import { LocationControls } from './location.js';
/**
* Own destination selection, lookup, orbit and world-jump lifetime. The camera
* is the globe `engine`'s, and a world jump stops its follow
* (`engine.camera.following()`); `viewer` is optional and only clears a
* Cesium tracked entity the engine does not report.
*/
export class LocationNavigation {
constructor({
viewer = null,
engine = null,
placeSearch,
services,
elements,
navigation,
readCockpit,
operations,
}) {
Object.assign(
this,
{ viewer, engine, placeSearch, services, navigation, readCockpit },
elements,
operations,
);
this._disposed = false;
this._activeLocationId = null;
this._expandedCityId = null;
this._activePoiIndex = null;
this._currentTarget = null;
this._currentPoi = null;
this._searchedLocationLabel = null;
this._trafficTransitionTimer = null;
this._globeResetPromise = null;
this._cancelGlobeReset = null;
this._worldJumpActive = false;
this.orbitController = new services.OrbitController(engine);
this._orbitIndicator = null;
this._locationState = createStateChannel(
() => this._locationLookup?.getState() || null,
);
this._locationState.subscribe(
({ state, change }) => this._handleLocationSearchState(state, change),
{ emitCurrent: false },
);
}
get cockpitView() {
return this.readCockpit();
}
get _navigationGeneration() {
return this.navigation._navigationGeneration;
}
get _activeLocationSearchGeneration() {
return this.navigation._activeLocationSearchGeneration;
}
set _activeLocationSearchGeneration(value) {
this.navigation._activeLocationSearchGeneration = value;
}
setOrbit(enabled) {
const active = !!this.orbitController?.active;
if (typeof enabled === 'boolean' && enabled === active) {
return { ok: true, orbiting: active };
}
if (enabled === false) {
this._stopOrbit();
return { ok: true, orbiting: false };
}
if (!this._currentTarget) {
return {
ok: false,
orbiting: false,
error: 'No active landmark to orbit — fly to a landmark first',
};
}
this._toggleOrbit();
return { ok: true, orbiting: !!this.orbitController?.active };
}
subscribeLocationSearch(listener, options) {
return this._locationState.subscribe(listener, options);
}
_handleLocationSearchState(state, change) {
if (this._disposed || !change) return;
if (change.type === 'started') {
this._activeLocationSearchGeneration = change.generation;
this._setLocationSearchError(null);
} else if (change.type === 'found') {
this._searchedLocationLabel = state.destination.label || state.query;
this._setActiveLocation(null);
this._currentPoi = null;
this._collapsePOIRow();
this._updateLocationMiniStatus();
} else if (change.type === 'missing')
this._setLocationSearchError(
`${t('Location not found')}. ${t('Check the spelling and press Enter to search again.')}`,
);
else if (change.type === 'failed')
this._setLocationSearchError(
`${t('Search failed')}. ${t('Press Enter to try again.')}`,
);
else if (change.type === 'settled')
this._settleLocationSearchUi(change.generation, {
keepQuery: state.status === 'missing' || state.status === 'failed',
});
else if (
change.type === 'reset' &&
this._activeLocationSearchGeneration !== null
) {
this._settleLocationSearchUi(this._activeLocationSearchGeneration);
}
}
/** Show, or with null clear, the announced error under the search field. */
_setLocationSearchError(message) {
this._locationControls?.setSearchError(message);
}
_initLocationBar() {
const { CITY_POIS, searchAndFlyTo, LocationSearch } = this.services;
// An open field stays open in the new controls.
const searchExpanded = Boolean(this._locationControls?.searchExpanded);
this._locationControls?.destroy();
this._locationLookupUnsubscribe?.();
this._locationLookup?.destroy();
this._locationLookup = new LocationSearch({
input: this._locationSearch,
setSearching: (active) => this._locationControls?.setSearching(active),
begin: () => this._beginDeferredNavigation('location'),
isCurrent: (generation) =>
!this._disposed && generation === this._navigationGeneration,
beforeFly: (generation) => this._reassertNavigationHandoff(generation),
// The engine the lookup ends on: an answer that lands after a switch
// flies the globe shown then; one started with none attached is
// cancelled.
search: (query, options) =>
this.engine
? searchAndFlyTo(this.engine, query, {
placeSearch: this.placeSearch,
...options,
})
: Promise.resolve({ cancelled: true }),
onResult: (destination) => {
if (destination.outlineUnavailable)
this._showToast(t('Detailed outline unavailable'));
},
onError: (error) => console.error('[Search] Geocoding failed:', error),
});
this._locationControls = new LocationControls({
elements: {
search: this._locationSearch,
},
publish: (view) => this._publishLocation?.(view),
cities: CITY_POIS,
getExpandedCity: () => this._expandedCityId,
onCity: (id) => this._onCityPillClick(id),
onPoi: (id, index) => this._onPoiClick(id, index),
onSearch: (query) => this._locationLookup.run(query),
onSearchEdit: () => this._setLocationSearchError(null),
onReset: () => this.resetToGlobeView(),
searchExpanded,
});
// The new lookup's reset settles a replaced lookup's search through the
// new controls, so it subscribes once they are in place.
this._locationLookupUnsubscribe = this._locationLookup.subscribe(
({ initial, change }) => {
this._locationState.publish(initial ? { type: 'reset' } : change);
},
);
this._connectLocation?.(this._locationControls);
this._connectGlobeReset?.(this._locationControls);
}
_beginWorldJumpTransition() {
const { suspendDetection, trafficLayer } = this.services;
clearTimeout(this._trafficTransitionTimer);
this._worldJumpActive = true;
trafficLayer.beginWorldJump?.();
suspendDetection('intercity');
}
_endWorldJumpTransition() {
const { resumeDetection, trafficLayer } = this.services;
clearTimeout(this._trafficTransitionTimer);
this._worldJumpActive = false;
this._trafficTransitionTimer = null;
trafficLayer.endWorldJump?.();
resumeDetection();
this._updateTrafficSyncChip(true);
}
_flyWithTransition(cityChanged, flyAction) {
return this._runExplicitNavigation('location', () => {
if (!cityChanged) return flyAction({});
let completed = false;
const finalize = () => {
if (completed || this._disposed) return;
completed = true;
this._endWorldJumpTransition();
};
const result = flyAction({
onStart: () => this._beginWorldJumpTransition(),
onComplete: finalize,
});
this._trafficTransitionTimer = window.setTimeout(finalize, 5200);
return result;
});
}
_onCityPillClick(cityId) {
const { CITY_POIS, flyToPresetLocation } = this.services;
if (this._expandedCityId === cityId) {
// Same city clicked again — toggle collapse
this._collapsePOIRow();
return;
}
const isCityChanged =
this._activeLocationId && this._activeLocationId !== cityId;
const result = this._flyWithTransition(!!isCityChanged, (hooks) =>
flyToPresetLocation(this.engine, cityId, hooks),
);
if (result === false) return;
this._expandPOIRow(cityId);
this._setActiveLocation(cityId);
this._activePoiIndex = 0;
this._updatePoiHighlight();
// Track current target + POI for orbit
if (result) {
this._currentTarget = result.targetPosition;
this._currentPoi = CITY_POIS[cityId].pois[0];
}
this._updateLocationMiniStatus();
}
_onPoiClick(cityId, poiIndex) {
const { CITY_POIS, flyToPOI } = this.services;
const isCityChanged =
this._activeLocationId && this._activeLocationId !== cityId;
const result = this._flyWithTransition(!!isCityChanged, (hooks) =>
flyToPOI(this.engine, cityId, poiIndex, hooks),
);
if (result === false) return;
this._setActiveLocation(cityId);
this._activePoiIndex = poiIndex;
this._updatePoiHighlight();
// Track current target + POI for orbit
if (result) {
this._currentTarget = result.targetPosition;
this._currentPoi = CITY_POIS[cityId].pois[poiIndex];
}
this._updateLocationMiniStatus();
}
_expandPOIRow(cityId) {
const { CITY_POIS } = this.services;
if (!CITY_POIS[cityId]) return;
this._expandedCityId = cityId;
this._locationControls.showPois(cityId);
}
_collapsePOIRow() {
this._expandedCityId = null;
this._activePoiIndex = null;
this._locationControls.hidePois();
}
_updatePoiHighlight() {
this._locationControls.highlightPoi(this._activePoiIndex);
}
clearSearchedLocation() {
if (this._searchedLocationLabel === null) return;
this._searchedLocationLabel = null;
this._updateLocationMiniStatus();
}
_setActiveLocation(locationId) {
this._activeLocationId = locationId;
// A preset city is now what the camera is framed on, so any earlier
// free-text destination has been superseded. Clearing only on a real id
// leaves the search path's own _setActiveLocation(null) untouched.
if (locationId) this._searchedLocationLabel = null;
this._locationControls?.highlightCity(locationId);
this._updateLocationMiniStatus();
}
_updateLocationMiniStatus() {
const { CITY_POIS } = this.services;
this._locationControls?.renderStatus({
city: this._activeLocationId ? CITY_POIS[this._activeLocationId] : null,
currentPoi: this._currentPoi,
searchedLabel: this._searchedLocationLabel,
});
}
_initOrbit() {
this._locationControls?.showOrbit(false);
}
_toggleOrbit() {
if (!this._currentTarget) {
this._showToast(t('Fly to a POI first'));
return;
}
this.services.interruptGlobeRotation?.('orbit-intent');
const isActive = this.orbitController.toggle(this._currentTarget, {
radius: this._currentPoi?.alt || 500,
pitch: this._currentPoi?.pitch || -30,
});
this._locationControls?.showOrbit(isActive);
}
_stopOrbit() {
if (this.orbitController.active) {
this.orbitController.stop();
this._locationControls?.showOrbit(false);
}
}
resetToGlobeView() {
const {
GLOBE_VIEW,
flyToGlobeView,
interruptCameraMotion,
flightsLayer,
militaryFlightsLayer,
satellitesLayer,
aisLiveVesselsLayer,
militaryAwarenessLayer,
rocketLaunchesLayer,
} = this.services;
// Between two globe engines there is no camera to reset: nothing moves
// and no navigation is stamped.
if (this._disposed || !this.engine)
return Promise.resolve({
ok: false,
action: 'zoom_to_globe',
cancelled: true,
});
if (this._globeResetPromise) return this._globeResetPromise;
this._stampNavigation();
interruptCameraMotion('reset-globe');
this._stopOrbit();
this.cockpitView?.exit({ restoreTracking: false });
try {
// A layer an engine leaves out (military awareness on Navara) has no
// controls: release the trackers it would release, below.
if (typeof militaryAwarenessLayer?.releaseCameraOwnership !== 'function')
throw new Error('no military awareness controls');
militaryAwarenessLayer.releaseCameraOwnership?.({ origin: 'tool' });
} catch {
// Keep reset available if Context has not initialized completely.
try {
flightsLayer.stopTracking?.({ origin: 'tool' });
} catch {
/* best-effort release */
}
try {
militaryFlightsLayer.stopTracking?.({ origin: 'tool' });
} catch {
/* best-effort release */
}
try {
aisLiveVesselsLayer.clearSelection?.();
} catch {
/* best-effort release */
}
}
try {
satellitesLayer.stopTracking?.({ origin: 'tool' });
} catch {
/* best-effort release */
}
try {
rocketLaunchesLayer.releaseCameraOwnership?.();
} catch {
/* best-effort release */
}
this.engine.camera.following()?.stop();
if (this.viewer) this.viewer.trackedEntity = undefined;
this.engine.camera.cancelFlight();
this.engine.camera.release();
this._beginWorldJumpTransition();
let resolveReset;
const resetPromise = new Promise((resolve) => {
resolveReset = resolve;
});
this._globeResetPromise = resetPromise;
let settled = false;
let timer = null;
const finish = (cancelled = false) => {
if (settled) return;
settled = true;
clearTimeout(timer);
this._endWorldJumpTransition();
const carto = this.engine.camera.pose().cartographic;
const result = {
ok: !cancelled,
action: 'zoom_to_globe',
cancelled,
heightKm: Math.round(GLOBE_VIEW.heightM / 1000),
centeredOn: {
latitude: Number(geo.math.toDegrees(carto.latitude).toFixed(2)),
longitude: Number(geo.math.toDegrees(carto.longitude).toFixed(2)),
},
};
this._publishGlobeResetting?.(false);
this._globeResetPromise = null;
this._cancelGlobeReset = null;
resolveReset(result);
};
this._cancelGlobeReset = () => finish(true);
timer = window.setTimeout(() => {
const height = this.engine.camera.height();
finish(
!Number.isFinite(height) ||
Math.abs(height - GLOBE_VIEW.heightM) > 1000,
);
}, 4200);
this._publishGlobeResetting?.(true);
const target = flyToGlobeView(this.engine, {
onComplete: () => finish(false),
onCancel: () => finish(true),
});
if (!target) finish(true);
return resetPromise;
}
/** Settle the search field once its lookup has (LocationControls.settleSearch). */
settleSearch(options) {
this._locationControls?.settleSearch(options);
}
/** Close the search field; with `ifOpen`, only when it is open. */
closeSearch({ ifOpen = false } = {}) {
const controls = this._locationControls;
if (ifOpen && !controls?.searchExpanded) return;
controls?.closeSearch();
}
/** Revoke callbacks and settle owned camera work before the viewer is released. */
/**
* Leave the globe (an engine switch): its reset flight, world-jump
* transition and orbit end; the search, its text and the readout stay.
*/
detachScene() {
if (!this._disposed) {
this._cancelGlobeReset?.();
this._cancelGlobeReset = null;
if (this._worldJumpActive) this._endWorldJumpTransition();
clearTimeout(this._trafficTransitionTimer);
this._trafficTransitionTimer = null;
this._stopOrbit();
}
this.orbitController?.attachEngine(null);
this.viewer = null;
this.engine = null;
}
/** Navigate on another globe (an engine switch). */
attachScene({ viewer = null, engine = null } = {}) {
if (this._disposed) return;
this.viewer = viewer;
this.engine = engine;
this.orbitController?.attachEngine(engine);
}
destroy() {
if (this._disposed) return;
this._disposed = true;
this._locationState.destroy();
this._locationLookupUnsubscribe?.();
this._locationLookupUnsubscribe = null;
this._locationLookup?.destroy();
this._locationControls?.destroy();
this._connectLocation?.(null);
this._connectGlobeReset?.(null);
this._publishLocation?.(null);
this._cancelGlobeReset?.();
this._cancelGlobeReset = null;
if (this._worldJumpActive) this._endWorldJumpTransition();
clearTimeout(this._trafficTransitionTimer);
this._trafficTransitionTimer = null;
this.orbitController?.stop();
}
}