mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
The camera port gains an optional followFrame() (capability followFrame): the frame the eye is placed in now, as a column-major 4x4 matrix to ECEF. Once a follow has framed the camera it is the follow's own frame (east-north-up, or the orbit frame an autodetect follow chose), under lookAt the target's east-north-up frame, otherwise the identity. setView places a world pose and keeps that frame. The Cesium port reads it from camera.transform, only when the capability is on; the stub from its own eye frame. A conformance check covers the world, lookAt and enu-follow frames, the offset in it, and setView keeping it. src/ui/shareFollow.js now reads the pose, the frame and the follow offset through the camera and frame ports: a shared offset is re-expressed in the follow's own frame as before, satellites included, and the eye is placed with setView at exact heading, pitch and roll, so a near-vertical view keeps its roll. placeFollowEye returns false on a camera that cannot say its frame. offsetFromHeadingPitchRange moves to src/geo/frames.js, shared with the stub.
424 lines
13 KiB
JavaScript
424 lines
13 KiB
JavaScript
/**
|
|
* @module render/cesium/camera
|
|
* @description The Cesium renderer's camera port over a Cesium camera:
|
|
* poses, views, flights, `lookAt`, events and command hooks, each mapped
|
|
* onto Cesium's own camera call, and the user's camera controls
|
|
* (`cameraControls.js`) on the scene's camera controller.
|
|
*/
|
|
import * as Cesium from 'cesium';
|
|
import { createCameraEvents } from '../camera/events.js';
|
|
import { listenerList, toCartesian, uncaught } from './common.js';
|
|
import { cameraFlightActive } from './internals.js';
|
|
import { createCesiumFollow } from './follow.js';
|
|
import { createCesiumControls } from './cameraControls.js';
|
|
import { cameraOf, findCamera, provideUnboundCamera } from '../rendererOf.js';
|
|
// Loads the factories an unbound viewer gets its credits, draw, frame and
|
|
// query ports from.
|
|
import './credits.js';
|
|
import './draw.js';
|
|
import './frame.js';
|
|
import './query.js';
|
|
|
|
/**
|
|
* `cameraOf` and `findCamera`, for code that already reaches Cesium:
|
|
* importing them from here loads the factory a viewer with no renderer
|
|
* bound gets its camera from.
|
|
*/
|
|
export { cameraOf, findCamera };
|
|
|
|
/** The contract's easings as Cesium's. */
|
|
export const EASINGS = Object.freeze({
|
|
linear: Cesium.EasingFunction.LINEAR_NONE,
|
|
quadraticInOut: Cesium.EasingFunction.QUADRATIC_IN_OUT,
|
|
cubicInOut: Cesium.EasingFunction.CUBIC_IN_OUT,
|
|
cubicOut: Cesium.EasingFunction.CUBIC_OUT,
|
|
quinticInOut: Cesium.EasingFunction.QUINTIC_IN_OUT,
|
|
sineInOut: Cesium.EasingFunction.SINUSOIDAL_IN_OUT,
|
|
});
|
|
|
|
/**
|
|
* The contract's moves and looks as Cesium camera method names, called by
|
|
* name: a caller's camera may come from another copy of Cesium.
|
|
*/
|
|
const MOVES = Object.freeze({
|
|
forward: 'moveForward',
|
|
back: 'moveBackward',
|
|
left: 'moveLeft',
|
|
right: 'moveRight',
|
|
up: 'moveUp',
|
|
down: 'moveDown',
|
|
});
|
|
const LOOKS = Object.freeze({
|
|
left: 'lookLeft',
|
|
right: 'lookRight',
|
|
up: 'lookUp',
|
|
down: 'lookDown',
|
|
});
|
|
|
|
/** A contract destination as Cesium's: a Cartesian3, or a Rectangle. */
|
|
export function toDestination(d) {
|
|
if ('rect' in d) {
|
|
const r = d.rect;
|
|
return Cesium.Rectangle.fromDegrees(r.west, r.south, r.east, r.north);
|
|
}
|
|
return toCartesian(d);
|
|
}
|
|
|
|
/**
|
|
* A contract orientation as Cesium's; omitted angles are heading 0, pitch
|
|
* straight down and roll 0, as the contract says.
|
|
*/
|
|
export function toOrientation(o = {}) {
|
|
if ('direction' in o)
|
|
return { direction: toCartesian(o.direction), up: toCartesian(o.up) };
|
|
return {
|
|
heading: o.heading ?? 0,
|
|
pitch: o.pitch ?? -Math.PI / 2,
|
|
roll: o.roll ?? 0,
|
|
};
|
|
}
|
|
|
|
/** The follow offset of a camera that cannot follow. */
|
|
const NO_FOLLOW_OFFSET = Object.freeze({ get: () => null, set() {} });
|
|
|
|
/**
|
|
* @param {{scene: object, camera: object, report: (error: unknown) => void,
|
|
* widget?: object, capabilities?: ReadonlySet<string>}} options `scene`
|
|
* gives `requestRender` and the `postUpdate` tick `changed` is measured
|
|
* on; `widget`, the Viewer or CesiumWidget, gives the entity tracking
|
|
* `follow` runs on (without it the camera cannot follow);
|
|
* `capabilities`, the renderer's, gates the optional members (a camera
|
|
* with none given has them all).
|
|
* @returns {{port: import('../contract/camera').CameraPort, dispose: () => void}}
|
|
*/
|
|
export function createCesiumCamera({
|
|
scene,
|
|
camera,
|
|
report,
|
|
widget,
|
|
capabilities,
|
|
}) {
|
|
const removers = [];
|
|
// Camera events: Cesium's own moveStart and moveEnd (500 ms after the
|
|
// last change, never while following), and `changed` measured per
|
|
// listener on every tick, where Cesium measures its single threshold.
|
|
const cameraEvents = createCameraEvents({
|
|
pose: () => cameraPort.pose(),
|
|
report,
|
|
});
|
|
removers.push(
|
|
scene.postUpdate.addEventListener(() => {
|
|
applyFov();
|
|
cameraEvents.stepChanged();
|
|
}),
|
|
camera.moveStart.addEventListener(() => cameraEvents.emit('moveStart')),
|
|
camera.moveEnd.addEventListener(() => cameraEvents.emit('moveEnd')),
|
|
);
|
|
|
|
const following = widget?.trackedEntityChanged
|
|
? createCesiumFollow({
|
|
widget,
|
|
scene,
|
|
camera,
|
|
onChanged: () => cameraEvents.emit('followChanged'),
|
|
})
|
|
: null;
|
|
|
|
const controlsPart = createCesiumControls({ scene });
|
|
|
|
// Camera commands: hooks run before each one, so an owner can yield.
|
|
const commandHooks = listenerList(report);
|
|
const command = (kind) => commandHooks.fire({ kind });
|
|
|
|
// 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
|
|
// that ends it. `flying` sees every Cesium flight; `flightEnd` comes for
|
|
// the flights this port started (the application's flights all move onto
|
|
// the port with the camera family).
|
|
let flight = null;
|
|
|
|
// A flight's end that Cesium raises inside one of this port's own calls
|
|
// waits until Cesium's call returns, still inside the port's call: Cesium
|
|
// runs a cancelled flight's callback before it lets go of that flight, so
|
|
// the callback would read `flying` wrong, and a flight it started would
|
|
// be let go of with the old one.
|
|
let inCesiumCall = 0;
|
|
const pendingEnds = [];
|
|
function cesiumCall(fn) {
|
|
inCesiumCall += 1;
|
|
try {
|
|
return fn();
|
|
} finally {
|
|
inCesiumCall -= 1;
|
|
if (inCesiumCall === 0)
|
|
for (const deliver of pendingEnds.splice(0)) deliver();
|
|
}
|
|
}
|
|
|
|
function startFlight(start, options) {
|
|
let resolve;
|
|
const done = new Promise((r) => (resolve = r));
|
|
let ended = false;
|
|
const handle = {
|
|
done,
|
|
cancel() {
|
|
if (flight === handle) cesiumCall(() => camera.cancelFlight());
|
|
},
|
|
};
|
|
const end = (outcome) => {
|
|
if (ended) return;
|
|
ended = true;
|
|
if (flight === handle) flight = null;
|
|
const deliver = () => {
|
|
const cb =
|
|
outcome === 'complete' ? options.onComplete : options.onCancel;
|
|
try {
|
|
cb?.();
|
|
} catch (error) {
|
|
report(error);
|
|
}
|
|
resolve(outcome);
|
|
cameraEvents.emit('flightEnd');
|
|
};
|
|
if (inCesiumCall) pendingEnds.push(deliver);
|
|
else deliver();
|
|
};
|
|
flight = handle;
|
|
cesiumCall(() =>
|
|
start({
|
|
complete: () => end('complete'),
|
|
cancel: () => end('cancelled'),
|
|
}),
|
|
);
|
|
// Cesium starts nothing mid scene-mode morph, and calls neither back.
|
|
if (!ended && !cameraFlightActive(camera)) end('cancelled');
|
|
scene.requestRender();
|
|
return handle;
|
|
}
|
|
|
|
/**
|
|
* The vertical field of view `setFov` asked for, held across resizes:
|
|
* Cesium's `fov` is the wider of the two angles (the horizontal one when
|
|
* the view is wider than tall), and it keeps that one when the aspect
|
|
* changes. Before the first resize, and on a frustum without a field of
|
|
* view, it waits.
|
|
*/
|
|
let heldFovy = null;
|
|
function applyFov() {
|
|
const frustum = camera.frustum;
|
|
const aspect = frustum?.aspectRatio;
|
|
if (heldFovy === null || !('fov' in frustum) || !(aspect > 0)) return;
|
|
const fov =
|
|
aspect > 1 ? 2 * Math.atan(Math.tan(heldFovy / 2) * aspect) : heldFovy;
|
|
if (frustum.fov !== fov) frustum.fov = fov;
|
|
}
|
|
|
|
const cameraPort = {
|
|
on: (event, cb, options) => cameraEvents.on(event, cb, options),
|
|
onCommand: (cb) => commandHooks.on(cb),
|
|
setView(spec) {
|
|
command('setView');
|
|
const d = spec.destination;
|
|
camera.setView({
|
|
...(d ? { destination: toDestination(d) } : {}),
|
|
orientation: toOrientation(spec.orientation),
|
|
});
|
|
scene.requestRender();
|
|
},
|
|
flyTo(destination, options = {}) {
|
|
command('flyTo');
|
|
return startFlight(
|
|
(callbacks) =>
|
|
camera.flyTo({
|
|
destination: toDestination(destination),
|
|
orientation: toOrientation(options.orientation),
|
|
duration: options.durationS,
|
|
easingFunction: options.easing && EASINGS[options.easing],
|
|
maximumHeight: options.maxHeight,
|
|
pitchAdjustHeight: options.pitchAdjustHeight,
|
|
endTransform:
|
|
options.endFrame === 'world'
|
|
? Cesium.Matrix4.IDENTITY
|
|
: undefined,
|
|
...callbacks,
|
|
}),
|
|
options,
|
|
);
|
|
},
|
|
flyToBounds(sphere, options = {}) {
|
|
command('flyToBounds');
|
|
const o = options.offset ?? {};
|
|
return startFlight(
|
|
(callbacks) =>
|
|
camera.flyToBoundingSphere(
|
|
new Cesium.BoundingSphere(
|
|
toCartesian(sphere.center),
|
|
sphere.radius,
|
|
),
|
|
{
|
|
offset: new Cesium.HeadingPitchRange(
|
|
o.heading ?? 0,
|
|
o.pitch ?? -Math.PI / 4,
|
|
o.range ?? 0,
|
|
),
|
|
duration: options.durationS,
|
|
easingFunction: options.easing && EASINGS[options.easing],
|
|
...callbacks,
|
|
},
|
|
),
|
|
options,
|
|
);
|
|
},
|
|
cancelFlight() {
|
|
command('cancelFlight');
|
|
cesiumCall(() => camera.cancelFlight());
|
|
},
|
|
get flying() {
|
|
return cameraFlightActive(camera);
|
|
},
|
|
lookAt(target, offset) {
|
|
command('lookAt');
|
|
camera.lookAt(
|
|
toCartesian(target),
|
|
new Cesium.HeadingPitchRange(
|
|
offset.heading,
|
|
offset.pitch,
|
|
offset.range,
|
|
),
|
|
);
|
|
scene.requestRender();
|
|
},
|
|
follow(target) {
|
|
if (!following)
|
|
throw new Error('This camera cannot follow: it has no entity tracking');
|
|
command('follow');
|
|
following.follow(target);
|
|
scene.requestRender();
|
|
},
|
|
get followed() {
|
|
return following?.followed ?? null;
|
|
},
|
|
get followFramed() {
|
|
return following?.followFramed ?? false;
|
|
},
|
|
followOffset: following?.followOffset ?? NO_FOLLOW_OFFSET,
|
|
controls: controlsPart.controls,
|
|
release() {
|
|
command('release');
|
|
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
|
|
scene.requestRender();
|
|
},
|
|
move(direction, metres) {
|
|
camera[MOVES[direction]](metres);
|
|
scene.requestRender();
|
|
},
|
|
look(direction, radians) {
|
|
camera[LOOKS[direction]](radians);
|
|
scene.requestRender();
|
|
},
|
|
rotateAround(axis, radians) {
|
|
camera.rotate(toCartesian(axis), radians);
|
|
scene.requestRender();
|
|
},
|
|
zoom(metres) {
|
|
// Cesium's zoom, not a move: outside 3D it changes the view's width.
|
|
if (metres < 0) camera.zoomOut(-metres);
|
|
else camera.zoomIn(metres);
|
|
scene.requestRender();
|
|
},
|
|
setFov({ vertical }) {
|
|
// Cesium would take a bad angle and draw a garbage projection.
|
|
if (!(vertical > 0 && vertical < Math.PI))
|
|
throw new RangeError(`no vertical field of view of ${vertical}`);
|
|
heldFovy = vertical;
|
|
applyFov();
|
|
scene.requestRender();
|
|
},
|
|
// The scene's own frame: ECEF in 3D, the only mode the app runs (Cesium's
|
|
// 2D and Columbus view frames are projected map coordinates).
|
|
matrices() {
|
|
return {
|
|
view: Float64Array.from(Cesium.Matrix4.toArray(camera.viewMatrix)),
|
|
projection: Float64Array.from(
|
|
Cesium.Matrix4.toArray(camera.frustum.projectionMatrix),
|
|
),
|
|
};
|
|
},
|
|
viewRectangle() {
|
|
const rect = camera.computeViewRectangle(Cesium.Ellipsoid.WGS84);
|
|
if (!rect) return null;
|
|
const deg = Cesium.Math.toDegrees;
|
|
return {
|
|
west: deg(rect.west),
|
|
south: deg(rect.south),
|
|
east: deg(rect.east),
|
|
north: deg(rect.north),
|
|
};
|
|
},
|
|
pose() {
|
|
const v = (c) => ({ x: c.x, y: c.y, z: c.z });
|
|
// Cesium has no cartographic position for an eye at the earth's
|
|
// centre; the pose then says so with NaN.
|
|
const carto = camera.positionCartographic ?? {
|
|
longitude: NaN,
|
|
latitude: NaN,
|
|
height: NaN,
|
|
};
|
|
return {
|
|
lon: Cesium.Math.toDegrees(carto.longitude),
|
|
lat: Cesium.Math.toDegrees(carto.latitude),
|
|
position: v(camera.positionWC),
|
|
direction: v(camera.directionWC),
|
|
up: v(camera.upWC),
|
|
right: v(camera.rightWC),
|
|
heading: camera.heading,
|
|
pitch: camera.pitch,
|
|
roll: camera.roll,
|
|
height: carto.height,
|
|
fovy: camera.frustum.fovy,
|
|
aspectRatio: camera.frustum.aspectRatio,
|
|
near: camera.frustum.near,
|
|
far: camera.frustum.far,
|
|
frameIsIdentity: Cesium.Matrix4.equals(
|
|
camera.transform,
|
|
Cesium.Matrix4.IDENTITY,
|
|
),
|
|
};
|
|
},
|
|
};
|
|
// Cesium keeps the eye in `camera.transform`: a tracked entity's frame, a
|
|
// `lookAt` target's, or the identity.
|
|
if (!capabilities || capabilities.has('followFrame'))
|
|
cameraPort.followFrame = () =>
|
|
Float64Array.from(Cesium.Matrix4.toArray(camera.transform));
|
|
|
|
return {
|
|
port: cameraPort,
|
|
dispose() {
|
|
following?.dispose();
|
|
controlsPart.dispose();
|
|
for (const off of removers.splice(0)) off();
|
|
cameraEvents.clear();
|
|
commandHooks.clear();
|
|
},
|
|
};
|
|
}
|
|
|
|
// A Cesium viewer with no renderer bound to it gets a
|
|
// camera port over its camera when code first asks `cameraOf` for one.
|
|
provideUnboundCamera((viewer) =>
|
|
// By shape, not `instanceof`: the viewer may come from another
|
|
// copy of Cesium.
|
|
typeof viewer.camera?.flyTo === 'function' &&
|
|
typeof viewer.camera.moveStart?.addEventListener === 'function' &&
|
|
typeof viewer.scene?.postUpdate?.addEventListener === 'function'
|
|
? createCesiumCamera({
|
|
scene: viewer.scene,
|
|
camera: viewer.camera,
|
|
report: uncaught,
|
|
widget: viewer,
|
|
})
|
|
: null,
|
|
);
|