mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 03:32:19 +00:00
Merge upstream main into feat/iss-3d-model
Main's renderer seam (#1760) keeps Cesium inside src/render/cesium/, so the ISS model now draws through the renderer contract: - issModel.js draws the station as an item of a draw-port `models` set (url, position, heading/pitch/roll from its flight axes, scale, minimum pixel size, display range), hands the near range over through the dots' `displayRange`, and reads the eye from the camera port. - issArticulation.js computes each joint's matrix as plain numbers and the Sun from geo/celestial, and hands them over by node name. - The contract's ModelItem gains `nodes`: transforms of a model's named glTF nodes, which the Cesium port writes once the model is ready and again only when they change; a dropped name gets its authored pose back. - issCommand.js asks the frame port for frames and zooms by shortening the camera port's follow offset. - A click on the model is told by its draw hit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
c737a354c4
1129 files changed
+150420
-46238
No files matched your search
Vendored
+394
@@ -0,0 +1,394 @@
|
||||
/**
|
||||
* The camera. It belongs to the renderer: the application asks for poses,
|
||||
* flights and follows, and the renderer reproduces the behaviour below
|
||||
* exactly.
|
||||
*
|
||||
* Behaviour the renderer keeps (the application depends on each one):
|
||||
* - Camera input is suspended during a flight, by a hold: a flight ending
|
||||
* gives back only its own hold, never another owner's.
|
||||
* - `lookAt` orbits the target (the user can still rotate and zoom about it);
|
||||
* `release` returns to the world frame.
|
||||
* - `changed` fires when the view has moved by more than the listener's own
|
||||
* `threshold` (`cameraChangeThreshold`; default 0.5, and 0.5 for every
|
||||
* listener without the capability) since it last fired, measured per
|
||||
* listener, without changing what any other listener is measured by:
|
||||
* heading and roll each by their change over π since they last fired; the
|
||||
* view by the larger of the direction's turn over half the vertical field
|
||||
* of view and the eye's travel over its height, since the view last
|
||||
* fired. A frame can fire it twice, once for each measure.
|
||||
* - `moveEnd` fires 500 ms after the last change of the eye, following or
|
||||
* not: a followed target that moves keeps the eye moving, and one that
|
||||
* stands still lets the move end.
|
||||
* - A flight's `onCancel` and `onComplete` run synchronously, inside the call
|
||||
* or frame that ends it.
|
||||
* - Axes follow the usual convention: heading clockwise from north, pitch
|
||||
* negative looking down, roll about the view direction; local frames are
|
||||
* east-north-up.
|
||||
*/
|
||||
import type {
|
||||
Ecef,
|
||||
GeoRect,
|
||||
HeadingPitchRange,
|
||||
HeadingPitchRoll,
|
||||
LonLat,
|
||||
Off,
|
||||
Position,
|
||||
Release,
|
||||
Sphere,
|
||||
Vec3,
|
||||
} from './common';
|
||||
import type { PointerEv, PointerEventType } from './input';
|
||||
import type { HeightOptions } from './query';
|
||||
|
||||
export interface CameraPose {
|
||||
lon: number;
|
||||
lat: number;
|
||||
/** Metres above the ellipsoid. */
|
||||
height: number;
|
||||
heading: number;
|
||||
pitch: number;
|
||||
roll: number;
|
||||
position: Ecef;
|
||||
direction: Vec3;
|
||||
up: Vec3;
|
||||
right: Vec3;
|
||||
/**
|
||||
* Vertical field of view, radians. `fovy` and `aspectRatio` describe a
|
||||
* centred perspective frustum. Where the renderer's frustum is off-centre or
|
||||
* orthographic, it reports the nearest centred one here and its exact
|
||||
* projection only in `matrices()`; code that culls or projects exactly
|
||||
* reads `matrices()`.
|
||||
*/
|
||||
fovy: number;
|
||||
aspectRatio: number;
|
||||
near: number;
|
||||
far: number;
|
||||
/** False while `lookAt` has the camera in a target's frame. */
|
||||
frameIsIdentity: boolean;
|
||||
}
|
||||
|
||||
export type Orientation =
|
||||
Partial<HeadingPitchRoll> | { direction: Vec3; up: Vec3 };
|
||||
|
||||
/**
|
||||
* A position, or a rectangle. For a rectangle the eye stands on the surface
|
||||
* normal at the geodesic midpoint of its central meridian (latitude 0 when it
|
||||
* spans nearly pole to pole), at the least distance that keeps on screen its
|
||||
* corners, its edge centres and, when it crosses the equator, its equator
|
||||
* points. The orientation is then resolved as for any position.
|
||||
*/
|
||||
export type Destination = Position | { rect: GeoRect };
|
||||
|
||||
/**
|
||||
* Omitted orientation angles are heading 0, pitch −π/2 (straight down) and
|
||||
* roll 0, not the current ones; an omitted destination keeps the position.
|
||||
*/
|
||||
export interface ViewSpec {
|
||||
destination?: Destination;
|
||||
orientation?: Orientation;
|
||||
}
|
||||
|
||||
export type Easing =
|
||||
| 'linear'
|
||||
| 'quadraticInOut'
|
||||
| 'cubicInOut'
|
||||
| 'cubicOut'
|
||||
| 'quadraticOut'
|
||||
| 'quinticInOut'
|
||||
| 'sineInOut';
|
||||
|
||||
/**
|
||||
* A flight's omitted orientation is the same as `setView`'s. Its omitted
|
||||
* duration is `min(3, ceil(distance / 1000 km) + 2)` seconds, the distance
|
||||
* measured from the eye's position in its current frame (the `lookAt` frame
|
||||
* when one is active). A flight with a duration of 0 or less, or one whose
|
||||
* eye (its position in its current frame, as above) already stands at the
|
||||
* destination with the destination's angles (to 1e-10, relative),
|
||||
* completes inside the call: it places the eye, runs `onComplete`, raises
|
||||
* `flightEnd` and resolves `done`, and no frame is needed. Starting a
|
||||
* flight cancels the one in progress.
|
||||
*
|
||||
* The path, at eased time `s` (0..1): longitude and latitude linear in `s`
|
||||
* the short way round; heading, pitch and roll linear in `s` the short way
|
||||
* round; height on an arc to `maxHeight` when both ends are below it,
|
||||
* otherwise linear. The reference traces (`conformance/goldens/camera.json`)
|
||||
* pin the arc and the omitted `maxHeight`.
|
||||
*/
|
||||
export interface FlightOptions {
|
||||
orientation?: Orientation;
|
||||
durationS?: number;
|
||||
/**
|
||||
* Omitted: `cubicOut` when descending from above 11.5 km, otherwise
|
||||
* `quinticInOut`.
|
||||
*/
|
||||
easing?: Easing;
|
||||
/** Top of the height arc, metres. Omitted: a fifth of what fits both ends on screen. */
|
||||
maxHeight?: number;
|
||||
/** When the arc tops this height, pitch turns straight down mid-flight. */
|
||||
pitchAdjustHeight?: number;
|
||||
/** End in the world frame even when a target frame is active. */
|
||||
endFrame?: 'world';
|
||||
onComplete?: () => void;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
export interface Flight {
|
||||
done: Promise<'complete' | 'cancelled'>;
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
/** Something the camera follows; the application owns it and the renderer reads it each frame. */
|
||||
export interface FollowTarget {
|
||||
/** Stable key, e.g. `'flights:a1b2c3'`. */
|
||||
key: string;
|
||||
/** Where the target is at scene time `t` (epoch ms), or null when unknown. */
|
||||
position(t: number): Ecef | null;
|
||||
/** Where it is drawn, when that differs from `position` (a lifted icon). */
|
||||
visualPosition?(t: number): Ecef | null;
|
||||
/**
|
||||
* The drawn item this target is, when it is one. Where the renderer moves
|
||||
* items itself (`motionSegments`), it follows where it draws the item, so the
|
||||
* eye and the icon never part; `position` stays the answer elsewhere.
|
||||
*/
|
||||
item?: { set: string; id: string };
|
||||
/**
|
||||
* `enu`: offset in the target's east-north-up frame;
|
||||
* `autodetect`: an orbit frame from its motion, north-up when still
|
||||
* (`followAutodetect`).
|
||||
*/
|
||||
frame: 'enu' | 'autodetect';
|
||||
/** Offset of the eye from the target, metres in `frame`. */
|
||||
viewFrom: Vec3 | ((t: number) => Vec3);
|
||||
minRange?: number;
|
||||
boundingRadius?: number;
|
||||
/**
|
||||
* Seconds of wall time the first framing takes; without it the eye is
|
||||
* placed at `viewFrom` on the first frame. With it the eye stays in the
|
||||
* target's frame from the first frame (riding along with the target) and
|
||||
* moves from where it stood to the framing, both its offset and its view
|
||||
* turning, eased (`render/camera/followTransition.js`, the one rule every
|
||||
* renderer follows); `followFramed` turns true on arrival. A `viewFrom`
|
||||
* along the eye's own view at its own range keeps the view and the range
|
||||
* throughout, so the target slides to the centre.
|
||||
*/
|
||||
transitionS?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A camera command, as an ownership hook sees it before it runs. An owner
|
||||
* that issues commands itself (a ground guard) recognises its own by
|
||||
* issuing them inside its own call; any other command is someone else's.
|
||||
*/
|
||||
export interface CameraCommand {
|
||||
kind:
|
||||
| 'setView'
|
||||
| 'flyTo'
|
||||
| 'flyToBounds'
|
||||
| 'lookAt'
|
||||
| 'release'
|
||||
| 'follow'
|
||||
| 'cancelFlight';
|
||||
}
|
||||
|
||||
export interface CameraControls {
|
||||
/** False while any hold is out. */
|
||||
readonly enabled: boolean;
|
||||
/** Suspend user camera input until released. Holds are counted. */
|
||||
suspend(reason: string): Release;
|
||||
enableTilt: boolean;
|
||||
enableRotate: boolean;
|
||||
enableZoom: boolean;
|
||||
minDistance: number;
|
||||
maxDistance: number;
|
||||
/**
|
||||
* How long a motion the user lets go of coasts: seconds for its speed to
|
||||
* fall to 1/e. `drag` is moving the globe under the pointer and tilting
|
||||
* (one motion in the default renderer), `zoom` is zooming; 0 stops at
|
||||
* once. Set the whole object to change it.
|
||||
*/
|
||||
coast: { drag: number; zoom: number };
|
||||
/** What the eye cannot pass below. */
|
||||
collision: 'none' | 'terrain' | 'tiles' | 'both';
|
||||
zoomFactor: number;
|
||||
/** Pitch the user may tilt between, radians (−π/2 straight down). */
|
||||
pitchRange: [min: number, max: number];
|
||||
/**
|
||||
* Input bindings that zoom. `ctrlWheel`: Ctrl+wheel, and a trackpad
|
||||
* pinch (which browsers send as Ctrl+wheel), zoom the globe rather than
|
||||
* 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 =
|
||||
'changed' | 'moveStart' | 'moveEnd' | 'followChanged' | 'flightEnd';
|
||||
|
||||
export interface CameraPort {
|
||||
pose(): CameraPose;
|
||||
/**
|
||||
* Place the eye. A position with a `{direction, up}` orientation is placed
|
||||
* exactly as given (`up` made square to `direction`), never rounded
|
||||
* through heading, pitch and roll: the application's step moves (pans, turns, the
|
||||
* globe turned under the eye, zooms; `geo/eyeMoves`) are such views,
|
||||
* sent many times over.
|
||||
*/
|
||||
setView(view: ViewSpec): void;
|
||||
/**
|
||||
* Hold the vertical field of view, across resizes, until `null` gives the
|
||||
* field of view back to the renderer: it is then as it was before the
|
||||
* first hold, and follows the view's shape as the renderer's own does.
|
||||
*/
|
||||
setFov(fov: { vertical: number } | null): void;
|
||||
/**
|
||||
* The geodetic rectangle in view: the bounds of the canvas corners on the
|
||||
* ellipsoid, a corner that misses it taken where the horizon is, and the
|
||||
* full longitude span to the pole when the view goes over one. The whole
|
||||
* globe when fewer than two corners land; null only when the globe is
|
||||
* wholly outside the view.
|
||||
*/
|
||||
viewRectangle(): GeoRect | null;
|
||||
flyTo(destination: Destination, options?: FlightOptions): Flight;
|
||||
/**
|
||||
* Fly to look at a sphere from `offset` in its east-north-up frame
|
||||
* (default heading 0, pitch −π/4; a range of 0 fits the sphere in view).
|
||||
*/
|
||||
flyToBounds(
|
||||
sphere: Sphere,
|
||||
options?: { offset?: HeadingPitchRange } & Pick<
|
||||
FlightOptions,
|
||||
'durationS' | 'easing' | 'onComplete' | 'onCancel'
|
||||
>,
|
||||
): Flight;
|
||||
cancelFlight(): void;
|
||||
readonly flying: boolean;
|
||||
/** Orbit `target` at `offset`; user input orbits it too. */
|
||||
lookAt(target: Ecef, offset: HeadingPitchRange): void;
|
||||
/** Leave `lookAt` for the world frame. */
|
||||
release(): void;
|
||||
/**
|
||||
* Follow `target`, or stop following with null; `followChanged` fires
|
||||
* whenever `followed` changes, and only then.
|
||||
*/
|
||||
follow(target: FollowTarget | null): void;
|
||||
readonly followed: FollowTarget | null;
|
||||
/** Whether the follow has placed its first frame. */
|
||||
readonly followFramed: boolean;
|
||||
/** The eye's offset from the followed target, in its frame. */
|
||||
readonly followOffset: {
|
||||
get(): Vec3 | null;
|
||||
set(offset: Vec3): void;
|
||||
};
|
||||
/**
|
||||
* `followFrame`: the frame the eye is placed in now, as a column-major
|
||||
* 4×4 matrix from that frame to ECEF (a rigid frame: unit axes, then the
|
||||
* origin). Once a follow has framed the camera (`followFramed`) it is the
|
||||
* follow's frame, whose origin is the target and in which `followOffset`
|
||||
* is the eye: east-north-up for an `enu` follow, the renderer's own orbit
|
||||
* frame for `autodetect`; until then it is whatever frame the eye was in
|
||||
* before. Under `lookAt` it is the target's east-north-up frame; in the
|
||||
* world frame, the identity. A follow's frame moves with its target, so a
|
||||
* reading is valid only for the tick it is read in. `setView` places a
|
||||
* world pose and keeps this frame, so code can re-express an offset in
|
||||
* the follow's own frame, whichever frame that is, and place the eye there.
|
||||
* Read-only, handed again while it holds, as `matrices()` are.
|
||||
*/
|
||||
followFrame?(): Float64Array;
|
||||
readonly controls: CameraControls;
|
||||
/**
|
||||
* `threshold` (`cameraChangeThreshold`): the fraction of change, as the
|
||||
* header measures it, that fires this `changed` listener; ignored for the
|
||||
* other events, and without the capability (every listener then fires at
|
||||
* 0.5).
|
||||
*/
|
||||
on(event: CameraEvent, cb: () => void, options?: { threshold?: number }): Off;
|
||||
/** Runs before each camera command, so an owner can yield to another. */
|
||||
onCommand(cb: (command: CameraCommand) => void): Off;
|
||||
/**
|
||||
* Column-major, right-handed: `view` takes ECEF to eye space (absolute,
|
||||
* not eye-relative); `projection` takes eye space to clip space with depth
|
||||
* in [-1, 1]. A renderer with an infinite far plane returns the
|
||||
* infinite-far form, and `pose().far` is `Infinity`. Read-only: a
|
||||
* renderer may hand the same arrays again while they hold, and hands new
|
||||
* ones once they change (one kept from an earlier frame stays as it was).
|
||||
*/
|
||||
matrices(): {
|
||||
readonly view: Float64Array;
|
||||
readonly projection: Float64Array;
|
||||
};
|
||||
}
|
||||
|
||||
/** A camera controller's frame tick: the loop's clock and the scene time. */
|
||||
export interface CameraTick {
|
||||
/** The loop's clock, ms, on the `performance.now()` timeline. */
|
||||
now: number;
|
||||
/** Scene time, epoch ms. */
|
||||
time: number;
|
||||
}
|
||||
|
||||
/** The eye a camera controller writes, in ECEF; `fovy` vertical, radians. */
|
||||
export interface ControllerEye {
|
||||
position: Ecef;
|
||||
direction: Ecef;
|
||||
up: Ecef;
|
||||
right: Ecef;
|
||||
fovy: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera a renderer hands a camera controller: it reads and writes the
|
||||
* eye exactly, says the canvas's CSS size, and lends the query, draw and
|
||||
* frame ports' members the controller needs.
|
||||
*/
|
||||
export interface NativeCamera {
|
||||
pose(): {
|
||||
position: Ecef;
|
||||
direction: Ecef;
|
||||
up: Ecef;
|
||||
near: number;
|
||||
far: number;
|
||||
};
|
||||
setPose(eye: ControllerEye): void;
|
||||
viewport(): { width: number; height: number };
|
||||
sampleHeightNow?(point: LonLat, options?: HeightOptions): number | null;
|
||||
pickPosition?(x: number, y: number): Ecef | null;
|
||||
/** Where the draw port draws an item it moves itself. */
|
||||
itemPosition?(
|
||||
item: { set: string; id: string | number },
|
||||
aheadMs?: number,
|
||||
): Ecef | null;
|
||||
requestRender?(reason: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A camera controller, handed to a renderer in place of its own camera:
|
||||
* given the native camera, the
|
||||
* input port's pointer events and the page's keys, it makes the camera port.
|
||||
* The renderer runs `frame.beforeUpdate` before its `preUpdate` listeners
|
||||
* and `frame.afterUpdate` after them, each tick, drawn or not.
|
||||
*/
|
||||
export type CameraControllerFactory = (options: {
|
||||
native: NativeCamera;
|
||||
input?: {
|
||||
on(type: PointerEventType, cb: (event: PointerEv) => void): Off;
|
||||
};
|
||||
report?: (error: unknown) => void;
|
||||
keyTarget?: EventTarget;
|
||||
thresholds?: boolean;
|
||||
}) => {
|
||||
port: CameraPort;
|
||||
frame: {
|
||||
beforeUpdate(tick: CameraTick): void;
|
||||
afterUpdate(tick: CameraTick): void;
|
||||
};
|
||||
destroy(): void;
|
||||
};
|
||||
Vendored
+217
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* Shared value types of the renderer contract.
|
||||
*
|
||||
* Only plain numbers, strings and typed arrays cross the contract: no engine
|
||||
* object ever does. Positions are f64 Earth-centred, Earth-fixed metres
|
||||
* (`Ecef`) or geodetic degrees and metres (`LonLatH`). Angles are radians
|
||||
* unless a name says degrees. Times are epoch milliseconds. Screen positions
|
||||
* are CSS pixels from the top left of the renderer's canvas.
|
||||
*/
|
||||
|
||||
/** Earth-centred, Earth-fixed position in metres (WGS84). */
|
||||
export interface Ecef {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
/** A direction or offset in metres; the frame is stated where it is used. */
|
||||
export interface Vec3 {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
/** Geodetic position: degrees, and metres above the WGS84 ellipsoid. */
|
||||
export interface LonLatH {
|
||||
lon: number;
|
||||
lat: number;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
/** Geodetic position without a height. */
|
||||
export interface LonLat {
|
||||
lon: number;
|
||||
lat: number;
|
||||
}
|
||||
|
||||
/** Either position form. A value with `lon` and `lat` is geodetic. */
|
||||
export type Position = Ecef | LonLatH;
|
||||
|
||||
/** CSS pixels from the canvas's top left. */
|
||||
export interface ScreenXY {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
/** A screen rectangle in CSS pixels. */
|
||||
export interface ScreenRect {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** A geodetic rectangle in degrees. */
|
||||
export interface GeoRect {
|
||||
west: number;
|
||||
south: number;
|
||||
east: number;
|
||||
north: number;
|
||||
}
|
||||
|
||||
/** A ray in ECEF metres; `direction` is a unit vector. */
|
||||
export interface Ray {
|
||||
origin: Ecef;
|
||||
direction: Vec3;
|
||||
}
|
||||
|
||||
/** A bounding sphere. */
|
||||
export interface Sphere {
|
||||
center: Ecef;
|
||||
radius: number;
|
||||
}
|
||||
|
||||
export interface HeadingPitchRoll {
|
||||
heading: number;
|
||||
pitch: number;
|
||||
roll: number;
|
||||
}
|
||||
|
||||
export interface HeadingPitchRange {
|
||||
heading: number;
|
||||
pitch: number;
|
||||
range: number;
|
||||
}
|
||||
|
||||
/** A quaternion `(x, y, z, w)`, unit length. */
|
||||
export interface Quaternion {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
w: number;
|
||||
}
|
||||
|
||||
/** A CSS colour string, or linear `[r, g, b, a]` in 0..1 (`a` defaults to 1). */
|
||||
export type Color = string | readonly [number, number, number, number?];
|
||||
|
||||
/**
|
||||
* A distance curve: `nearValue` at `near` metres from the eye, `farValue`
|
||||
* at `far`, linear in between and clamped outside.
|
||||
*/
|
||||
export interface NearFar {
|
||||
near: number;
|
||||
nearValue: number;
|
||||
far: number;
|
||||
farValue: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribes. Calling it twice is harmless.
|
||||
*
|
||||
* Every `on(...)` in the contract keeps these rules: listeners run in the
|
||||
* order they subscribed; one removed while an event is being delivered does
|
||||
* not run for it if it has not yet; one added during delivery first runs for
|
||||
* the next event; a listener that throws is reported (`Renderer` `error`,
|
||||
* or the platform's `reportError` when nothing listens for errors) and the
|
||||
* others, and the frame, still run.
|
||||
*/
|
||||
export type Off = () => void;
|
||||
|
||||
/** Gives back a hold. Calling it twice is harmless. */
|
||||
export type Release = () => void;
|
||||
|
||||
/**
|
||||
* A handle on something the renderer draws. Once disposed, and once the
|
||||
* renderer is destroyed, it does nothing: its methods neither draw nor
|
||||
* throw, and a set or field asked for after destroy is such a handle.
|
||||
* Disposing it again is harmless.
|
||||
*/
|
||||
export interface Handle {
|
||||
show: boolean;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/** Opaque data the application attaches to a drawn item and gets back on a pick. */
|
||||
export type Meta = unknown;
|
||||
|
||||
/**
|
||||
* Optional features. A renderer lists the ones it has in
|
||||
* `Renderer.capabilities`. A member's documentation names the capability
|
||||
* it depends on, in backticks, first:
|
||||
* - on an optional member (`?`), the member exists only with the capability;
|
||||
* - on a required member, the member always exists, and without the
|
||||
* capability it answers null, an empty list or a status saying so (a
|
||||
* query asked for depth on a renderer without `pickPosition` returns null).
|
||||
* Options guarded by a capability are ignored without it. Quality settings
|
||||
* are not capabilities: `QualityPort.knobs()` lists the ones a renderer has.
|
||||
*/
|
||||
export type Capability =
|
||||
/** Google photorealistic 3D tiles as the base. */
|
||||
| 'photoreal'
|
||||
/** A vector basemap (`BaseSpec.vector`), with its own labels. */
|
||||
| 'vectorBase'
|
||||
/** Heights from the finest data available, not only what is drawn. */
|
||||
| 'finestHeights'
|
||||
/** Height terrain under the globe. */
|
||||
| 'terrain'
|
||||
/** Atmosphere scattering applied to drawn models. */
|
||||
| 'modelAtmosphere'
|
||||
/** Clouds, fog, haze, rain and snow around the view (`globe.weather`). */
|
||||
| 'weather'
|
||||
/** Imagery draped onto 3D tiles as well as the globe. */
|
||||
| 'imageryOnTiles'
|
||||
/** A screen-split comparison between imagery layers. */
|
||||
| 'splitSwipe'
|
||||
/** Timed imagery frames with hidden prefetch. */
|
||||
| 'imageryFrames'
|
||||
/** Wind-relief and similar shading of the globe surface. */
|
||||
| 'surfaceShading'
|
||||
/** A version of what surface heights answer against (`globe.surfaceVersion`). */
|
||||
| 'surfaceIdentity'
|
||||
/** Main-thread tile hooks: `tileTransform`, `admit` and `canvas` imagery. */
|
||||
| 'imageHooks'
|
||||
/** A screen-space sector modulation pass (a sweeping sonar band). */
|
||||
| 'screenModulation'
|
||||
/** GPU frame timing through timer queries. */
|
||||
| '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. */
|
||||
| 'rayCast'
|
||||
/** Columnar draw-set updates with dirty ranges. */
|
||||
| 'columns'
|
||||
/** Icon motion segments evaluated on the renderer's clock. */
|
||||
| 'motionSegments'
|
||||
/** glTF models. */
|
||||
| 'models'
|
||||
/** Image, video and canvas planes. */
|
||||
| 'quads'
|
||||
/** Custom meshes in a local east-north-up frame. */
|
||||
| 'meshes'
|
||||
/** Wind streamlines and raised raster shells. */
|
||||
| 'fields'
|
||||
/** Rate-limited course easing (`IconItem.courseGlide`). */
|
||||
| 'courseGlide'
|
||||
/** Screen-space clustering of icons. */
|
||||
| 'cluster'
|
||||
/** Post-processing styles. */
|
||||
| 'styles'
|
||||
/** A bloom pass. */
|
||||
| 'bloom'
|
||||
/** A sharpen pass. */
|
||||
| 'sharpen'
|
||||
/** Following with an automatically chosen frame (orbit or north-up). */
|
||||
| 'followAutodetect'
|
||||
/** Reading back whether the globe surface is shown (`globe.isGlobeVisible`). */
|
||||
| 'globeVisibility'
|
||||
/** Reading the frame the eye is placed in (`camera.followFrame`). */
|
||||
| 'followFrame'
|
||||
/** A `threshold` per `changed` listener (`camera.on`). */
|
||||
| 'cameraChangeThreshold';
|
||||
@@ -0,0 +1,260 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import ts from 'typescript';
|
||||
import {
|
||||
CAPABILITIES,
|
||||
CONTRACT_VERSION,
|
||||
FRAME_STEPS,
|
||||
PORTS,
|
||||
ROLES,
|
||||
roleOf,
|
||||
QUALITY_KEYS,
|
||||
checkPortShape,
|
||||
checkRendererShape,
|
||||
} from './index.js';
|
||||
|
||||
const DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
const INDEX = path.join(DIR, 'index.d.ts');
|
||||
|
||||
const program = ts.createProgram([INDEX], {
|
||||
strict: true,
|
||||
noEmit: true,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts'],
|
||||
skipLibCheck: false,
|
||||
types: [],
|
||||
});
|
||||
const checker = program.getTypeChecker();
|
||||
const contractFiles = program
|
||||
.getSourceFiles()
|
||||
.filter((file) => path.dirname(file.fileName) === DIR);
|
||||
|
||||
/** The named interface or type alias declared in the contract files. */
|
||||
function declared(name) {
|
||||
for (const file of contractFiles)
|
||||
for (const statement of file.statements)
|
||||
if (
|
||||
(ts.isInterfaceDeclaration(statement) ||
|
||||
ts.isTypeAliasDeclaration(statement)) &&
|
||||
statement.name.text === name
|
||||
)
|
||||
return statement;
|
||||
throw new Error(`${name} is not declared in the contract`);
|
||||
}
|
||||
|
||||
const PORT_INTERFACES = {
|
||||
renderer: 'Renderer',
|
||||
frame: 'FramePort',
|
||||
globe: 'GlobePort',
|
||||
draw: 'DrawPort',
|
||||
camera: 'CameraPort',
|
||||
query: 'QueryPort',
|
||||
input: 'InputPort',
|
||||
effects: 'EffectsPort',
|
||||
credits: 'CreditsPort',
|
||||
quality: 'QualityPort',
|
||||
drawSet: 'DrawSet',
|
||||
imageryLayer: 'ImageryLayer',
|
||||
flight: 'Flight',
|
||||
lease: 'Lease',
|
||||
};
|
||||
const PORT_NAMES = new Set(Object.values(PORT_INTERFACES));
|
||||
|
||||
/** Whether a property's type is one of the contract's own object shapes to list member by member. */
|
||||
function nestedShape(type) {
|
||||
if (type.isUnion() || type.getCallSignatures().length) return null;
|
||||
const symbol = type.aliasSymbol ?? type.getSymbol();
|
||||
const declaration = symbol?.declarations?.[0];
|
||||
if (!declaration) return null;
|
||||
const inContract = path.dirname(declaration.getSourceFile().fileName) === DIR;
|
||||
if (!inContract) return null;
|
||||
if (ts.isTypeLiteralNode(declaration)) return type;
|
||||
if (ts.isInterfaceDeclaration(declaration))
|
||||
return PORT_NAMES.has(declaration.name.text) ? null : type;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `[member, optional]` for every member, nested shapes dotted; a member of
|
||||
* an optional shape is as optional as the shape.
|
||||
*/
|
||||
function members(type, prefix = '', inOptional = false) {
|
||||
const out = [];
|
||||
for (const property of checker.getPropertiesOfType(type)) {
|
||||
const name = `${prefix}${property.name}`;
|
||||
const optional =
|
||||
inOptional || Boolean(property.flags & ts.SymbolFlags.Optional);
|
||||
out.push([name, optional]);
|
||||
const declaration = property.valueDeclaration ?? property.declarations?.[0];
|
||||
const declared = checker.getTypeOfSymbolAtLocation(property, declaration);
|
||||
// An optional member's shape, without the `undefined` its `?` adds.
|
||||
const propertyType =
|
||||
property.flags & ts.SymbolFlags.Optional
|
||||
? checker.getNonNullableType(declared)
|
||||
: declared;
|
||||
const nested = nestedShape(propertyType);
|
||||
if (nested) out.push(...members(nested, `${name}.`, optional));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function unionLiterals(name) {
|
||||
const type = checker.getTypeAtLocation(declared(name).name);
|
||||
return (type.isUnion() ? type.types : [type]).map((t) => t.value).sort();
|
||||
}
|
||||
|
||||
test('the contract type-checks under strict TypeScript', () => {
|
||||
const diagnostics = ts.getPreEmitDiagnostics(program).map((d) => {
|
||||
const where = d.file
|
||||
? `${path.relative(DIR, d.file.fileName)}:${d.file.getLineAndCharacterOfPosition(d.start).line + 1}`
|
||||
: '';
|
||||
return `${where} ${ts.flattenDiagnosticMessageText(d.messageText, '\n')}`;
|
||||
});
|
||||
assert.deepEqual(diagnostics, []);
|
||||
});
|
||||
|
||||
test('PORTS lists every member of every port, required exactly when the type requires it', () => {
|
||||
for (const [port, interfaceName] of Object.entries(PORT_INTERFACES)) {
|
||||
const type = checker.getTypeAtLocation(declared(interfaceName).name);
|
||||
const typed = Object.fromEntries(members(type));
|
||||
const described = PORTS[port];
|
||||
assert.deepEqual(
|
||||
Object.keys(described).sort(),
|
||||
Object.keys(typed).sort(),
|
||||
`${port} members`,
|
||||
);
|
||||
for (const [member, capability] of Object.entries(described))
|
||||
assert.equal(
|
||||
capability !== null,
|
||||
typed[member],
|
||||
`${port}.${member}: optional in the type exactly when a capability adds it`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('every member of every port has one role, and each role names real members', () => {
|
||||
const ids = ROLES.map((r) => r.id);
|
||||
assert.equal(new Set(ids).size, ids.length);
|
||||
// No entry is claimed by two roles, so the most specific entry is never a tie.
|
||||
const entries = ROLES.flatMap((r) => r.members);
|
||||
assert.equal(new Set(entries).size, entries.length, 'an entry in two roles');
|
||||
for (const [port, members] of Object.entries(PORTS))
|
||||
for (const member of Object.keys(members))
|
||||
assert.ok(
|
||||
ids.includes(roleOf(port, member)),
|
||||
`${port}.${member} has no role`,
|
||||
);
|
||||
// An entry is a port, or a member (or a prefix of dotted members) of one.
|
||||
for (const role of ROLES)
|
||||
for (const entry of role.members) {
|
||||
const [port, ...rest] = entry.split('.');
|
||||
const member = rest.join('.');
|
||||
assert.ok(PORTS[port], `${role.id}: ${entry} names no port`);
|
||||
if (member)
|
||||
assert.ok(
|
||||
Object.keys(PORTS[port]).some(
|
||||
(m) => m === member || m.startsWith(`${member}.`),
|
||||
),
|
||||
`${role.id}: ${entry} names no member`,
|
||||
);
|
||||
}
|
||||
// The most specific entry wins.
|
||||
assert.equal(roleOf('globe', 'setBase'), 'surface');
|
||||
assert.equal(roleOf('globe', 'sky.set'), 'look');
|
||||
assert.equal(roleOf('globe', 'setSurfaceShading'), 'look');
|
||||
assert.equal(roleOf('nowhere', 'x'), undefined);
|
||||
assert.equal(roleOf('globe', 'bogus'), undefined);
|
||||
assert.equal(roleOf('globe'), 'surface');
|
||||
assert.equal(roleOf('imageryLayer', 'lit'), 'look');
|
||||
});
|
||||
|
||||
test('the capability and frame-step lists are the types’ own', () => {
|
||||
assert.deepEqual([...CAPABILITIES].sort(), unionLiterals('Capability'));
|
||||
assert.deepEqual([...FRAME_STEPS].sort(), unionLiterals('FrameStep'));
|
||||
for (const port of Object.values(PORTS))
|
||||
for (const capability of Object.values(port))
|
||||
if (capability !== null) assert.ok(CAPABILITIES.includes(capability));
|
||||
assert.equal(CONTRACT_VERSION, '0');
|
||||
const settings = checker.getTypeAtLocation(declared('QualitySettings').name);
|
||||
assert.deepEqual(
|
||||
[...QUALITY_KEYS].sort(),
|
||||
checker
|
||||
.getPropertiesOfType(settings)
|
||||
.map((p) => p.name)
|
||||
.sort(),
|
||||
);
|
||||
});
|
||||
|
||||
test('a draw set’s events: ready with the id, loadFailed with the id and why', () => {
|
||||
const on = checker
|
||||
.getTypeAtLocation(declared('DrawSet').name)
|
||||
.getProperty('on');
|
||||
const signatures = checker
|
||||
.getTypeOfSymbolAtLocation(on, declared('DrawSet'))
|
||||
.getCallSignatures();
|
||||
const events = Object.fromEntries(
|
||||
signatures.map((signature) => {
|
||||
const [event, cb] = signature.getParameters();
|
||||
const callback = checker
|
||||
.getTypeOfSymbolAtLocation(cb, cb.valueDeclaration)
|
||||
.getCallSignatures()[0];
|
||||
return [
|
||||
checker.getTypeOfSymbolAtLocation(event, event.valueDeclaration).value,
|
||||
callback
|
||||
.getParameters()
|
||||
.map((p) =>
|
||||
checker.typeToString(
|
||||
checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration),
|
||||
),
|
||||
),
|
||||
];
|
||||
}),
|
||||
);
|
||||
assert.deepEqual(events, {
|
||||
ready: ['string'],
|
||||
loadFailed: ['string', 'string'],
|
||||
});
|
||||
});
|
||||
|
||||
test('members added to version 0 later are optional, each behind its capability', () => {
|
||||
// A renderer conforms without them.
|
||||
assert.equal(PORTS.globe.isGlobeVisible, 'globeVisibility');
|
||||
assert.equal(PORTS.camera.followFrame, 'followFrame');
|
||||
// Item fields added later are optional too.
|
||||
const optional = (shape, field) =>
|
||||
Object.fromEntries(
|
||||
members(checker.getTypeAtLocation(declared(shape).name)),
|
||||
)[field];
|
||||
assert.equal(optional('LineItem', 'depthFail'), true);
|
||||
// And on one kind of a union: the rectangle's rotation.
|
||||
const rectangle = checker
|
||||
.getTypeAtLocation(declared('ShapeGeometry').name)
|
||||
.types.find((kind) => checker.getPropertyOfType(kind, 'rect'));
|
||||
assert.equal(Object.fromEntries(members(rectangle)).rotation, true);
|
||||
});
|
||||
|
||||
test('the shape check names what is missing and what a capability does not allow', () => {
|
||||
assert.deepEqual(checkRendererShape(null), ['renderer is not an object']);
|
||||
assert.deepEqual(checkRendererShape({}), [
|
||||
'renderer.capabilities is not a Set',
|
||||
]);
|
||||
const problems = checkRendererShape({
|
||||
capabilities: new Set(['warp']),
|
||||
contractVersion: '0',
|
||||
});
|
||||
assert.ok(problems.includes('unknown capability warp'));
|
||||
assert.ok(problems.includes('renderer.frame is missing'));
|
||||
const set = Object.fromEntries(
|
||||
Object.keys(PORTS.drawSet).map((member) => [member, () => {}]),
|
||||
);
|
||||
assert.deepEqual(checkPortShape(set, 'drawSet', new Set()), [
|
||||
'drawSet.setColumns is present without columns',
|
||||
]);
|
||||
delete set.setColumns;
|
||||
assert.deepEqual(checkPortShape(set, 'drawSet', new Set(['columns'])), [
|
||||
'drawSet.setColumns is missing with columns',
|
||||
]);
|
||||
assert.deepEqual(checkPortShape(set, 'drawSet', new Set()), []);
|
||||
});
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Attribution. The renderer reports every credit it owes (its own, each
|
||||
* base layer's, and per-tile credits as tiles load); the application renders the
|
||||
* credit DOM, so the credits always look the same.
|
||||
*/
|
||||
import type { Off } from './common';
|
||||
|
||||
/** One credit, as plain data: the application renders and escapes it. */
|
||||
export interface Credit {
|
||||
/** Plain text, never markup. */
|
||||
text: string;
|
||||
/** Where the credit links to. */
|
||||
href?: string;
|
||||
/** The words of `text` the link covers; the whole text when absent. */
|
||||
linkText?: string;
|
||||
/** A logo, drawn in place of the text; the text names it. */
|
||||
logoUrl?: string;
|
||||
/** Shown on the map itself, rather than in the expanded list. */
|
||||
inline?: boolean;
|
||||
}
|
||||
|
||||
export interface CreditsPort {
|
||||
/** Add a credit the application owes (a layer's source). */
|
||||
addStatic(credit: Credit): Off;
|
||||
/** Every credit owed now, in display order. */
|
||||
list(): Credit[];
|
||||
on(event: 'change', cb: (credits: Credit[]) => void): Off;
|
||||
}
|
||||
Vendored
+627
@@ -0,0 +1,627 @@
|
||||
/**
|
||||
* Things to draw: batched sets of items keyed by string id.
|
||||
*
|
||||
* The application owns every record; a set is only what it pushed. Each item may carry
|
||||
* an opaque `meta` that comes back on a pick (`Hit.meta`). There is no world
|
||||
* text here: every label goes through the application's screen-space label overlay,
|
||||
* which only needs `query.project`/`projectMany` and `query.isOccluded`.
|
||||
*
|
||||
* Moving icons follow a motion segment the renderer evaluates on its own
|
||||
* clock (`motionSegments`), so the application writes a row only when its motion or
|
||||
* style changes, not every frame.
|
||||
*/
|
||||
import type {
|
||||
Color,
|
||||
Ecef,
|
||||
GeoRect,
|
||||
Handle,
|
||||
Meta,
|
||||
NearFar,
|
||||
Off,
|
||||
Position,
|
||||
Quaternion,
|
||||
ScreenXY,
|
||||
Vec3,
|
||||
} from './common';
|
||||
|
||||
/** How an item's height is read. */
|
||||
export type HeightMode = 'absolute' | 'clampGround' | 'relativeGround';
|
||||
|
||||
/** What `clampGround` / `relativeGround` clamp to. */
|
||||
export type ClampTarget = 'terrain' | 'tiles' | 'both';
|
||||
|
||||
/**
|
||||
* `cluster`: screen-space clustering of a set's icons. Which icons cluster
|
||||
* is `clusterScreenPoints` (`src/geo/screenCluster.js`) over the set's shown
|
||||
* icons in front of the eye and above the horizon, in the set's order, each
|
||||
* boxed at its drawn size (its larger side, times its `scale`), with
|
||||
* `pixelRange` and `minimumSize`, and the last pass's clusters kept as it
|
||||
* keeps them: so the renderer forms exactly these clusters. A cluster draws one
|
||||
* icon at the cluster's position (the mean of its members') in place of its
|
||||
* members, which are not drawn: its image is `icon(count)` when given, else
|
||||
* a default badge showing the count, drawn at its seed's size. A pick on a
|
||||
* cluster answers one `Hit` per member, in the cluster's order (seed
|
||||
* first), each with that member's own `set`, `id` and `meta` and the
|
||||
* cluster's `position`: so `pick` gives the seed and `drillPick` every
|
||||
* member. Clusters are recomputed in the frames drawn after the camera
|
||||
* moves or the set changes, never on a timer.
|
||||
*/
|
||||
export interface ClusterSpec {
|
||||
/** Screen distance under which icons merge, CSS pixels. */
|
||||
pixelRange: number;
|
||||
/** Fewest icons that form a cluster. */
|
||||
minimumSize: number;
|
||||
/** Draws a cluster's icon from its member count. */
|
||||
icon?: (count: number) => ImageRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* `recede`: a set's items shrink and fade toward the globe's limb, as
|
||||
* `src/render/recession.js` (exported as `render/recession`) works it out,
|
||||
* so the renderer draws exactly those factors. Nearer than `startLimbRatio` of
|
||||
* the eye's distance to the limb an item is drawn as it is; from there it
|
||||
* eases (smoothstep) to `scaleFloor` times its scale and `alphaFloor` haze
|
||||
* at the limb and beyond. All of it eases back to nothing as the eye climbs
|
||||
* from `globeViewBlendStartM` to `globeViewBlendEndM` above the ellipsoid.
|
||||
* An item draws at its alpha times `max(combinedAlphaFloor, focus × haze)`,
|
||||
* that floor holding even while nothing recedes. Icons shrink and fade;
|
||||
* models only fade. Every parameter is optional, the defaults in brackets.
|
||||
*/
|
||||
export interface RecedeSpec {
|
||||
/** Where receding starts, as a share of the limb's distance [0.5]. */
|
||||
startLimbRatio?: number;
|
||||
/** The scale an item reaches at the limb [0.45]; icons only. */
|
||||
scaleFloor?: number;
|
||||
/** The haze an item reaches at the limb [0.35]. */
|
||||
alphaFloor?: number;
|
||||
/** The least `focus × haze` draws with [0.2]. */
|
||||
combinedAlphaFloor?: number;
|
||||
/** Eye height above the ellipsoid where receding starts to ease off, metres [3,500,000]. */
|
||||
globeViewBlendStartM?: number;
|
||||
/** Eye height from which nothing recedes, metres [4,500,000]. */
|
||||
globeViewBlendEndM?: number;
|
||||
/** The radius of the sphere the limb is measured on, metres [6,378,137]. */
|
||||
earthRadiusM?: number;
|
||||
}
|
||||
|
||||
/** Options of a whole set; the mutable ones can change later through `setOptions`. */
|
||||
export interface SetSpec {
|
||||
/**
|
||||
* Unique among the renderer's live sets (making a second set with a live
|
||||
* id throws; a disposed set's id can be used again); returned as `Hit.set`.
|
||||
*/
|
||||
id: string;
|
||||
/** Hide items beyond the ellipsoid's horizon, for sets drawn without depth test. */
|
||||
horizonCull?: boolean;
|
||||
/** `cluster`: screen-space clustering (icons only; see `ClusterSpec`). */
|
||||
cluster?: ClusterSpec | null;
|
||||
/**
|
||||
* Icons and models: the items recede toward the limb (`RecedeSpec`; `{}`
|
||||
* for the defaults). Omitted or `null`: they do not. Changes live.
|
||||
*/
|
||||
recede?: RecedeSpec | null;
|
||||
/**
|
||||
* How the set's items blend with what is drawn. Omitted: opaque parts
|
||||
* opaque with depth writes, items with alpha under 1 alpha-blended without
|
||||
* depth writes. `opaque`: every item opaque, its alpha ignored (taken as
|
||||
* 1), with depth writes (icons and points keep every part they draw,
|
||||
* unblended). `translucent`: every item alpha-blended without depth
|
||||
* writes, even at alpha 1. `additive`: each item's colour times its alpha
|
||||
* added to what is drawn, without depth writes and still depth-tested.
|
||||
* For every kind of set; `setOptions({blend})` takes effect from the next
|
||||
* frame, and models do not load again.
|
||||
*/
|
||||
blend?: 'opaque' | 'translucent' | 'additive';
|
||||
/**
|
||||
* Among sets that do not depth-test against each other (items drawn with
|
||||
* `disableDepthTest`), a higher one draws over a lower one whatever order
|
||||
* they were made in; equal ones keep that order. `pick` and `drillPick`
|
||||
* name them topmost first. Default 0.
|
||||
*/
|
||||
drawOrder?: number;
|
||||
/** `false`: the set never takes part in picks. */
|
||||
pickable?: boolean;
|
||||
/**
|
||||
* Height queries (`query.sampleHeight` and the rest) see this set as
|
||||
* ground. Off by default: queries answer from tiles and terrain alone.
|
||||
*/
|
||||
includeInHeightQueries?: boolean;
|
||||
/** What clamped items clamp to. */
|
||||
clampTo?: ClampTarget;
|
||||
/**
|
||||
* `motionSegments`: the clock motion segments are evaluated on.
|
||||
* `live` (the default) is wall time minus `delayMs`, as a live feed is
|
||||
* drawn a little behind real time; `scene` is the frame port's scene time.
|
||||
*/
|
||||
motionClock?: { kind: 'live'; delayMs?: number } | { kind: 'scene' };
|
||||
show?: boolean;
|
||||
}
|
||||
|
||||
/** Common to items placed at one position. */
|
||||
export interface Placed {
|
||||
id: string;
|
||||
pos: Position;
|
||||
height?: HeightMode;
|
||||
meta?: Meta;
|
||||
show?: boolean;
|
||||
/** `false`: this item never takes part in picks. */
|
||||
pickable?: boolean;
|
||||
scaleByDistance?: NearFar;
|
||||
fadeByDistance?: NearFar;
|
||||
/** Shown only at eye distances in `[near, far)`, metres. */
|
||||
displayRange?: [near: number, far: number];
|
||||
/** Draw over depth within this many metres of the eye (`Infinity`: always). */
|
||||
disableDepthTest?: number;
|
||||
}
|
||||
|
||||
/** An image an icon draws: a URL, a slot in a shared atlas, or generated. */
|
||||
export type ImageRef =
|
||||
| string
|
||||
| { atlas: string; slot: string }
|
||||
| { svg: string }
|
||||
| { blob: Blob }
|
||||
| { canvas: HTMLCanvasElement | OffscreenCanvas; key: string };
|
||||
|
||||
/**
|
||||
* How an icon moves between updates, on its set's `motionClock`. Times are
|
||||
* epoch ms. Sending an item a new segment replaces its old one, whatever the
|
||||
* times (an earlier or equal `t0` included).
|
||||
* - hold: stays at `pos`.
|
||||
* - lerp: straight in space from `from` (at `t0`) to `to` (at `t1`), holding
|
||||
* at both ends; the course runs from `course0Deg` by `courseSlopeDeg`
|
||||
* across the segment.
|
||||
* - arc: a constant-rate turn in the plane tangent to the ellipsoid at `fix`
|
||||
* (its east and north axes), from `fix` at `t0`, at `speedMps` along
|
||||
* `trackDeg` turning at `turnRateDps` (under 1e-4 rad/s is straight), and
|
||||
* climbing along the fix's up axis at `climbMps` (default 0). The elapsed
|
||||
* time is clamped to `[minDtS, maxDtS]`; a negative `minDtS` runs the same
|
||||
* path backward before `t0` (a warm-up), `maxDtS` is how long it coasts.
|
||||
* The drawn course turns onto a new one at once; an item with `courseGlide`
|
||||
* eases at its rate instead, on a renderer with the `courseGlide` capability.
|
||||
*/
|
||||
export type MotionSegment =
|
||||
| { kind: 'hold'; courseDeg?: number }
|
||||
| {
|
||||
kind: 'lerp';
|
||||
from: Ecef;
|
||||
to: Ecef;
|
||||
t0: number;
|
||||
t1: number;
|
||||
course0Deg?: number;
|
||||
courseSlopeDeg?: number;
|
||||
}
|
||||
| {
|
||||
kind: 'arc';
|
||||
fix: Ecef;
|
||||
t0: number;
|
||||
minDtS: number;
|
||||
maxDtS: number;
|
||||
speedMps: number;
|
||||
trackDeg: number;
|
||||
turnRateDps: number;
|
||||
/** Metres per second along the fix's up axis. */
|
||||
climbMps?: number;
|
||||
};
|
||||
|
||||
export interface CourseGlide {
|
||||
fromCourseDeg: number;
|
||||
t0: number;
|
||||
/** Degrees per second; 0 or less holds `fromCourseDeg`. */
|
||||
rateDps: number;
|
||||
}
|
||||
|
||||
export interface IconItem extends Placed {
|
||||
image: ImageRef;
|
||||
/** Drawn size in CSS pixels. */
|
||||
size: [width: number, height: number];
|
||||
color?: Color;
|
||||
alpha?: number;
|
||||
scale?: number;
|
||||
/** `motionSegments`: motion on the renderer's clock. */
|
||||
motion?: MotionSegment;
|
||||
/** `courseGlide`: ease the drawn course at a rate, from `fromCourseDeg`. */
|
||||
courseGlide?: CourseGlide;
|
||||
/** Degrees clockwise from north. */
|
||||
course?: number;
|
||||
/**
|
||||
* `screen`: upright on screen, rotated by `rotation`;
|
||||
* `course`: rotated on screen along `course` (or the motion's course);
|
||||
* `axis`: its up along `alignedAxis` as projected on screen, then
|
||||
* rotated by `rotation`.
|
||||
*/
|
||||
rotationMode?: 'screen' | 'course' | 'axis';
|
||||
/**
|
||||
* Radians counter-clockwise on screen, for `rotationMode: 'screen'` and
|
||||
* `'axis'`.
|
||||
*/
|
||||
rotation?: number;
|
||||
/** ECEF axis for `rotationMode: 'axis'`. */
|
||||
alignedAxis?: Vec3;
|
||||
/** CSS pixels, y down. */
|
||||
pixelOffset?: ScreenXY;
|
||||
/** `pixelOffset` grows and shrinks with `scaleByDistance`, as the icon does. */
|
||||
offsetScalesByDistance?: boolean;
|
||||
anchor?: 'center' | 'bottom' | 'top';
|
||||
/** Swap to `near` when drawn larger than `switchPx`. */
|
||||
imageLod?: { near: ImageRef; switchPx: number };
|
||||
/** A larger invisible pick target, CSS pixels. */
|
||||
pickProxy?: { size: [width: number, height: number] };
|
||||
/**
|
||||
* Emphasis for a focused item, 0..1, 1 = none: the alpha is multiplied by
|
||||
* it (in a set that recedes, as `RecedeSpec` says).
|
||||
*/
|
||||
focus?: number;
|
||||
}
|
||||
|
||||
export interface PointItem extends Placed {
|
||||
pixelSize: number;
|
||||
color: Color;
|
||||
outlineColor?: Color;
|
||||
outlineWidth?: number;
|
||||
}
|
||||
|
||||
export type LineStyle =
|
||||
| {
|
||||
kind: 'solid';
|
||||
color: Color;
|
||||
/**
|
||||
* An edge `widthPx` wide in all, half of it on each side, inside the
|
||||
* line's width (a line 8 px wide with an outline of 4 has 2 px of
|
||||
* outline each side and 4 px of `color` between), drawn in the same
|
||||
* pass as the line: a translucent edge does not darken where it meets
|
||||
* the line. Its colour changes in place.
|
||||
*/
|
||||
outline?: { color: Color; widthPx: number };
|
||||
}
|
||||
| { kind: 'glow'; color: Color; power: number; taper?: number }
|
||||
| { kind: 'dash'; color: Color; length: number; pattern16?: number }
|
||||
| { kind: 'arrow'; color: Color }
|
||||
| { kind: 'pattern'; image: ImageRef; repeat: number }
|
||||
| { kind: 'flow'; color: Color; repeat: number; duty: number; speed: number }
|
||||
| {
|
||||
/**
|
||||
* Draped lines only. `color` from fraction `at` of the line's length
|
||||
* to its end, `behind` from its start to `at` (the other way round
|
||||
* with `reverse`); `at` outside 0..1 draws it all in `color`. With a
|
||||
* `rim`, the outer `widthFraction` of the width in all (half each
|
||||
* side) draws each colour's red, green and blue times `shade`, its
|
||||
* alpha kept. `at`, `reverse` and the colours change in place.
|
||||
*/
|
||||
kind: 'split';
|
||||
color: Color;
|
||||
behind: Color;
|
||||
at: number;
|
||||
reverse?: boolean;
|
||||
rim?: { shade: number; widthFraction: number };
|
||||
};
|
||||
|
||||
export interface LineItem {
|
||||
id: string;
|
||||
/** ECEF positions, or packed `x, y, z` triples. */
|
||||
positions: Ecef[] | Float64Array;
|
||||
widthPx: number;
|
||||
/**
|
||||
* `3d`: straight in space; `geodesic`: along the ellipsoid; `draped`: on
|
||||
* the surface. Where the renderer cannot drape at all, it draws `draped` lines
|
||||
* and clamped shapes as in `overlay`, and `clampState()` says `overlay`.
|
||||
*/
|
||||
mode: '3d' | 'geodesic' | 'draped';
|
||||
clampTo?: ClampTarget;
|
||||
style: LineStyle;
|
||||
/**
|
||||
* How the parts behind the surface draw, solid or dashed; omitted or
|
||||
* `null` hides them. Ignored on draped lines, which are never behind it.
|
||||
*/
|
||||
depthFail?:
|
||||
| { kind: 'solid'; color: Color }
|
||||
| Extract<LineStyle, { kind: 'dash' }>
|
||||
| null;
|
||||
/** Per-segment colours; changing them does not rebuild the line. */
|
||||
segmentColors?: Color[];
|
||||
segmentShow?: boolean[];
|
||||
/** Draw only the first fraction of the line, 0..1. */
|
||||
revealFraction?: number;
|
||||
/** Positions are in a frame rotating with the sky (orbits). */
|
||||
frame?: 'fixed' | 'inertial';
|
||||
meta?: Meta;
|
||||
show?: boolean;
|
||||
pickable?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A shape's fill: a colour, or an image stretched over the shape's extent
|
||||
* (`repeat` times across and up). A canvas image sent again with a new
|
||||
* `key` is new content.
|
||||
*/
|
||||
export type Fill = Color | { image: ImageRef; repeat?: [number, number] };
|
||||
|
||||
/**
|
||||
* Declarative animation the renderer runs (no per-frame callbacks): the
|
||||
* fill's and outline's alpha swings between `from` and `to` and back every
|
||||
* `periodMs`, forever.
|
||||
*/
|
||||
export interface Pulse {
|
||||
property: 'alpha';
|
||||
from: number;
|
||||
to: number;
|
||||
periodMs: number;
|
||||
}
|
||||
|
||||
export type ShapeGeometry =
|
||||
| { kind: 'polygon'; rings: Position[][]; perPositionHeight?: boolean }
|
||||
| {
|
||||
kind: 'ellipse';
|
||||
center: Position;
|
||||
/** Metres. */
|
||||
semiMajor: number;
|
||||
semiMinor: number;
|
||||
/** Radians counter-clockwise from north to the semi-major axis. */
|
||||
rotation?: number;
|
||||
}
|
||||
/**
|
||||
* `height`: metres above the ellipsoid, for a rectangle not clamped.
|
||||
* `rotation`: radians counter-clockwise, turning the rectangle about its
|
||||
* centre in longitude and latitude (as a KML ground overlay turns); an
|
||||
* image fill turns with it.
|
||||
*/
|
||||
| { kind: 'rectangle'; rect: GeoRect; height?: number; rotation?: number }
|
||||
| {
|
||||
kind: 'wall';
|
||||
positions: Position[];
|
||||
minimumHeights?: number[];
|
||||
maximumHeights?: number[];
|
||||
};
|
||||
|
||||
export interface ShapeItem {
|
||||
id: string;
|
||||
geometry: ShapeGeometry;
|
||||
fill?: Fill | null;
|
||||
outline?: Color | null;
|
||||
outlineWidth?: number;
|
||||
/** Draw the outline only. Clamped outlines are drawn as draped lines. */
|
||||
outlineOnly?: boolean;
|
||||
/** Height of the extruded face, metres above the ellipsoid (not above the shape). */
|
||||
extrudeHeight?: number;
|
||||
height?: 'absolute' | 'clampGround';
|
||||
clampTo?: ClampTarget;
|
||||
/**
|
||||
* Shaded by the renderer's fixed light (true) or flat colour (false).
|
||||
* Omitted: lit for extruded shapes, flat otherwise. A renderer
|
||||
* may draw clamped shapes, which drape on the surface, flat whatever it
|
||||
* says.
|
||||
*/
|
||||
lit?: boolean;
|
||||
animate?: Pulse;
|
||||
meta?: Meta;
|
||||
show?: boolean;
|
||||
pickable?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A glTF model. The renderer draws one this way: glTF is Y-up and is
|
||||
* turned to Z-up before `orientation` applies; `minPixelSize` is measured at
|
||||
* the model's bounding-sphere distance from the eye; `colorBlend` mixes the
|
||||
* tint into the shaded colour and never changes the model's alpha.
|
||||
*/
|
||||
export interface ModelItem extends Placed {
|
||||
url: string;
|
||||
orientation: { heading: number; pitch: number; roll: number };
|
||||
scale?: number;
|
||||
minPixelSize?: number;
|
||||
maxPixelSize?: number;
|
||||
maxScale?: number;
|
||||
/** Can change live. */
|
||||
shading?: 'pbr' | 'unlit' | 'thermal';
|
||||
tint?: Color;
|
||||
colorBlend?: { mode: 'highlight' | 'replace' | 'mix'; amount?: number };
|
||||
environmentMap?: boolean;
|
||||
/**
|
||||
* The model's glTF (GLB) bytes, loaded already: the renderer draws it from
|
||||
* these and never fetches `url`, which stays its identity (an update that
|
||||
* keeps the `url` keeps the model, whatever bytes it carries), so models
|
||||
* loaded up front are never fetched mid-session. A renderer reads models
|
||||
* compressed with `EXT_meshopt_compression` and `KHR_mesh_quantization`.
|
||||
*/
|
||||
gltf?: Uint8Array;
|
||||
/**
|
||||
* Per-axis multipliers on top of `scale`, along the model's own glTF axes
|
||||
* (`x`, `y`, `z` as authored, before the Y-up turn): a model stretched
|
||||
* wider or taller than its length scale. `minPixelSize` and
|
||||
* `maxPixelSize` measure `scale` alone. Can change live.
|
||||
*/
|
||||
axisScale?: [x: number, y: number, z: number];
|
||||
/**
|
||||
* For a model whose meshes carry a `_TINT` vertex attribute (0..1): a
|
||||
* colour painted where it marks the model, drawn colour = colour ×
|
||||
* mix(1, maskColor, _TINT), `maskColor` read as sRGB (its alpha unused).
|
||||
* Applied under `pbr` and `unlit` shading, not under `thermal`. Never sent
|
||||
* for a model without the attribute. Can change live.
|
||||
*/
|
||||
maskColor?: Color;
|
||||
/**
|
||||
* `belowOrigin`: only the part of the model above the horizontal plane
|
||||
* through `pos` is drawn (a hull above its waterline, where the globe
|
||||
* would not hide what lies below it). Can change live.
|
||||
*/
|
||||
clip?: 'belowOrigin';
|
||||
/**
|
||||
* Transforms of the model's named glTF nodes (an articulated model's
|
||||
* joints): each a column-major 4×4 matrix in the node's parent frame that
|
||||
* replaces the node's own transform. A node whose name leaves the map goes
|
||||
* back to its authored pose; names the model lacks are ignored. Applied
|
||||
* once the model is ready. Can change live.
|
||||
*/
|
||||
nodes?: Readonly<Record<string, ArrayLike<number>>>;
|
||||
/**
|
||||
* Emphasis for a focused model, 0..1, 1 = none: the tint's alpha is
|
||||
* multiplied by it (in a set that recedes, as `RecedeSpec` says). Can
|
||||
* change live.
|
||||
*/
|
||||
focus?: number;
|
||||
}
|
||||
|
||||
/** A plane showing an image, a video or a canvas. */
|
||||
export interface QuadItem {
|
||||
id: string;
|
||||
center: Position;
|
||||
orientation: Quaternion;
|
||||
/** Metres. */
|
||||
size: [width: number, height: number];
|
||||
source:
|
||||
| { image: ImageRef }
|
||||
| { video: HTMLVideoElement }
|
||||
| { canvas: HTMLCanvasElement | OffscreenCanvas };
|
||||
alpha?: number;
|
||||
outline?: { color: Color; widthPx: number } | null;
|
||||
meta?: Meta;
|
||||
show?: boolean;
|
||||
pickable?: boolean;
|
||||
}
|
||||
|
||||
/** Custom geometry in a local east-north-up frame at `origin`. */
|
||||
export interface MeshItem {
|
||||
id: string;
|
||||
origin: Ecef;
|
||||
/** Packed `east, north, up` metres. */
|
||||
positions: Float32Array;
|
||||
indices: Uint16Array | Uint32Array;
|
||||
color: Color;
|
||||
/** Unlit, with back faces drawn. */
|
||||
flat?: boolean;
|
||||
meta?: Meta;
|
||||
show?: boolean;
|
||||
pickable?: boolean;
|
||||
}
|
||||
|
||||
export type FieldSpec =
|
||||
| {
|
||||
kind: 'windStreamlines';
|
||||
id: string;
|
||||
/** Row-major `u` and `v` in m/s on a `width × height` grid over `rectangle`. */
|
||||
u: Float32Array;
|
||||
v: Float32Array;
|
||||
width: number;
|
||||
height: number;
|
||||
rectangle: GeoRect;
|
||||
pathBudget: number;
|
||||
steps: number;
|
||||
style: { color: Color; widthPx: number; speedFactor?: number };
|
||||
/** Draw height, metres; omitted drapes on the surface. */
|
||||
heightM?: number;
|
||||
/** 0..1, changeable without a rebuild (fade by height). */
|
||||
alpha?: number;
|
||||
/** Draw the paths still, dimmed. */
|
||||
paused?: boolean;
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* A raster on a sphere raised above the ground. Shells draw in
|
||||
* ascending `heightM`, alpha-blended and unlit; they are never picked
|
||||
* and never in height queries. Changing `liftM` or `alpha` never
|
||||
* rebuilds. An `update` that changes `image`, `rectangle` or `detail`
|
||||
* keeps drawing what it drew until the new content can be drawn whole.
|
||||
*/
|
||||
kind: 'rasterShell';
|
||||
id: string;
|
||||
image: ImageRef;
|
||||
rectangle: GeoRect;
|
||||
heightM: number;
|
||||
liftM?: number;
|
||||
/**
|
||||
* A sharper image drawn in place of `image` inside its own
|
||||
* `rectangle`, never blended with it; null or omitted: none.
|
||||
*/
|
||||
detail?: { image: ImageRef; rectangle: GeoRect } | null;
|
||||
alpha?: number;
|
||||
};
|
||||
|
||||
export interface FieldHandle extends Handle {
|
||||
update(patch: Partial<FieldSpec>): void;
|
||||
/**
|
||||
* `fields`: what the spec or the last `update` asked for is drawn now.
|
||||
* Once per such change; never while hidden. Changes made before one is
|
||||
* drawn (the spec and updates, or updates while hidden) are told once,
|
||||
* when the latest is drawn.
|
||||
*/
|
||||
on(event: 'drawn', cb: () => void): Off;
|
||||
}
|
||||
|
||||
/**
|
||||
* Columnar update for large sets (`columns`). Column `i` of each array is
|
||||
* row `ids[i]`. `dirty` limits the upload to these index runs.
|
||||
*/
|
||||
export interface Columns {
|
||||
ids: readonly string[];
|
||||
/** Packed ECEF `x, y, z`. */
|
||||
positions?: Float64Array;
|
||||
/** Degrees clockwise from north. */
|
||||
courses?: Float32Array;
|
||||
/**
|
||||
* 0 hides a row. A hidden row keeps its motion state (where it is on its
|
||||
* segment, its eased course), so showing it again resumes, not restarts.
|
||||
*/
|
||||
shown?: Uint8Array;
|
||||
scales?: Float32Array;
|
||||
alphas?: Float32Array;
|
||||
/** Packed `r, g, b, a`, 0..255. */
|
||||
colors?: Uint8Array;
|
||||
meta?: readonly Meta[];
|
||||
dirty?: ReadonlyArray<{ start: number; end: number }>;
|
||||
}
|
||||
|
||||
export interface DrawSet<T> {
|
||||
readonly id: string;
|
||||
/** Replace every item. */
|
||||
set(items: T[]): void;
|
||||
/** Add or replace items by id. */
|
||||
upsert(items: T[]): void;
|
||||
remove(ids: string[]): void;
|
||||
clear(): void;
|
||||
/** `columns`. */
|
||||
setColumns?(columns: Columns): void;
|
||||
/** Change the mutable set options. */
|
||||
setOptions(options: Partial<Omit<SetSpec, 'id'>>): void;
|
||||
/** Items in the set. */
|
||||
size(): number;
|
||||
show: boolean;
|
||||
/** `models`: a model has loaded and is posed. */
|
||||
on(event: 'ready', cb: (id: string) => void): Off;
|
||||
/**
|
||||
* `models`: a model's url failed to load (`message` says why), once per
|
||||
* failed load. The item stays in the set, drawing what it drew before (a
|
||||
* new item draws nothing); a renderer may try the url again when the item
|
||||
* is next updated. Removing the item and adding it again tries at once.
|
||||
* Optional: where the renderer cannot tell a failure it may never fire it, so
|
||||
* a fallback must not wait on it.
|
||||
*/
|
||||
on(event: 'loadFailed', cb: (id: string, message: string) => void): Off;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface DrawPort {
|
||||
icons(spec: SetSpec): DrawSet<IconItem>;
|
||||
points(spec: SetSpec): DrawSet<PointItem>;
|
||||
lines(spec: SetSpec): DrawSet<LineItem>;
|
||||
shapes(spec: SetSpec): DrawSet<ShapeItem>;
|
||||
/** `models`. */
|
||||
models?(spec: SetSpec): DrawSet<ModelItem>;
|
||||
/** `quads`. */
|
||||
quads?(spec: SetSpec): DrawSet<QuadItem>;
|
||||
/** `meshes`. */
|
||||
meshes?(spec: SetSpec): DrawSet<MeshItem>;
|
||||
/** `fields`. */
|
||||
field?(spec: FieldSpec): FieldHandle;
|
||||
/**
|
||||
* Whether clamped items (`clampTo: 'tiles' | 'both'`, draped lines and
|
||||
* shapes) are draped onto the 3D tiles now (`draped`), or drawn over them
|
||||
* and hidden past the ellipsoid's horizon (`overlay`), the fallback a
|
||||
* renderer uses where it cannot drape. Without tiles in the base it is
|
||||
* `draped`: clamping to terrain or the ellipsoid always drapes, on a
|
||||
* renderer that can drape at all (one that cannot is always `overlay`).
|
||||
*/
|
||||
clampState(): 'draped' | 'overlay';
|
||||
/** Fires when `clampState()` changes (not on subscribing). */
|
||||
on(event: 'clampState', cb: (state: 'draped' | 'overlay') => void): Off;
|
||||
/** Register an atlas of images icons refer to by slot. */
|
||||
atlas(id: string, images: Record<string, ImageRef>): void;
|
||||
}
|
||||
Vendored
+103
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Full-screen effects: visual styles, bloom, sharpen and screen modulation.
|
||||
* Each style is a plain full-screen pass over the frame's colour. The
|
||||
* application owns the styles and defines them on the renderer
|
||||
* (`defineStyle`); the renderer's own styles are extra ones.
|
||||
*/
|
||||
import type { Off } from './common';
|
||||
|
||||
export interface StyleDescriptor {
|
||||
id: string;
|
||||
/** Parameters and their ranges. */
|
||||
params: Array<{ key: string; min: number; max: number; default: number }>;
|
||||
/** Animates, so it needs frames while on. */
|
||||
animated: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A style's shader. `glsl` is a GLSL ES 3.00 fragment shader with its
|
||||
* `main()`, as GEV's styles are written, without `#version`, `precision`
|
||||
* or an `out` declaration: the renderer declares `out_FragColor`, which it
|
||||
* writes. It declares what it reads of `uniform sampler2D colorTexture`,
|
||||
* `uniform vec2 colorTextureDimensions` (pixels),
|
||||
* `in vec2 v_textureCoordinates`, `uniform float intensity` (0..1),
|
||||
* `uniform float time` (seconds, for an animated style) and one
|
||||
* `uniform float` per parameter under its key. Parameter keys are GLSL
|
||||
* identifiers and never one of those names.
|
||||
* `wgsl` is the same pass in WGSL: a fragment entry
|
||||
* `fs_main` taking `@location(0) uv: vec2f` and returning the colour at
|
||||
* `@location(0)`. Group 0 binds `colorTexture` (`texture_2d<f32>`) at 0,
|
||||
* `colorSampler` at 1 and, at 2, a uniform struct the shader declares as
|
||||
* `params`: `intensity: f32`, `time: f32`, `dimensions: vec2f`, then one
|
||||
* `f32` per parameter in the order `params` lists them.
|
||||
*/
|
||||
export interface StyleShader {
|
||||
glsl: string;
|
||||
wgsl?: string;
|
||||
}
|
||||
|
||||
export interface StyleDefinition extends StyleDescriptor {
|
||||
shader: StyleShader;
|
||||
}
|
||||
|
||||
/**
|
||||
* `screenModulation`: a sweeping band over the drawn markers (a sonar).
|
||||
* Icons, points and models are dimmed toward `floor` and brought back to
|
||||
* full inside the band, each by where its anchor is on screen; the map,
|
||||
* lines and shapes draw as they are, and picks are unchanged. A radius of 0
|
||||
* dims every marker to `floor` (the theme on, the sweep off). Setting a
|
||||
* sector, or clearing it, asks for one frame; the application moves it about every
|
||||
* 80 ms while it sweeps.
|
||||
* `diagnostics().passes` lists `'screenModulation'` while it draws, so a
|
||||
* sector set but not listed is unsupported.
|
||||
*/
|
||||
export interface ModulationSector {
|
||||
/** Centre of the sweep, CSS pixels. */
|
||||
center: { x: number; y: number };
|
||||
/** Current angle, radians clockwise from up. */
|
||||
angle: number;
|
||||
/** Width of the band, radians. */
|
||||
width: number;
|
||||
/** Reach of the band from `center`, CSS pixels. */
|
||||
radius: number;
|
||||
/** Alpha factor outside the band, 0..1. */
|
||||
floor: number;
|
||||
/** 0..1: how far a marker's colour is pulled toward `color`. */
|
||||
strength: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export interface EffectsDiagnostics {
|
||||
style: string | null;
|
||||
/** The passes that draw: `style:<id>` for each style, `bloom`, ... */
|
||||
passes: string[];
|
||||
}
|
||||
|
||||
export interface EffectsPort {
|
||||
/** `styles`: every style, defined by the application or the renderer's own. */
|
||||
styles(): StyleDescriptor[];
|
||||
/**
|
||||
* `styles`: add a style, replacing one with the same id. Null without
|
||||
* the capability, or when the renderer runs none of the shader's
|
||||
* languages; the Off removes it (turning it off when it is the style).
|
||||
*/
|
||||
defineStyle(definition: StyleDefinition): Off | null;
|
||||
/**
|
||||
* Make `id` the style, or none. The style it replaces, if its intensity
|
||||
* is above 0, keeps drawing with the new one until its intensity is set
|
||||
* to 0, so the application crossfades by fading one out as it fades the other in.
|
||||
* Styles draw in the order they were defined.
|
||||
*/
|
||||
setStyle(id: string | null, params?: Record<string, number>): void;
|
||||
/** A style's intensity, 0..1; kept while it is not the style. 1 at first. */
|
||||
setStyleIntensity(id: string, intensity: number): void;
|
||||
setStyleParams(id: string, params: Record<string, number>): void;
|
||||
/** `bloom`. `strength`, 0..1, is kept while bloom is off. */
|
||||
bloom(settings: { enabled: boolean; strength?: number }): void;
|
||||
/** `sharpen`. `amount`, 0..1, is kept while sharpen is off. */
|
||||
sharpen(settings: { enabled: boolean; amount?: number }): void;
|
||||
/** `screenModulation`. */
|
||||
screenModulation?(sector: ModulationSector | null): void;
|
||||
diagnostics(): EffectsDiagnostics;
|
||||
on(event: 'change', cb: (diagnostics: EffectsDiagnostics) => void): Off;
|
||||
}
|
||||
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* The frame loop, render on demand and scene time.
|
||||
*
|
||||
* A renderer draws on demand: a frame is drawn when something asks for one
|
||||
* (`requestRender`), while any continuous hold is out, or every frame on an
|
||||
* engine that cannot idle (it then reports `mode()` as `'continuous'`).
|
||||
*
|
||||
* One frame runs in this order, and the renderer keeps it:
|
||||
* camera flight → input → camera `changed` → follow → `preUpdate` →
|
||||
* move detection (`moveStart` / `moveEnd`) → `preRender` → render →
|
||||
* `postRender`. `preUpdate` fires on every frame the loop ticks, including
|
||||
* frames that end up drawing nothing, so owners that write the camera there
|
||||
* (a cockpit, a follow clamp) see each one. This is the default renderer's
|
||||
* own order. `changed` is measured before follow and `preUpdate` move the
|
||||
* camera, so a move made there is reported by `changed` on the next frame;
|
||||
* move detection runs after them and sees it in the same frame. The
|
||||
* default renderer's `postUpdate` has no place here: the application does not use it.
|
||||
*/
|
||||
import type { Off, Release } from './common';
|
||||
|
||||
export type FramePhase = 'preUpdate' | 'preRender' | 'postRender';
|
||||
|
||||
/** The order the phases (and the steps between them) run in one frame. */
|
||||
export type FrameStep =
|
||||
| 'flight'
|
||||
| 'input'
|
||||
| 'changed'
|
||||
| 'follow'
|
||||
| 'preUpdate'
|
||||
| 'moveDetection'
|
||||
| 'preRender'
|
||||
| 'render'
|
||||
| 'postRender';
|
||||
|
||||
export interface FrameTime {
|
||||
/** Frames ticked since creation. */
|
||||
frame: number;
|
||||
/** Scene time, epoch ms: what sun, stars and lighting show. */
|
||||
time: number;
|
||||
/** The loop's clock, ms (virtual under a test clock). */
|
||||
now: number;
|
||||
/** Seconds since the previous tick. */
|
||||
dt: number;
|
||||
/**
|
||||
* Whether this tick draws. Read during `preUpdate` it counts what has been
|
||||
* asked so far; a request or hold made later in `preUpdate` draws this
|
||||
* tick or the next, as the engine decides, and readers after it see
|
||||
* which. Once the tick is over it keeps its answer.
|
||||
*/
|
||||
rendering: boolean;
|
||||
}
|
||||
|
||||
export interface FrameDiagnostics {
|
||||
mode: 'demand' | 'continuous';
|
||||
frames: number;
|
||||
rendered: number;
|
||||
/** Reasons given to `requestRender` since the last frame drawn. */
|
||||
pendingReasons: string[];
|
||||
/** Reasons of the holds now out. */
|
||||
holds: string[];
|
||||
suspended: boolean;
|
||||
/**
|
||||
* The loop stopped after a frame failed, until the application starts it
|
||||
* again (a retry). Absent where the loop never stops so.
|
||||
*/
|
||||
stopped?: boolean;
|
||||
targetFps: number;
|
||||
}
|
||||
|
||||
export interface FramePort {
|
||||
on(phase: FramePhase, cb: (t: FrameTime) => void): Off;
|
||||
/** Ask for one frame. The reason shows in diagnostics and signals. */
|
||||
requestRender(reason: string): void;
|
||||
/** Keep drawing every frame until released. Holds are counted. */
|
||||
holdContinuous(reason: string): Release;
|
||||
mode(): 'demand' | 'continuous';
|
||||
diagnostics(): FrameDiagnostics;
|
||||
/** Stop ticking while the page is hidden; resume on `false`. */
|
||||
suspend(hidden: boolean): void;
|
||||
/**
|
||||
* Draw a frame now, synchronously; throws when the frame fails to draw.
|
||||
* `ifDue`: run one tick of the loop now as its own would (camera flight,
|
||||
* input, clock), drawing only if a frame is due, for a host that stops
|
||||
* the animation frames the loop runs on.
|
||||
*/
|
||||
renderNow(options?: { ifDue?: boolean }): void;
|
||||
/**
|
||||
* Resolves after the next frame has been drawn and presented. Once the
|
||||
* renderer is destroyed it rejects with a "renderer destroyed" error, and
|
||||
* so does one still waiting when the renderer is destroyed.
|
||||
*/
|
||||
renderOnce(options?: { timeoutMs?: number }): Promise<void>;
|
||||
/** Cap the loop's rate; 0 is the display's rate. */
|
||||
setTargetFps(fps: number): void;
|
||||
/**
|
||||
* Set scene time, epoch ms. Set in `preUpdate`, it is the time that frame
|
||||
* draws at; set between frames to a new time, it asks for a frame.
|
||||
*/
|
||||
setTime(ms: number): void;
|
||||
/** Scene time, epoch ms. */
|
||||
time(): number;
|
||||
}
|
||||
Vendored
+365
@@ -0,0 +1,365 @@
|
||||
/**
|
||||
* The base world: photorealistic tiles or a globe with terrain and imagery,
|
||||
* the sky, and what drapes onto them.
|
||||
*/
|
||||
import type { Credit } from './credits';
|
||||
import type { GeoRect, Off } from './common';
|
||||
|
||||
export interface PhotorealSpec {
|
||||
provider: 'google';
|
||||
key?: string;
|
||||
/** Renews a session token; called again when the token expires. */
|
||||
token?: () => Promise<string>;
|
||||
/**
|
||||
* Fall back to the renderer's copy of the same tiles when Google refuses
|
||||
* (for the default renderer, one served from Cesium ion).
|
||||
*/
|
||||
fallback?: boolean;
|
||||
}
|
||||
|
||||
export interface PhotorealStatus {
|
||||
/** Which route is drawing, or `'none'` when photoreal is off or failed. */
|
||||
route: 'google' | 'fallback' | 'none';
|
||||
error?: { code: string; message: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* Heights everywhere in the contract are physical (metres above the
|
||||
* ellipsoid, unexaggerated): absolute positions, `HeightSample.height`,
|
||||
* `clampToSurface`. Only drawing follows the exaggerated surface:
|
||||
* `clampGround` and `relativeGround` items sit on the ground as drawn.
|
||||
*/
|
||||
export type TerrainSpec = (
|
||||
| { kind: 'ellipsoid' }
|
||||
/**
|
||||
* The renderer's global terrain, through `CreateOptions.worldDataToken`
|
||||
* (for the default renderer, Cesium World Terrain).
|
||||
*/
|
||||
| { kind: 'world'; requestVertexNormals?: boolean }
|
||||
/**
|
||||
* Quantized-mesh terrain (Cesium's tile format) in the folder `url`,
|
||||
* holding `layer.json` and its tiles; heights above the ellipsoid.
|
||||
*/
|
||||
| { kind: 'quantizedMesh'; url: string; requestVertexNormals?: boolean }
|
||||
) & {
|
||||
/** Vertical exaggeration of the drawn terrain; default 1. */
|
||||
exaggeration?: number;
|
||||
};
|
||||
|
||||
export type TilingScheme = 'webMercator' | 'geographic';
|
||||
|
||||
/** One tile request, as an admission hook sees it. */
|
||||
export interface TileRequest {
|
||||
x: number;
|
||||
y: number;
|
||||
level: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a tile fetch answered: the bytes to decode, `missing` (no tile
|
||||
* there; draw the parent's), or `defer` (ask again on a later frame).
|
||||
*/
|
||||
export type TileFetch =
|
||||
| { bytes: ArrayBuffer; contentType?: string }
|
||||
| { missing: true }
|
||||
| { defer: true };
|
||||
|
||||
export interface ImagerySpec {
|
||||
/**
|
||||
* `world`: the renderer's global imagery through
|
||||
* `CreateOptions.worldDataToken` (for the default renderer, Cesium ion's
|
||||
* world imagery), in `worldStyle`. `canvas`: `imageHooks`.
|
||||
*/
|
||||
kind: 'xyz' | 'world' | 'single-image' | 'canvas';
|
||||
/** `world`: aerial (the default), or aerial with labels. */
|
||||
worldStyle?: 'aerial' | 'aerialLabels';
|
||||
/** URL or URL template (`{x}`, `{y}`, `{z}`, `{s}`, `{time}`). */
|
||||
url?: string;
|
||||
/** `'canvas'` (`imageHooks`): draws one tile. */
|
||||
drawTile?: (tile: TileRequest, canvas: HTMLCanvasElement) => void;
|
||||
subdomains?: string[];
|
||||
tiling?: TilingScheme;
|
||||
rectangle?: GeoRect;
|
||||
minLevel?: number;
|
||||
maxLevel?: number;
|
||||
/**
|
||||
* Drawn nowhere the surface is coarser than `minLevel`, rather than made
|
||||
* from `minLevel` tiles there: for a layer whose `minLevel` tiles are too
|
||||
* many to fetch far out.
|
||||
*/
|
||||
hiddenBelowMinLevel?: boolean;
|
||||
tileSize?: number;
|
||||
credit?: Credit;
|
||||
/** Requests in flight at once for this layer. */
|
||||
maxConcurrentRequests?: number;
|
||||
/** HTTP statuses retried rather than treated as missing. */
|
||||
retryStatuses?: number[];
|
||||
/**
|
||||
* Fetches a tile in place of the renderer, with the URL it would fetch.
|
||||
* The renderer calls it, before its own decoding (in a worker, say).
|
||||
*/
|
||||
fetchTile?: (request: {
|
||||
tile: TileRequest;
|
||||
url: string;
|
||||
signal: AbortSignal;
|
||||
}) => Promise<TileFetch>;
|
||||
/** `imageHooks`: changes a tile's decoded image before it is drawn. */
|
||||
tileTransform?: (
|
||||
tile: TileRequest,
|
||||
image: ImageBitmap,
|
||||
) => ImageBitmap | Promise<ImageBitmap>;
|
||||
/**
|
||||
* `imageHooks`: decides each tile request on the main thread: call
|
||||
* `issue()` to fetch it, or return `undefined` to defer it and be asked
|
||||
* again on a later frame. Layers given the same function share its waits:
|
||||
* while one of their tiles is in flight, its settling is that frame. `fetchTile`'s `defer` does the same anywhere.
|
||||
* With both, `admit` decides first and an issued request goes through
|
||||
* `fetchTile`; each defers on its own.
|
||||
*/
|
||||
admit?: (
|
||||
tile: TileRequest,
|
||||
issue: () => Promise<unknown> | undefined,
|
||||
) => Promise<unknown> | undefined;
|
||||
/** Draw order among imagery layers; higher draws on top. */
|
||||
zOrder?: number;
|
||||
}
|
||||
|
||||
export interface TimedUrl {
|
||||
/** Epoch ms the frame shows. */
|
||||
time: number;
|
||||
url: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A timed source: frames as URLs (one template per time), or video tiles
|
||||
* in segments, each a template whose tiles are videos spanning `start` to
|
||||
* `end` (epoch ms), a time within shown by its offset into the segment's
|
||||
* videos. Outside every segment, the nearest segment end is shown.
|
||||
*/
|
||||
export type TimedSource =
|
||||
| { kind: 'frames'; frames: TimedUrl[] }
|
||||
| {
|
||||
kind: 'video';
|
||||
segments: Array<{ url: string; start: number; end: number }>;
|
||||
};
|
||||
|
||||
export interface ImageryLayer {
|
||||
alpha: number;
|
||||
show: boolean;
|
||||
/** Which side of the split this layer shows on. */
|
||||
split: 'none' | 'left' | 'right';
|
||||
/**
|
||||
* What it drapes onto: the globe's surface (terrain or the ellipsoid),
|
||||
* objects (3D tiles and models; `imageryOnTiles`), or all of them. The
|
||||
* default `all` drapes on whichever is drawn, so under photoreal it is
|
||||
* on the tiles. Without `imageryOnTiles`, `objects` drapes on nothing and
|
||||
* `all` on the surface. So nothing drapes while the globe is hidden and
|
||||
* either photoreal's route is `none` or there is no `imageryOnTiles`:
|
||||
* The application reads that from what it set, with no event for it.
|
||||
*/
|
||||
drapeOn: 'surface' | 'objects' | 'all';
|
||||
/** Shaded by the sun like the surface (the default), or drawn unlit. */
|
||||
lit: boolean;
|
||||
/**
|
||||
* `imageryFrames`: a timed source, prefetched hidden. `clock: 'scene'`
|
||||
* (the default) shows the frame for the frame port's scene time;
|
||||
* `'own'` shows the one `setFrameTime` names.
|
||||
*/
|
||||
setFrames?(
|
||||
source: TimedSource,
|
||||
options?: {
|
||||
mode?: 'nearest' | 'blend';
|
||||
prefetch?: number;
|
||||
clock?: 'scene' | 'own';
|
||||
},
|
||||
): void;
|
||||
/** `imageryFrames`: which time to show, on the `own` clock. */
|
||||
setFrameTime?(ms: number): void;
|
||||
/**
|
||||
* `imageryFrames`: the frame the layer's clock now shows (by its time)
|
||||
* has been drawn. Fires once each time the shown frame changes, never
|
||||
* for frames only prefetched.
|
||||
*/
|
||||
on(event: 'frameReady', cb: (time: number) => void): Off;
|
||||
on(
|
||||
event: 'tileError',
|
||||
cb: (error: { tile: TileRequest; status?: number }) => void,
|
||||
): Off;
|
||||
raise(): void;
|
||||
lower(): void;
|
||||
remove(): void;
|
||||
}
|
||||
|
||||
export interface BaseSpec {
|
||||
photoreal?: PhotorealSpec | null;
|
||||
/** `vectorBase`: a vector basemap from a style document. */
|
||||
vector?: { styleUrl: string } | null;
|
||||
terrain?: TerrainSpec | null;
|
||||
imagery?: ImagerySpec[];
|
||||
credit?: Credit;
|
||||
}
|
||||
|
||||
export interface BaseStatus {
|
||||
photoreal: PhotorealStatus;
|
||||
imagery: ImageryLayer[];
|
||||
settled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sky. These switch parts of it on and off; they do not say how it
|
||||
* looks. How the sky, the atmosphere over the ground, distance haze, the
|
||||
* lighting and the tone mapping and exposure of the frame look is the
|
||||
* renderer's own, and no check compares colours. With `atmosphere`, `fog`
|
||||
* and `lighting` off and clear weather, the renderer applies none of its
|
||||
* look: what is drawn shows its own colours. Where the renderer's sun, moon
|
||||
* or fog are not separate from its atmosphere, it follows `atmosphere` for them and reports them as it draws them.
|
||||
*/
|
||||
export interface SkySettings {
|
||||
atmosphere: boolean;
|
||||
stars: boolean;
|
||||
/** Milky Way brightness, 0..1. */
|
||||
milkyWay: number;
|
||||
sun: boolean;
|
||||
moon: boolean;
|
||||
/** Distance fog, separate from atmosphere on models. */
|
||||
fog: boolean;
|
||||
/** Sun lighting of the globe and models. */
|
||||
lighting: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* `weather`: the conditions drawn around the view. Each strength is 0..1,
|
||||
* 0 drawing none of it; all are 0 at first. Clouds are a layer above the
|
||||
* ground that the camera can fly into and above; fog and haze thin what is
|
||||
* seen with distance, fog close in, haze far off; rain and snow fall around
|
||||
* the eye below the clouds and are not drawn from above them. A renderer
|
||||
* fades what makes no sense at the camera's height (rain from orbit) by
|
||||
* itself. None of it is picked or answers height queries. The application sets the
|
||||
* conditions observed at the view, which the user can override.
|
||||
*
|
||||
* The renderer draws these in its own way, as well as it can; the
|
||||
* strengths say what is observed, not how it is drawn. Clouds and
|
||||
* precipitation are where scene time (`frame.time()`) puts them, drifting
|
||||
* with `wind`: the same scene time draws the same sky, and moving scene time
|
||||
* moves them. Where the sun lights the globe (`SkySettings.lighting`),
|
||||
* clouds shade the ground and models under them.
|
||||
*/
|
||||
export interface WeatherSettings {
|
||||
/**
|
||||
* The fraction of the sky the clouds cover, as observed: 0 clear, about
|
||||
* 0.5 scattered to broken, 1 overcast. Under scattered cloud the ground
|
||||
* shows between the clouds, from below and from above.
|
||||
*/
|
||||
clouds: number;
|
||||
/** Fog: 1 is about 500 m visibility or less. */
|
||||
fog: number;
|
||||
/** Haze. */
|
||||
haze: number;
|
||||
/** Rain. */
|
||||
rain: number;
|
||||
/** Snow. */
|
||||
snow: number;
|
||||
/** What the clouds and precipitation drift with. */
|
||||
wind: {
|
||||
/** Metres per second. */
|
||||
speedMps: number;
|
||||
/** Where the wind blows from, degrees clockwise from north. */
|
||||
fromDeg: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* View-lit shading of the drawn terrain's own relief (the ellipsoid's
|
||||
* curvature where terrain has no normals); darkens only, at most
|
||||
* `strength` opacity.
|
||||
*/
|
||||
export type SurfaceShading = { kind: 'hillshade'; strength: number };
|
||||
|
||||
export interface LoadProgress {
|
||||
tilesPending: number;
|
||||
imageryPending: number;
|
||||
terrainPending: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* `surface`: what `against: 'surface'` heights answer from has loaded what
|
||||
* is in view: the terrain while the globe is shown, otherwise the drawn
|
||||
* tiles; false when neither is drawn.
|
||||
*/
|
||||
export type SettleKind = 'base' | 'tiles' | 'terrain' | 'imagery' | 'surface';
|
||||
|
||||
export interface GlobePort {
|
||||
/**
|
||||
* Switch the whole base at once; resolves when the new base has settled.
|
||||
* The last call wins: one a later `setBase` (or the renderer's disposal)
|
||||
* overtakes before its base changes (its vector style still loading)
|
||||
* changes nothing and resolves with `imagery: []`, `settled: false` and the
|
||||
* photoreal status as it stands, never rejecting.
|
||||
*
|
||||
* `settled` describes the moment the call resolves: true when its base is
|
||||
* still the one drawn (no later call has changed the base since) and has
|
||||
* settled. A later call only changes the base once its style has loaded,
|
||||
* so for a call A overtaken by a call B:
|
||||
* - A resolves before B changes the base (B's style still loading): A's
|
||||
* base is the one drawn, so `settled: true`; B then replaces it and
|
||||
* answers for itself.
|
||||
* - B changes the base before A resolves: `settled: false`.
|
||||
* - B's style fails (B rejects): the base stays A's, so A resolves with
|
||||
* `settled: true` whenever it resolves.
|
||||
* Only the latest call's answer says what is drawn once every call is done.
|
||||
*/
|
||||
setBase(base: BaseSpec): Promise<BaseStatus>;
|
||||
/** `photoreal`: on, off or a new token route. */
|
||||
setPhotoreal(spec: PhotorealSpec | null): Promise<PhotorealStatus>;
|
||||
setTerrain(spec: TerrainSpec | null): Promise<void>;
|
||||
/** Show or hide the globe surface (hidden under photoreal). */
|
||||
setGlobeVisible(visible: boolean): void;
|
||||
/**
|
||||
* `globeVisibility`: whether the globe surface is shown now, as
|
||||
* `setGlobeVisible` or whoever last set it left it. For code that only holds
|
||||
* the scene and must know whether the surface it drapes on or samples is
|
||||
* drawn.
|
||||
*/
|
||||
isGlobeVisible?(): boolean;
|
||||
/**
|
||||
* `surfaceIdentity`: a number that changes whenever what heights answer
|
||||
* against changes (base, terrain or photoreal route swapped, the globe
|
||||
* shown or hidden) and never otherwise (not on camera moves or tile
|
||||
* loads). The application keys cached surface heights by it.
|
||||
*/
|
||||
surfaceVersion?(): number;
|
||||
/** `surfaceShading`. */
|
||||
setSurfaceShading?(shading: SurfaceShading | null): void;
|
||||
readonly imagery: {
|
||||
/**
|
||||
* Without `imageHooks`, a spec with `tileTransform`, `admit` or kind
|
||||
* `canvas` throws, rather than drawing tiles the hooks were meant to
|
||||
* change.
|
||||
*/
|
||||
add(spec: ImagerySpec, index?: number): ImageryLayer;
|
||||
list(): ImageryLayer[];
|
||||
/** `splitSwipe`: split position, a fraction of the canvas's CSS width. */
|
||||
getSplit?(): number;
|
||||
/** `splitSwipe`: move the split to `x01` of the canvas's CSS width. */
|
||||
setSplit?(x01: number): void;
|
||||
};
|
||||
readonly sky: {
|
||||
get(): SkySettings;
|
||||
set(settings: Partial<SkySettings>): void;
|
||||
};
|
||||
/**
|
||||
* `weather`. `set` keeps each strength it is not given or given as no
|
||||
* number, clamps the others to 0..1, and asks for a frame. `wind` is taken
|
||||
* whole: a speed below 0 or missing is 0, the direction is wrapped into
|
||||
* [0, 360) and a missing one is 0. `get` answers a copy of what was set;
|
||||
* at first every strength and the wind speed are 0 (`CLEAR_WEATHER` in
|
||||
* `src/render/weather.js`, whose `mergeWeather` is these rules).
|
||||
*/
|
||||
readonly weather?: {
|
||||
get(): WeatherSettings;
|
||||
set(settings: Partial<WeatherSettings>): void;
|
||||
};
|
||||
/** Whether that part of the base has finished loading what is in view. */
|
||||
isSettled(kind: SettleKind): boolean;
|
||||
on(event: 'progress', cb: (progress: LoadProgress) => void): Off;
|
||||
}
|
||||
Vendored
+69
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* The renderer contract: what the application asks of a renderer, typed
|
||||
* one file per port.
|
||||
*/
|
||||
export * from './common';
|
||||
export * from './renderer';
|
||||
export * from './frame';
|
||||
export * from './globe';
|
||||
export * from './draw';
|
||||
export * from './camera';
|
||||
export * from './query';
|
||||
export * from './input';
|
||||
export * from './effects';
|
||||
export * from './credits';
|
||||
export * from './quality';
|
||||
|
||||
/** Every capability a renderer may list. */
|
||||
export declare const CAPABILITIES: readonly import('./common').Capability[];
|
||||
|
||||
/** The contract version this module describes. */
|
||||
export declare const CONTRACT_VERSION: import('./renderer').ContractVersion;
|
||||
|
||||
/** One port's members: null when required, else the capability that adds it. */
|
||||
export type PortDescriptor = Readonly<
|
||||
Record<string, import('./common').Capability | null>
|
||||
>;
|
||||
|
||||
/** Every port's members, by port name. */
|
||||
export declare const PORTS: Readonly<Record<string, PortDescriptor>>;
|
||||
|
||||
/** One of the roles a renderer plays, and the members that make it up. */
|
||||
export interface ContractRole {
|
||||
readonly id: 'surface' | 'scene' | 'view' | 'queries' | 'look' | 'host';
|
||||
readonly title: string;
|
||||
readonly summary: string;
|
||||
/** `port` or `port.member`; the most specific entry wins. */
|
||||
readonly members: readonly string[];
|
||||
}
|
||||
|
||||
/** What a renderer does, by role: every member of {@link PORTS} in one. */
|
||||
export declare const ROLES: readonly ContractRole[];
|
||||
|
||||
/**
|
||||
* The role of `port`'s `member` (dotted), or of the port itself without one;
|
||||
* undefined for a member the port does not have.
|
||||
*/
|
||||
export declare function roleOf(
|
||||
port: string,
|
||||
member?: string,
|
||||
): ContractRole['id'] | undefined;
|
||||
|
||||
/** Every quality setting a renderer may support. */
|
||||
export declare const QUALITY_KEYS: readonly import('./quality').QualityKey[];
|
||||
|
||||
/** The phases and steps of one frame, in order. */
|
||||
export declare const FRAME_STEPS: readonly import('./frame').FrameStep[];
|
||||
|
||||
/**
|
||||
* What a renderer is missing against the contract: each required member it
|
||||
* lacks, and each capability-gated member present without its capability.
|
||||
*/
|
||||
export declare function checkRendererShape(renderer: unknown): string[];
|
||||
|
||||
/** What one port (or handed-out shape) is missing against its descriptor. */
|
||||
export declare function checkPortShape(
|
||||
target: object,
|
||||
port: string,
|
||||
capabilities: ReadonlySet<string>,
|
||||
): string[];
|
||||
@@ -0,0 +1,467 @@
|
||||
/**
|
||||
* @module render/contract
|
||||
* @description The renderer contract at run time: the capability flags, every
|
||||
* port's members, and a shape check. The types live beside this file
|
||||
* (`index.d.ts` and one `.d.ts` per port); `contract.test.mjs` keeps
|
||||
* {@link PORTS} and those types in step, member for member.
|
||||
*
|
||||
* A member is required (`null`) or added by a capability: a renderer without
|
||||
* that capability leaves the member out.
|
||||
*/
|
||||
|
||||
/** @type {import('./index').ContractVersion} */
|
||||
export const CONTRACT_VERSION = '0';
|
||||
|
||||
/** @type {readonly import('./common').Capability[]} */
|
||||
export const CAPABILITIES = Object.freeze([
|
||||
'photoreal',
|
||||
'vectorBase',
|
||||
'finestHeights',
|
||||
'terrain',
|
||||
'modelAtmosphere',
|
||||
'weather',
|
||||
'imageryOnTiles',
|
||||
'splitSwipe',
|
||||
'imageryFrames',
|
||||
'surfaceShading',
|
||||
'surfaceIdentity',
|
||||
'imageHooks',
|
||||
'screenModulation',
|
||||
'gpuTiming',
|
||||
'pickPosition',
|
||||
'sampleHeight',
|
||||
'rayCast',
|
||||
'columns',
|
||||
'motionSegments',
|
||||
'models',
|
||||
'quads',
|
||||
'meshes',
|
||||
'fields',
|
||||
'courseGlide',
|
||||
'cluster',
|
||||
'styles',
|
||||
'bloom',
|
||||
'sharpen',
|
||||
'followAutodetect',
|
||||
'globeVisibility',
|
||||
'followFrame',
|
||||
'cameraChangeThreshold',
|
||||
'occlusionTest',
|
||||
'keepEarthFramed',
|
||||
]);
|
||||
|
||||
/** @type {readonly import('./frame').FrameStep[]} */
|
||||
export const FRAME_STEPS = Object.freeze([
|
||||
'flight',
|
||||
'input',
|
||||
'changed',
|
||||
'follow',
|
||||
'preUpdate',
|
||||
'moveDetection',
|
||||
'preRender',
|
||||
'render',
|
||||
'postRender',
|
||||
]);
|
||||
|
||||
/** Every quality setting a renderer may support. */
|
||||
export const QUALITY_KEYS = Object.freeze([
|
||||
'pixelRatio',
|
||||
'msaa',
|
||||
'tiles3dDetail',
|
||||
'terrainDetail',
|
||||
'imageryDetail',
|
||||
'tilesCacheBytes',
|
||||
'shadows',
|
||||
'atmosphere',
|
||||
'milkyWay',
|
||||
'particles',
|
||||
'models',
|
||||
'postFx',
|
||||
'targetFps',
|
||||
]);
|
||||
|
||||
const required = (...names) => names.map((name) => [name, null]);
|
||||
|
||||
/**
|
||||
* Every port's members. Nested members are dotted (`imagery.add`); the
|
||||
* instance shapes a port hands out (`drawSet`, `imageryLayer`, `flight`,
|
||||
* `lease`) are listed as their own entries.
|
||||
* @type {Readonly<Record<string, Readonly<Record<string, import('./common').Capability|null>>>>}
|
||||
*/
|
||||
export const PORTS = deepFreeze({
|
||||
renderer: Object.fromEntries(
|
||||
required(
|
||||
'id',
|
||||
'contractVersion',
|
||||
'capabilities',
|
||||
'canvas',
|
||||
'frame',
|
||||
'globe',
|
||||
'draw',
|
||||
'camera',
|
||||
'query',
|
||||
'input',
|
||||
'effects',
|
||||
'credits',
|
||||
'quality',
|
||||
'capture',
|
||||
'readPixels',
|
||||
'whenSettled',
|
||||
'resize',
|
||||
'releaseUnused',
|
||||
'on',
|
||||
'destroy',
|
||||
),
|
||||
),
|
||||
frame: Object.fromEntries(
|
||||
required(
|
||||
'on',
|
||||
'requestRender',
|
||||
'holdContinuous',
|
||||
'mode',
|
||||
'diagnostics',
|
||||
'suspend',
|
||||
'renderNow',
|
||||
'renderOnce',
|
||||
'setTargetFps',
|
||||
'setTime',
|
||||
'time',
|
||||
),
|
||||
),
|
||||
globe: Object.fromEntries([
|
||||
...required(
|
||||
'setBase',
|
||||
'setPhotoreal',
|
||||
'setTerrain',
|
||||
'setGlobeVisible',
|
||||
'imagery',
|
||||
'imagery.add',
|
||||
'imagery.list',
|
||||
'sky',
|
||||
'sky.get',
|
||||
'sky.set',
|
||||
'isSettled',
|
||||
'on',
|
||||
),
|
||||
['isGlobeVisible', 'globeVisibility'],
|
||||
['surfaceVersion', 'surfaceIdentity'],
|
||||
['setSurfaceShading', 'surfaceShading'],
|
||||
['imagery.getSplit', 'splitSwipe'],
|
||||
['imagery.setSplit', 'splitSwipe'],
|
||||
['weather', 'weather'],
|
||||
['weather.get', 'weather'],
|
||||
['weather.set', 'weather'],
|
||||
]),
|
||||
draw: Object.fromEntries([
|
||||
...required(
|
||||
'icons',
|
||||
'points',
|
||||
'lines',
|
||||
'shapes',
|
||||
'atlas',
|
||||
'clampState',
|
||||
'on',
|
||||
),
|
||||
['models', 'models'],
|
||||
['quads', 'quads'],
|
||||
['meshes', 'meshes'],
|
||||
['field', 'fields'],
|
||||
]),
|
||||
camera: Object.fromEntries([
|
||||
...required(
|
||||
'pose',
|
||||
'setView',
|
||||
'setFov',
|
||||
'viewRectangle',
|
||||
'flyTo',
|
||||
'flyToBounds',
|
||||
'cancelFlight',
|
||||
'flying',
|
||||
'lookAt',
|
||||
'release',
|
||||
'follow',
|
||||
'followed',
|
||||
'followFramed',
|
||||
'followOffset',
|
||||
'followOffset.get',
|
||||
'followOffset.set',
|
||||
'controls',
|
||||
'controls.enabled',
|
||||
'controls.suspend',
|
||||
'controls.enableTilt',
|
||||
'controls.enableRotate',
|
||||
'controls.enableZoom',
|
||||
'controls.minDistance',
|
||||
'controls.maxDistance',
|
||||
'controls.coast',
|
||||
'controls.coast.drag',
|
||||
'controls.coast.zoom',
|
||||
'controls.collision',
|
||||
'controls.zoomFactor',
|
||||
'controls.pitchRange',
|
||||
'controls.zoomInputs',
|
||||
'on',
|
||||
'onCommand',
|
||||
'matrices',
|
||||
),
|
||||
['followFrame', 'followFrame'],
|
||||
['controls.keepEarthFramed', 'keepEarthFramed'],
|
||||
]),
|
||||
query: Object.fromEntries([
|
||||
...required(
|
||||
'pick',
|
||||
'drillPick',
|
||||
'pickPosition',
|
||||
'pickEllipsoid',
|
||||
'pickGlobe',
|
||||
'pickRay',
|
||||
'project',
|
||||
'projectMany',
|
||||
'isOccluded',
|
||||
'sampleHeightNow',
|
||||
'sampleHeight',
|
||||
'clampToSurface',
|
||||
'rayCast',
|
||||
),
|
||||
['occlusionTest', 'occlusionTest'],
|
||||
]),
|
||||
input: Object.fromEntries(
|
||||
required(
|
||||
'on',
|
||||
'claimPointer',
|
||||
'isPointerFree',
|
||||
'suspendCameraControls',
|
||||
'behaviours',
|
||||
'behaviours.select',
|
||||
'behaviours.select.enabled',
|
||||
'behaviours.select.suppress',
|
||||
'behaviours.dblclickFollow',
|
||||
'behaviours.dblclickFollow.enabled',
|
||||
'behaviours.dblclickFollow.suppress',
|
||||
),
|
||||
),
|
||||
effects: Object.fromEntries([
|
||||
...required(
|
||||
'styles',
|
||||
'defineStyle',
|
||||
'setStyle',
|
||||
'setStyleIntensity',
|
||||
'setStyleParams',
|
||||
'bloom',
|
||||
'sharpen',
|
||||
'diagnostics',
|
||||
'on',
|
||||
),
|
||||
['screenModulation', 'screenModulation'],
|
||||
]),
|
||||
credits: Object.fromEntries(required('addStatic', 'list', 'on')),
|
||||
quality: Object.fromEntries(
|
||||
required(
|
||||
'knobs',
|
||||
'get',
|
||||
'set',
|
||||
'device',
|
||||
'probe',
|
||||
'signals',
|
||||
'signals.gpuTiming',
|
||||
'signals.on',
|
||||
),
|
||||
),
|
||||
drawSet: Object.fromEntries([
|
||||
...required(
|
||||
'id',
|
||||
'set',
|
||||
'upsert',
|
||||
'remove',
|
||||
'clear',
|
||||
'setOptions',
|
||||
'size',
|
||||
'show',
|
||||
'on',
|
||||
'dispose',
|
||||
),
|
||||
['setColumns', 'columns'],
|
||||
]),
|
||||
imageryLayer: Object.fromEntries([
|
||||
...required(
|
||||
'alpha',
|
||||
'show',
|
||||
'split',
|
||||
'drapeOn',
|
||||
'lit',
|
||||
'on',
|
||||
'raise',
|
||||
'lower',
|
||||
'remove',
|
||||
),
|
||||
['setFrames', 'imageryFrames'],
|
||||
['setFrameTime', 'imageryFrames'],
|
||||
]),
|
||||
flight: Object.fromEntries(required('done', 'cancel')),
|
||||
lease: Object.fromEntries(required('owner', 'current', 'release')),
|
||||
});
|
||||
|
||||
/**
|
||||
* What a renderer does, by role rather than by port. A renderer is more than
|
||||
* a drawing surface: it streams and builds the Earth from map sources, draws
|
||||
* the application's data as keyed sets, moves the camera, answers questions
|
||||
* about the world, applies the look, and runs the frame. The application owns the data
|
||||
* (providers, records, layers); the renderer owns everything from a source
|
||||
* spec or a draw set down to the pixels.
|
||||
*
|
||||
* Each role lists the members it covers as `port` (all of a port) or
|
||||
* `port.member` (that member and the members under it); the most specific
|
||||
* entry wins, so every member of {@link PORTS} has exactly one role
|
||||
* ({@link roleOf}). The roles describe the contract; they change no member.
|
||||
* @type {readonly import('./index').ContractRole[]}
|
||||
*/
|
||||
export const ROLES = deepFreeze([
|
||||
{
|
||||
id: 'surface',
|
||||
// i18n-ignore: developer documentation of the contract, never shown in the app
|
||||
title: 'The Earth',
|
||||
summary:
|
||||
'Streams, decodes and builds the globe from map sources: base imagery, terrain, photoreal 3D tiles and draped imagery layers (frames, split), with their credits and loading state.',
|
||||
members: ['globe', 'imageryLayer', 'credits'],
|
||||
},
|
||||
{
|
||||
id: 'scene',
|
||||
// i18n-ignore: developer documentation of the contract, never shown in the app
|
||||
title: 'Scene contents',
|
||||
summary:
|
||||
"Draws the application's data as keyed, retained sets: icons, points, lines, shapes, models, quads, meshes and fields, clamped to the surface where asked.",
|
||||
members: ['draw', 'drawSet'],
|
||||
},
|
||||
{
|
||||
id: 'view',
|
||||
// i18n-ignore: developer documentation of the contract, never shown in the app
|
||||
title: 'Camera and input',
|
||||
summary:
|
||||
'Places and moves the camera (views, flights, follow, user controls) and hands pointer input to the application.',
|
||||
members: ['camera', 'flight', 'input', 'lease'],
|
||||
},
|
||||
{
|
||||
id: 'queries',
|
||||
// i18n-ignore: developer documentation of the contract, never shown in the app
|
||||
title: 'World queries',
|
||||
summary:
|
||||
'Answers questions about what is drawn: picks, surface positions and heights, rays, projection and occlusion.',
|
||||
members: ['query'],
|
||||
},
|
||||
{
|
||||
id: 'look',
|
||||
// i18n-ignore: developer documentation of the contract, never shown in the app
|
||||
title: 'Look',
|
||||
summary:
|
||||
'How the world is lit and finished: sky and atmosphere, surface shading, styles and screen effects.',
|
||||
members: [
|
||||
'effects',
|
||||
'globe.sky',
|
||||
'globe.weather',
|
||||
'globe.setSurfaceShading',
|
||||
'imageryLayer.lit',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'host',
|
||||
// i18n-ignore: developer documentation of the contract, never shown in the app
|
||||
title: 'Host and frame',
|
||||
summary:
|
||||
'The renderer itself: its canvas and life cycle, the frame loop and scene time, quality, capture and settling.',
|
||||
members: ['renderer', 'frame', 'quality'],
|
||||
},
|
||||
]);
|
||||
|
||||
/**
|
||||
* The role a member belongs to: the most specific {@link ROLES} entry naming
|
||||
* its port or one of its dotted prefixes.
|
||||
* @param {string} port
|
||||
* @param {string} [member] dotted, as in {@link PORTS}; empty for the port's own role
|
||||
* @returns {string|undefined} the role's id; undefined for a member the port does not have
|
||||
*/
|
||||
export function roleOf(port, member = '') {
|
||||
if (member && !(PORTS[port] && member in PORTS[port])) return undefined;
|
||||
const parts = member ? member.split('.') : [];
|
||||
for (let n = parts.length; n >= 0; n--) {
|
||||
const key = [port, ...parts.slice(0, n)].join('.');
|
||||
const role = ROLES.find((r) => r.members.includes(key));
|
||||
if (role) return role.id;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The ports a renderer object holds, by the key it holds them under. */
|
||||
const RENDERER_PORTS = [
|
||||
'frame',
|
||||
'globe',
|
||||
'draw',
|
||||
'camera',
|
||||
'query',
|
||||
'input',
|
||||
'effects',
|
||||
'credits',
|
||||
'quality',
|
||||
];
|
||||
|
||||
function deepFreeze(value) {
|
||||
for (const inner of Object.values(value))
|
||||
if (inner && typeof inner === 'object') deepFreeze(inner);
|
||||
return Object.freeze(value);
|
||||
}
|
||||
|
||||
function has(target, dotted) {
|
||||
let at = target;
|
||||
for (const key of dotted.split('.')) {
|
||||
if (at == null || (typeof at !== 'object' && typeof at !== 'function'))
|
||||
return false;
|
||||
if (!(key in at)) return false;
|
||||
at = at[key];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* What `target` is missing against one descriptor, and what it has that its
|
||||
* capabilities do not allow.
|
||||
* @param {object} target
|
||||
* @param {string} port
|
||||
* @param {ReadonlySet<string>} capabilities
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function checkPortShape(target, port, capabilities) {
|
||||
const problems = [];
|
||||
for (const [member, capability] of Object.entries(PORTS[port])) {
|
||||
const present = has(target, member);
|
||||
if (capability === null) {
|
||||
if (!present) problems.push(`${port}.${member} is missing`);
|
||||
} else if (capabilities.has(capability) && !present) {
|
||||
problems.push(`${port}.${member} is missing with ${capability}`);
|
||||
} else if (!capabilities.has(capability) && present) {
|
||||
problems.push(`${port}.${member} is present without ${capability}`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a renderer is missing against the contract.
|
||||
* @param {unknown} renderer
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function checkRendererShape(renderer) {
|
||||
if (!renderer || typeof renderer !== 'object')
|
||||
return ['renderer is not an object'];
|
||||
const r = /** @type {any} */ (renderer);
|
||||
const capabilities = r.capabilities instanceof Set ? r.capabilities : null;
|
||||
if (!capabilities) return ['renderer.capabilities is not a Set'];
|
||||
const problems = [];
|
||||
for (const capability of capabilities)
|
||||
if (!CAPABILITIES.includes(capability))
|
||||
problems.push(`unknown capability ${capability}`);
|
||||
if (r.contractVersion !== CONTRACT_VERSION)
|
||||
problems.push(`contractVersion is ${r.contractVersion}`);
|
||||
problems.push(...checkPortShape(r, 'renderer', capabilities));
|
||||
for (const port of RENDERER_PORTS)
|
||||
if (r[port]) problems.push(...checkPortShape(r[port], port, capabilities));
|
||||
return problems;
|
||||
}
|
||||
Vendored
+133
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Pointer input over the scene, through one dispatcher.
|
||||
*
|
||||
* A tool takes the pointer with a lease; while a lease is out, ambient
|
||||
* subscribers (those without a lease) get only `move` and `up`: no presses,
|
||||
* clicks, double-clicks, wheel or pinch. A lease with `grab` takes only the
|
||||
* presses it grabs: `grab` is asked on each `down`, and a grabbed press (its
|
||||
* `down`, and the `click` and `dblclick` it ends in) goes to the lease's
|
||||
* listeners alone. Every other press, and wheel and pinch, go to ambient
|
||||
* subscribers and the camera as if the pointer were free; `move` and `up`
|
||||
* go to both.
|
||||
*
|
||||
* Every event of a press goes where its `down` went, even when the lease
|
||||
* ends or changes before the press is over (an ended lease's to no one), so
|
||||
* a claim never takes a press already under way. Each button's presses
|
||||
* are separate. A press runs from its `down` through its `up`, the `click`
|
||||
* straight after it where it went up, and a `dblclick` straight after that
|
||||
* at the same spot;
|
||||
* any other event after its `up` ends it. A click or double-click with no
|
||||
* press of its own is decided as a press, `grab` seeing it as a `down`
|
||||
* (without `pick`, `drill` or `ground`).
|
||||
*
|
||||
* Suspending camera input is separate and counted, and takes effect on the
|
||||
* same pointerdown that asked for it, so a tool that grabs a press suspends
|
||||
* the camera in its `down` listener.
|
||||
*
|
||||
* A click is delivered with its pick already made, once, and shared by
|
||||
* every subscriber (`PointerEv.pick`). Where the renderer's picks answer a
|
||||
* frame or two late, it delivers the click that much later rather than answering
|
||||
* without them; `query.pick` stays synchronous for everything else.
|
||||
*
|
||||
* The engine's stock behaviours (select on click, follow on double-click)
|
||||
* are explicit and removable here, never implicit.
|
||||
*/
|
||||
import type { Hit, PickWindow } from './query';
|
||||
import type { Ecef, Off, Release, ScreenXY } from './common';
|
||||
|
||||
export type PointerEventType =
|
||||
'down' | 'move' | 'up' | 'click' | 'dblclick' | 'wheel' | 'pinch';
|
||||
|
||||
export interface Modifiers {
|
||||
shift: boolean;
|
||||
ctrl: boolean;
|
||||
alt: boolean;
|
||||
meta: boolean;
|
||||
}
|
||||
|
||||
export interface PointerEv {
|
||||
type: PointerEventType;
|
||||
position: ScreenXY;
|
||||
/** For `move`: where the pointer is now (`position` is where it was). */
|
||||
endPosition?: ScreenXY;
|
||||
button: 0 | 1 | 2;
|
||||
modifiers: Modifiers;
|
||||
/** Event time, ms (`performance.now()` timeline). */
|
||||
timestamp: number;
|
||||
pointerType: 'mouse' | 'touch' | 'pen';
|
||||
/** `click`: how far the pointer travelled and how long the press lasted. */
|
||||
gesture?: { travelPx: number; durationMs: number };
|
||||
/**
|
||||
* `wheel`: lines scrolled, down positive, counted as the reference
|
||||
* renderer counts them: a pixel-mode wheel at 40 px a line, a page at 3
|
||||
* lines (so 40 px a line turns either back into the reference's pixels);
|
||||
* `pinch`: scale since the last event.
|
||||
*/
|
||||
delta?: number;
|
||||
/** `click` and `dblclick`: the hit under the pointer, picked once for every subscriber. */
|
||||
pick?(): Hit | null;
|
||||
/** `click` and `dblclick`: every hit under the pointer, from the same pick. */
|
||||
drill?(options?: PickWindow & { limit?: number }): Hit[];
|
||||
/** `click` and `dblclick`: the surface position under the pointer. */
|
||||
ground?(): Ecef | null;
|
||||
}
|
||||
|
||||
/** A tool's hold on the pointer. */
|
||||
export interface Lease {
|
||||
readonly owner: string;
|
||||
readonly current: boolean;
|
||||
release(): void;
|
||||
}
|
||||
|
||||
/** A stock behaviour, on until suppressed. */
|
||||
export interface StockBehaviour {
|
||||
readonly enabled: boolean;
|
||||
/** Turn it off until released. Holds are counted. */
|
||||
suppress(): Release;
|
||||
}
|
||||
|
||||
export interface InputPort {
|
||||
on(
|
||||
type: PointerEventType,
|
||||
cb: (ev: PointerEv) => void,
|
||||
options?: { lease?: Lease | (() => Lease | null) },
|
||||
): Off;
|
||||
/**
|
||||
* Take the pointer for a tool. The newest claim takes over: it ends the
|
||||
* previous lease, whose `onLost` is called once, after the new lease holds
|
||||
* the pointer, so that tool turns itself off (its button, a half-drawn
|
||||
* shape). A lease its holder releases, or that has already ended, is never
|
||||
* told, and releasing an ended lease frees nothing. An `onLost` that throws
|
||||
* is reported.
|
||||
* `grab` decides each press from its `down` event, synchronously: true
|
||||
* makes it the tool's, anything else leaves it. A `down` carries no pick,
|
||||
* so `grab` decides from the position, button and modifiers (and the
|
||||
* tool's own hit test, through `query`). Omitted, every press is the
|
||||
* tool's. A `grab` that throws is reported and leaves the press to the
|
||||
* others.
|
||||
*/
|
||||
claimPointer(
|
||||
owner: string,
|
||||
options?: {
|
||||
grab?: (down: PointerEv) => boolean;
|
||||
/** Called once when a newer claim ends this lease. */
|
||||
onLost?: () => void;
|
||||
},
|
||||
): Lease;
|
||||
isPointerFree(): boolean;
|
||||
/** Suspend user camera input until released. Holds are counted. */
|
||||
suspendCameraControls(reason: string): Release;
|
||||
/**
|
||||
* Every behaviour the renderer does on its own in answer to input, each
|
||||
* suppressible. `select` and `dblclickFollow` are always listed (a
|
||||
* renderer without one reports it disabled); any other built-in one (a
|
||||
* double-click zoom) is listed under its own name.
|
||||
*/
|
||||
readonly behaviours: {
|
||||
/** Select the item under a click. */
|
||||
readonly select: StockBehaviour;
|
||||
/** Follow the item under a double-click. */
|
||||
readonly dblclickFollow: StockBehaviour;
|
||||
readonly [name: string]: StockBehaviour;
|
||||
};
|
||||
}
|
||||
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* Adaptive quality. A governor above the contract decides a level; each
|
||||
* renderer reports its frame signals, lists the settings it supports and
|
||||
* applies them. Nothing here is engine-specific. Quality sets only how
|
||||
* detailed a thing is drawn; switching it on or off is the port's that
|
||||
* draws it (`globe.sky`, `effects`).
|
||||
*/
|
||||
import type { Off } from './common';
|
||||
|
||||
export interface QualitySettings {
|
||||
/** Absolute device pixel ratio for the scene; 0 = browser recommended. */
|
||||
pixelRatio: number;
|
||||
msaa: 0 | 2 | 4 | 8;
|
||||
/** 0..1: 3D tile detail (screen-space error, both directions). */
|
||||
tiles3dDetail: number;
|
||||
terrainDetail: number;
|
||||
imageryDetail: number;
|
||||
tilesCacheBytes: number;
|
||||
shadows: boolean;
|
||||
/** Detail of the atmosphere; whether it shows is `globe.sky`'s. */
|
||||
atmosphere: 'low' | 'high';
|
||||
/** Detail of the Milky Way; its brightness is `globe.sky`'s. */
|
||||
milkyWay: 'low' | 'high';
|
||||
/** 0..1 density of particle fields (wind, weather). */
|
||||
particles: number;
|
||||
models: { maxInstances: number; maxDistance: number };
|
||||
/** Detail of the post-processing passes; bloom and sharpen are switched in `effects`. */
|
||||
postFx: 'low' | 'high';
|
||||
targetFps: number;
|
||||
}
|
||||
|
||||
export type QualityKey = keyof QualitySettings;
|
||||
|
||||
export interface KnobDescriptor {
|
||||
key: QualityKey;
|
||||
kind: 'number' | 'boolean' | 'enum' | 'object';
|
||||
min?: number;
|
||||
max?: number;
|
||||
options?: readonly string[] | readonly number[];
|
||||
default: unknown;
|
||||
/** Relative cost, 0 (free) to 1 (the heaviest knob). */
|
||||
cost: number;
|
||||
/** Changing it recreates the drawing context. */
|
||||
recreates?: boolean;
|
||||
/** What else changing it affects (lower tile detail lowers height accuracy). */
|
||||
couples?: string[];
|
||||
}
|
||||
|
||||
export interface FrameSignals {
|
||||
cpuMs: number;
|
||||
/** `gpuTiming`. */
|
||||
gpuMs?: number;
|
||||
passes?: Record<string, number>;
|
||||
drawCalls?: number;
|
||||
commands?: number;
|
||||
tilesInFlight?: number;
|
||||
memory?: { gpuBytes?: number; tilesBytes?: number };
|
||||
pixelRatio: number;
|
||||
width: number;
|
||||
height: number;
|
||||
mode: 'demand' | 'continuous';
|
||||
/** This frame was asked for (not continuous). */
|
||||
requested: boolean;
|
||||
holds: string[];
|
||||
/** Spread of present intervals over the last second, ms. */
|
||||
presentJitterMs?: number;
|
||||
}
|
||||
|
||||
export interface DeviceFacts {
|
||||
backend: 'webgl1' | 'webgl2' | 'webgpu';
|
||||
gpuVendor?: string;
|
||||
gpuRenderer?: string;
|
||||
maxTextureSize: number;
|
||||
msaaSamples: number[];
|
||||
gpuTimer: boolean;
|
||||
}
|
||||
|
||||
export interface ProbeResult {
|
||||
device: DeviceFacts;
|
||||
browser: {
|
||||
devicePixelRatio: number;
|
||||
screen: { width: number; height: number };
|
||||
hardwareConcurrency?: number;
|
||||
deviceMemory?: number;
|
||||
touchOnly: boolean;
|
||||
};
|
||||
knobs: KnobDescriptor[];
|
||||
}
|
||||
|
||||
export interface QualityPort {
|
||||
/** The settings this renderer supports, with ranges, defaults and costs. */
|
||||
knobs(): KnobDescriptor[];
|
||||
get(): Partial<QualitySettings>;
|
||||
/** Applied at the next frame; returns the keys it ignored as unsupported. */
|
||||
set(settings: Partial<QualitySettings>): QualityKey[];
|
||||
device(): DeviceFacts;
|
||||
probe(): ProbeResult;
|
||||
readonly signals: {
|
||||
readonly gpuTiming: 'none' | 'frame' | 'perPass';
|
||||
on(event: 'frame', cb: (signals: FrameSignals) => void): Off;
|
||||
};
|
||||
}
|
||||
Vendored
+166
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Questions about what is on screen.
|
||||
*
|
||||
* Picks, projection and rays are synchronous and answer against the last
|
||||
* presented frame. Heights have a synchronous cache-only form that may
|
||||
* return null, and asynchronous forms that load what they need.
|
||||
*
|
||||
* Picks, depth picks and rays answer against the scene as drawn before
|
||||
* effects: a style that moves pixels does not move what is picked, so the application
|
||||
* maps a pointer through its own style before it picks.
|
||||
*/
|
||||
import type { Ecef, LonLat, Meta, Ray, ScreenXY } from './common';
|
||||
|
||||
/** One thing under the pointer. */
|
||||
export interface Hit {
|
||||
/** The draw set's id. */
|
||||
set: string;
|
||||
/** The item's id. */
|
||||
id: string;
|
||||
/** The item's `meta`, as it was given; absent when the item had none. */
|
||||
meta?: Meta;
|
||||
/** The map itself (tiles or globe), rather than a drawn item. */
|
||||
surface: boolean;
|
||||
/** Where the hit is, when the renderer knows it. */
|
||||
position?: Ecef;
|
||||
}
|
||||
|
||||
export interface PickWindow {
|
||||
/** Pick window, CSS pixels; default 3 × 3. */
|
||||
width?: number;
|
||||
height?: number;
|
||||
/**
|
||||
* What the pick is for. A hover pick may skip costly exact tests (a
|
||||
* point-in-polygon on a large fill) that a select pick must make.
|
||||
*/
|
||||
purpose?: 'hover' | 'select';
|
||||
}
|
||||
|
||||
export interface HeightOptions {
|
||||
/**
|
||||
* `surface`: tiles where they are drawn, otherwise terrain. Sets drawn
|
||||
* with `includeInHeightQueries` count under `surface` and `tiles`, never
|
||||
* under `terrain`.
|
||||
*/
|
||||
against?: 'surface' | 'terrain' | 'tiles';
|
||||
/** Set ids to see through, of those drawn with `includeInHeightQueries`. */
|
||||
exclude?: string[];
|
||||
}
|
||||
|
||||
export interface HeightSample {
|
||||
/** Metres above the ellipsoid. */
|
||||
height: number;
|
||||
/** 1 for the most detailed data, lower for a coarser level. */
|
||||
confidence: number;
|
||||
/** `set`: a draw set drawn with `includeInHeightQueries`. */
|
||||
source: 'tiles' | 'terrain' | 'ellipsoid' | 'set';
|
||||
/** The detail answered from: what is drawn now, or (`finestHeights`) the finest available. */
|
||||
lod: 'visible' | 'finest';
|
||||
/** Edge length of the tile answered from, metres, when known. */
|
||||
tileSizeM?: number;
|
||||
}
|
||||
|
||||
export interface QueryPort {
|
||||
pick(x: number, y: number, window?: PickWindow): Hit | null;
|
||||
/**
|
||||
* The pickable draw-set items under the pointer, nearest first, each once:
|
||||
* never the surface (`surface` is always false) and never anything that is
|
||||
* not a draw-set item. `limit`, a whole number of 0 or more, bounds the
|
||||
* work as well as the answer: the renderer stops at `limit` hits and
|
||||
* looks through at most `max(limit, 16)` things of any kind under the pointer that its picks
|
||||
* see (tiles, unpickable items it still picks, its own), so it may return
|
||||
* fewer than `limit` when more lie above them. Omitted: every item, at
|
||||
* whatever cost.
|
||||
*/
|
||||
drillPick(
|
||||
x: number,
|
||||
y: number,
|
||||
options?: PickWindow & { limit?: number },
|
||||
): Hit[];
|
||||
/** `pickPosition`: depth under the pointer, against tiles and terrain. */
|
||||
pickPosition(x: number, y: number): Ecef | null;
|
||||
pickEllipsoid(x: number, y: number): Ecef | null;
|
||||
/** Where a ray meets the globe surface (not tiles). */
|
||||
pickGlobe(ray: Ray): Ecef | null;
|
||||
/** Null while the canvas has no size (hidden, not laid out yet). */
|
||||
pickRay(x: number, y: number): Ray | null;
|
||||
/** Screen position, or null behind the eye (off-screen points still answer). */
|
||||
project(position: Ecef): ScreenXY | null;
|
||||
/**
|
||||
* Packed `x, y, z` in → packed `x, y` out, CSS pixels; NaN for points
|
||||
* behind the eye. For the label overlay's per-frame pass.
|
||||
*/
|
||||
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;
|
||||
/**
|
||||
* `sampleHeight`: heights, loading as needed; null per miss.
|
||||
* `mostDetailed` (`finestHeights`) waits for the finest data.
|
||||
*/
|
||||
sampleHeight(
|
||||
points: LonLat[],
|
||||
options?: HeightOptions & { mostDetailed?: boolean },
|
||||
): Promise<Array<HeightSample | null>>;
|
||||
/** `sampleHeight`: positions moved onto the surface; null per miss. */
|
||||
clampToSurface(
|
||||
positions: Ecef[],
|
||||
options?: HeightOptions,
|
||||
): Promise<Array<Ecef | null>>;
|
||||
/** `rayCast`: first surface hit along a ray. */
|
||||
rayCast(
|
||||
ray: Ray,
|
||||
options?: HeightOptions & { maxDistance?: number },
|
||||
): Promise<Ecef | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
Vendored
+187
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* The renderer itself: what a plugin creates and what the application holds.
|
||||
*
|
||||
* A renderer draws the globe and what the application asks it to draw, owns the camera,
|
||||
* and answers queries about what is on screen. The application keeps every record of
|
||||
* its own; it never reads a renderer to learn its own state, only what the
|
||||
* renderer itself measures (picks, depth, heights, readiness).
|
||||
*/
|
||||
import type { Capability, Off, ScreenRect } from './common';
|
||||
import type { CameraPort } from './camera';
|
||||
import type { CreditsPort } from './credits';
|
||||
import type { DrawPort } from './draw';
|
||||
import type { EffectsPort } from './effects';
|
||||
import type { FramePort } from './frame';
|
||||
import type { GlobePort, SkySettings } from './globe';
|
||||
import type { InputPort } from './input';
|
||||
import type { QualityPort } from './quality';
|
||||
import type { QueryPort } from './query';
|
||||
|
||||
/** The version of the contract this file describes. */
|
||||
export type ContractVersion = '0';
|
||||
|
||||
/** What the application is given to make a renderer. */
|
||||
export interface RendererPlugin {
|
||||
/** Stable id, recorded with each session (`'cesium'`, ...). */
|
||||
id: string;
|
||||
create(options: CreateOptions): Promise<Renderer>;
|
||||
/**
|
||||
* 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 the renderer's plugin hands the application beside the contract; the
|
||||
* application uses each where given and does without where not. None is a
|
||||
* contract member: what the renderer should 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<Record<string, unknown>>;
|
||||
/**
|
||||
* Show a recoverable notice when the renderer stops drawing (an error, a
|
||||
* lost context), with Retry and, if `allowReload`, Reset, by publishing it
|
||||
* to `store`. Returns its removal.
|
||||
*/
|
||||
renderFailureNotice?(options: {
|
||||
allowReload: boolean;
|
||||
store: RenderFailureStore;
|
||||
}): () => void;
|
||||
}
|
||||
|
||||
/** Where a renderer's failure notice is published for the application to show. */
|
||||
export interface RenderFailureStore {
|
||||
/** The notice shown now, or null. */
|
||||
readonly renderFailure: RenderFailureNotice | null;
|
||||
/** Show a notice, or none with null. */
|
||||
publishRenderFailure(next: RenderFailureNotice | null): void;
|
||||
}
|
||||
|
||||
/** A notice that the renderer stopped drawing. */
|
||||
export interface RenderFailureNotice {
|
||||
/** Why: an error in a frame, or a lost graphics context. */
|
||||
reason: 'render-error' | 'context-lost';
|
||||
/** The error's description, or empty. */
|
||||
detail: string;
|
||||
/** Draw again; after a lost context, reload the page. */
|
||||
retry(): void;
|
||||
/** Open the application's root address, or null where it must not. */
|
||||
reset: (() => void) | null;
|
||||
}
|
||||
|
||||
export interface CreateOptions {
|
||||
/** The element the renderer fills. It creates its own canvas inside. */
|
||||
container: HTMLElement;
|
||||
/** Google Maps Platform key for photorealistic tiles. */
|
||||
googleApiKey?: string;
|
||||
/** Short-lived Google session tokens, when the key is held server-side. */
|
||||
googleTokens?: () => Promise<string>;
|
||||
/**
|
||||
* The token for the renderer's world data: `world` terrain and imagery
|
||||
* and the photoreal `fallback`. For the default renderer, a Cesium ion
|
||||
* token.
|
||||
*/
|
||||
worldDataToken?: string;
|
||||
/** Initial multisampling; quality can change it later. */
|
||||
msaa?: 0 | 2 | 4 | 8;
|
||||
/** Sky applied before the first frame, so nothing draws in the wrong sky. */
|
||||
sky?: Partial<SkySettings>;
|
||||
/** Scene time in epoch ms. The application passes its boot time. */
|
||||
time?: number;
|
||||
/**
|
||||
* The clocks the renderer reads, for `FrameTime.now`, the camera's
|
||||
* `moveEnd` wait, input, flights and tweens, and for inertia where it
|
||||
* times that itself (Cesium's keeps Cesium's own timing): `now` on the
|
||||
* `performance.now()` timeline, `date` in epoch ms. Omitted: the
|
||||
* browser's. Tests pass virtual ones.
|
||||
*/
|
||||
clock?: { now(): number; date(): number };
|
||||
/** Aborts creation; the renderer cleans up whatever it had built. */
|
||||
signal: AbortSignal;
|
||||
}
|
||||
|
||||
export interface CaptureOptions {
|
||||
type?: 'png' | 'jpeg';
|
||||
/** JPEG quality, 0..1. */
|
||||
quality?: number;
|
||||
/** Output scale relative to the canvas's CSS size. */
|
||||
scale?: number;
|
||||
/** Part of the canvas, in CSS pixels. */
|
||||
crop?: ScreenRect;
|
||||
}
|
||||
|
||||
export interface SettleResult {
|
||||
state: 'settled' | 'timeout' | 'failed';
|
||||
blockers: string[];
|
||||
}
|
||||
|
||||
export interface Renderer {
|
||||
readonly id: string;
|
||||
readonly contractVersion: ContractVersion;
|
||||
readonly capabilities: ReadonlySet<Capability>;
|
||||
readonly canvas: HTMLCanvasElement;
|
||||
readonly frame: FramePort;
|
||||
readonly globe: GlobePort;
|
||||
readonly draw: DrawPort;
|
||||
readonly camera: CameraPort;
|
||||
readonly query: QueryPort;
|
||||
readonly input: InputPort;
|
||||
readonly effects: EffectsPort;
|
||||
readonly credits: CreditsPort;
|
||||
readonly quality: QualityPort;
|
||||
/**
|
||||
* The last presented frame as an encoded image. Once the renderer is
|
||||
* destroyed it rejects with a "renderer destroyed" error.
|
||||
*/
|
||||
capture(options?: CaptureOptions): Promise<Blob>;
|
||||
/**
|
||||
* The last presented frame's pixels, synchronously, for loops that render
|
||||
* a frame and read it at once (a share clip, a black-frame check). Call it
|
||||
* right after `frame.renderNow()`.
|
||||
*/
|
||||
readPixels(options?: { crop?: ScreenRect; scale?: number }): ImageData;
|
||||
/**
|
||||
* Resolves once what is in view has loaded and the last presented frame
|
||||
* shows it (no redraw of the renderer's own is pending), or the timeout
|
||||
* passes, or a load failed for good. `blockers` names what was still loading or
|
||||
* failed (`'tiles'`, `'imagery:<id>'`, `'models'`, ...); empty when settled.
|
||||
*/
|
||||
whenSettled(options?: { timeoutMs?: number }): Promise<SettleResult>;
|
||||
/** Follows the container's size. */
|
||||
resize(): void;
|
||||
/** Frees caches and GPU memory nothing in view uses. */
|
||||
releaseUnused(): void;
|
||||
on(event: 'error', cb: (error: Error) => void): Off;
|
||||
/**
|
||||
* The drawing context was lost, or came back. Where the renderer cannot
|
||||
* restore its context it never sends `contextRestored`; the application
|
||||
* then makes a new renderer.
|
||||
*/
|
||||
on(event: 'contextLost' | 'contextRestored', cb: () => void): Off;
|
||||
/**
|
||||
* Lets go of everything. Afterwards handles do nothing (`Handle`), and
|
||||
* `frame.renderOnce` and `capture` reject with a "renderer destroyed"
|
||||
* error, as does a `renderOnce` still waiting.
|
||||
*/
|
||||
destroy(): void;
|
||||
}
|
||||
Reference in new issue
Block a user