mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-04 10:24:02 +00:00
Merge pull request #1519 from manjunath22466/manjunath/hal-769-gev-ux-improve-visibility-of-the-250-km-radius-circle
feat(awareness): add calm sonar pulses that flash the range ring and echo contacts
This commit is contained in:
14 files changed
+2544
-74
No files matched your search
@@ -0,0 +1,8 @@
|
||||
- The Global Context range ring pulses like a sonar: three dim rings with a
|
||||
soft inward glow grow from the subject to 250 km, and the ring flashes as
|
||||
each one arrives. Flights, military aircraft and AIS vessels a pulse crosses
|
||||
get a brief echo around their brackets. The pulses run for about 9 s after
|
||||
a selection or camera move, dimming the ring between flashes, then rest
|
||||
with the ring steady on screen, so a parked view stops repainting. Under
|
||||
reduced motion there are no pulses and the ring stays on screen
|
||||
(manjunath22466, #1519).
|
||||
@@ -4997,7 +4997,7 @@ silently demoting every later lookup for the session.
|
||||
- Enabled Data Layer controls report normalized feed health on the button (`LOADING`, `DEGRADED`, `STALE`, `FALLBACK`, or `UNAVAILABLE`) while the metadata line retains the source and reason. A partial CelesTrak group failure keeps the usable catalog and reports `DEGRADED`; a total outage keeps last-good catalog data visible but reports `UNAVAILABLE`.
|
||||
- On activation it focuses the nearest currently observed aircraft across the civilian and military feeds, with military winning an exact distance tie; if none are available, it focuses an observed AIS vessel. The aircraft search is deliberately uncapped and one refresh-tick retry handles initially empty feeds. This is an attention-priority navigation shortcut, not a high-risk, affiliation, or threat classification.
|
||||
- A selected aircraft, AIS vessel, or mapped installation gets a 250 km **context window** with nearby cohort counts, nearest examples, source labels, and stale/unavailable reasons. It emits `NEARBY` or `UNKNOWN`; no detection, engagement, affiliation, or sensor-activity conclusion is calculated.
|
||||
- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline with a 2 px Context-blue core inside a 1 px dark halo on each side, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is a polyline because WebGL draws ellipse outlines at 1 px whatever width is asked for. The ring follows a moving subject once it has moved 250 m.
|
||||
- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline with a 2 px Context-blue core inside a 1 px dark halo on each side, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is a polyline because WebGL draws ellipse outlines at 1 px whatever width is asked for, drawn as an unpickable primitive rather than an entity so a click or tap on its edge reaches the contact underneath (headless viewers without a primitive collection get a static entity instead); it is rebuilt when the subject moves. Three dim sonar pulses (3 px with a 1 px dark outline, same colours, at most 60% opacity) grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius. One unpickable 250 km disc draws both the pulse lines and the gradient, its shader reading the pulse radii and opacities each frame, so a click or tap near a pulse still reaches the contact underneath; the disc follows the subject by a model-matrix rotation and is rebuilt only after the subject moves 20 km, and not at all while the pulses rest. While the camera is below the disc's 2.5 km height, where it would sweep across the sky, the pulses rest: the disc is hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the disc and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one render request 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`), so they repaint at about 12.5 fps and never beat the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or in a scene without primitives or preRender and postRender hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m.
|
||||
- For a selected live aircraft or vessel, the context window refreshes from the existing tracker/feed position every 750 ms, so nearest distances and cohort counts follow the subject without introducing a duplicate poll loop.
|
||||
- Aircraft cohort membership uses every locally loaded, selectable contact inside the 250 km window, including a plane hidden only by horizon culling or because its 3D model owns the visual. Counts and navigation therefore do not change with the current camera angle or billboard/model handoff.
|
||||
- Nearby examples in the context panel are focus controls: they use their owning layer's existing selection/tracking path, then frame that contact. Static-installation distances use ellipsoidal surface distance so the count matches the ground-projected context disk.
|
||||
|
||||
@@ -1184,6 +1184,9 @@
|
||||
"src/overlays/worldOverlayActionsView.test.mjs",
|
||||
"src/ui/stores/awarenessDirection.js",
|
||||
"src/layers/awareness/directionOverlay.test.mjs",
|
||||
"src/awarenessEcho.js",
|
||||
"src/awarenessEcho.test.mjs",
|
||||
"src/data/detectionAwarenessEcho.test.mjs",
|
||||
"src/hudReadouts.js",
|
||||
"src/ui/stores/hud.js",
|
||||
"src/ui/views/intelHudView.test.mjs",
|
||||
|
||||
@@ -1684,6 +1684,7 @@
|
||||
"src/data/distanceFormat.js",
|
||||
"src/i18n/marker.js",
|
||||
"src/cyberSonar.js",
|
||||
"src/awarenessEcho.js",
|
||||
"src/cockpitMath.js",
|
||||
"src/data/iconOrientation.js",
|
||||
"src/data/militaryAwarenessEngine.js",
|
||||
@@ -2234,6 +2235,7 @@
|
||||
"src/ui/placeNames.js",
|
||||
"src/cyberSonarScene.js",
|
||||
"src/cyberSonar.js",
|
||||
"src/awarenessEcho.js",
|
||||
"src/hudLayouts.js",
|
||||
"src/hudLayoutPolicy.js",
|
||||
"src/ui/radioPanelPlacement.js",
|
||||
@@ -3233,6 +3235,7 @@
|
||||
"src/data/headingDegrees.js",
|
||||
"src/data/distanceFormat.js",
|
||||
"src/cyberSonar.js",
|
||||
"src/awarenessEcho.js",
|
||||
"src/data/approxDistance.js",
|
||||
"src/data/bhoteKoshiEvent.js",
|
||||
"src/ui/imagerySplit.js",
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* @module awarenessEcho
|
||||
* @description The Global Context sonar echo field. The awareness layer
|
||||
* publishes it while its range pulses run; the detection overlay reads it to
|
||||
* pulse the brackets of contacts a pulse front has just crossed. It holds no
|
||||
* awareness policy of its own: the publisher passes radius, pulse timing and
|
||||
* echo styling in, so the overlay never imports awareness internals.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/**
|
||||
* @typedef {object} AwarenessEchoField
|
||||
* @property {Cesium.Cartesian3} center Subject's ground point. The publisher
|
||||
* may move it in place; it is read on every query.
|
||||
* @property {number} radiusM Range the pulses grow to.
|
||||
* @property {{count: number, periodMs: number, startFraction: number, fadeInFraction?: number}} pulse
|
||||
* @property {{fadeMs: number, layerIds: string[]}} echo
|
||||
* @property {(nowMs: number) => number} [level] How far the pulses are
|
||||
* switched on, 0 to 1; echoes scale with it, so they rest with the pulses.
|
||||
*/
|
||||
|
||||
/** @type {AwarenessEchoField|null} */
|
||||
let field = null;
|
||||
let layerIds = new Set();
|
||||
const groundScratch = new Cesium.Cartesian3();
|
||||
|
||||
/**
|
||||
* Start (or replace) the echo field.
|
||||
* @param {AwarenessEchoField} next
|
||||
* @returns {void}
|
||||
*/
|
||||
export function setAwarenessEchoField(next) {
|
||||
field = next;
|
||||
layerIds = new Set(next.echo.layerIds);
|
||||
}
|
||||
|
||||
/** Stop all echoes. Safe when none were set. */
|
||||
export function clearAwarenessEchoField() {
|
||||
field = null;
|
||||
layerIds = new Set();
|
||||
}
|
||||
|
||||
/** @returns {AwarenessEchoField|null} The field the overlay styles from. */
|
||||
export function getAwarenessEchoField() {
|
||||
return field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether any echo can light at `nowMs`: a field is set and its pulses are
|
||||
* running. The overlay checks this once per frame, so resting pulses cost no
|
||||
* per-contact work.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function awarenessEchoActive(nowMs) {
|
||||
return Boolean(field) && (field.level?.(nowMs) ?? 1) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* How lit a contact's echo is at `nowMs`: 1 the moment a pulse front reaches
|
||||
* its distance, fading as (1 - elapsed / `fadeMs`) squared, 0 otherwise. The
|
||||
* strongest pulse wins. A front that has wrapped back to the centre still
|
||||
* counts for the contact it last crossed, so rim contacts fade out instead of
|
||||
* cutting off. Nothing nearer than the birth ring `startFraction` out echoes,
|
||||
* and within the pulse's `fadeInFraction` the echo is scaled down with it.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {number} distanceM Contact's distance from the subject.
|
||||
* @param {number} radiusM Range the pulses grow to.
|
||||
* @param {{count: number, periodMs: number, startFraction: number, fadeInFraction?: number}} pulse
|
||||
* @param {{fadeMs: number}} echo
|
||||
* @returns {number} 0 to 1.
|
||||
*/
|
||||
export function awarenessEchoStrength(nowMs, distanceM, radiusM, pulse, echo) {
|
||||
// Pulses are born `startFraction` out, so nothing nearer (the subject
|
||||
// itself, its wingmen) is ever crossed; without this it lit on every birth.
|
||||
if (
|
||||
!Number.isFinite(distanceM) ||
|
||||
distanceM < radiusM * pulse.startFraction ||
|
||||
distanceM > radiusM
|
||||
)
|
||||
return 0;
|
||||
// The phase at which a pulse front sits at this distance.
|
||||
const touchPhase =
|
||||
(distanceM / radiusM - pulse.startFraction) / (1 - pulse.startFraction);
|
||||
let strength = 0;
|
||||
for (let index = 0; index < pulse.count; index++) {
|
||||
const cycle = nowMs / pulse.periodMs + index / pulse.count;
|
||||
let since = cycle - Math.floor(cycle) - touchPhase;
|
||||
// Rounding at the exact crossing must not read as a whole period ago.
|
||||
if (since < -1e-9) since += 1;
|
||||
else if (since < 0) since = 0;
|
||||
const elapsedMs = since * pulse.periodMs;
|
||||
if (elapsedMs < echo.fadeMs)
|
||||
strength = Math.max(strength, (1 - elapsedMs / echo.fadeMs) ** 2);
|
||||
}
|
||||
// A front still fading in over `fadeInFraction` of its travel echoes no
|
||||
// brighter than it shows.
|
||||
const fadeIn = pulse.fadeInFraction ?? 0;
|
||||
return fadeIn > 0 ? strength * Math.min(1, touchPhase / fadeIn) : strength;
|
||||
}
|
||||
|
||||
/**
|
||||
* The echo for one contact of `layerId` at world `position`, or 0 when no
|
||||
* field is set or the layer does not echo. Distance is measured between
|
||||
* ground points, so an aircraft's altitude does not shift its echo.
|
||||
* @param {string} layerId Owning layer of the contact.
|
||||
* @param {Cesium.Cartesian3} position Contact's world position.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @returns {number} 0 to 1.
|
||||
*/
|
||||
export function awarenessEchoAt(layerId, position, nowMs) {
|
||||
if (!field || !position || !layerIds.has(layerId)) return 0;
|
||||
const level = field.level?.(nowMs) ?? 1;
|
||||
if (!(level > 0)) return 0;
|
||||
const ground = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(
|
||||
position,
|
||||
groundScratch,
|
||||
);
|
||||
if (!ground) return 0;
|
||||
return (
|
||||
level *
|
||||
awarenessEchoStrength(
|
||||
nowMs,
|
||||
Cesium.Cartesian3.distance(field.center, ground),
|
||||
field.radiusM,
|
||||
field.pulse,
|
||||
field.echo,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The echo bracket the detection overlay draws around one contact, or null
|
||||
* when it has no echo. `band` is the alpha band, 1 to `steps`, the echo's
|
||||
* strength times the contact bracket's own `bracketAlpha` rounded to the
|
||||
* nearest band, so an echo is never drawn brighter than its bracket; one
|
||||
* that rounds to nothing is not drawn. `spreadPx` is how far the echo sits
|
||||
* outside the contact's bracket, 0 as the front arrives, growing to the
|
||||
* field's `spreadPx` as it fades.
|
||||
* @param {string} layerId Owning layer of the contact.
|
||||
* @param {Cesium.Cartesian3} position Contact's world position.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {number} bracketAlpha The contact bracket's drawn alpha, 0 to 1.
|
||||
* @param {number} steps Alpha bands the overlay batches by.
|
||||
* @returns {{band: number, spreadPx: number}|null}
|
||||
*/
|
||||
export function awarenessEchoBracket(
|
||||
layerId,
|
||||
position,
|
||||
nowMs,
|
||||
bracketAlpha,
|
||||
steps,
|
||||
) {
|
||||
const echo = awarenessEchoAt(layerId, position, nowMs);
|
||||
if (!(echo > 0.01)) return null;
|
||||
const band = Math.min(steps, Math.round(echo * bracketAlpha * steps));
|
||||
if (!(band >= 1)) return null;
|
||||
return { band, spreadPx: field.echo.spreadPx * (1 - echo) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The echo's stroke colour: the field's own colour on the default detection
|
||||
* style, and the style's line colour under the others (NVG, FLIR, CRT), so
|
||||
* an echo never stands out of a monochrome palette.
|
||||
* @param {string} styleLine The active detection style's line colour.
|
||||
* @param {boolean} defaultStyle Whether the default detection style is active.
|
||||
* @returns {string|null} Null when no field is set.
|
||||
*/
|
||||
export function awarenessEchoColor(styleLine, defaultStyle) {
|
||||
if (!field) return null;
|
||||
return defaultStyle ? field.echo.color : styleLine;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
// src/awarenessEcho.test.mjs — the Global Context echo field: when a sonar
|
||||
// pulse front crosses a flight or vessel, its bracket echo lights and fades.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
awarenessEchoActive,
|
||||
awarenessEchoAt,
|
||||
awarenessEchoStrength,
|
||||
clearAwarenessEchoField,
|
||||
getAwarenessEchoField,
|
||||
setAwarenessEchoField,
|
||||
} from './awarenessEcho.js';
|
||||
|
||||
const R = 250_000;
|
||||
const pulse = { count: 3, periodMs: 9000, startFraction: 0.02 };
|
||||
const echo = { fadeMs: 1400, layerIds: ['flights', 'ais-live-vessels'] };
|
||||
const strength = (nowMs, distanceM) =>
|
||||
awarenessEchoStrength(nowMs, distanceM, R, pulse, echo);
|
||||
/** The moment pulse 0's front sits at `distanceM`, in a later cycle. */
|
||||
const arrival = (distanceM) =>
|
||||
((distanceM / R - pulse.startFraction) / (1 - pulse.startFraction)) *
|
||||
pulse.periodMs +
|
||||
pulse.periodMs * 4;
|
||||
|
||||
test('an echo lights as a pulse front reaches the contact, then fades', () => {
|
||||
const d = 100_000;
|
||||
const t0 = arrival(d);
|
||||
assert.ok(Math.abs(strength(t0, d) - 1) < 1e-6);
|
||||
assert.ok(Math.abs(strength(t0 + echo.fadeMs / 2, d) - 0.25) < 1e-6);
|
||||
assert.equal(strength(t0 + echo.fadeMs + 1, d), 0);
|
||||
assert.equal(strength(t0 - 50, d), 0, 'dark just before the front');
|
||||
// Every pulse lights it once a period: `count` separate flashes in any
|
||||
// one-period window that starts after a flash has faded.
|
||||
let flashes = 0;
|
||||
let wasLit = false;
|
||||
const from = t0 + echo.fadeMs + 1;
|
||||
for (let ms = 0; ms < pulse.periodMs; ms += 10) {
|
||||
const lit = strength(from + ms, d) > 0.5;
|
||||
if (lit && !wasLit) flashes++;
|
||||
wasLit = lit;
|
||||
}
|
||||
assert.equal(flashes, pulse.count);
|
||||
});
|
||||
|
||||
test('rim contacts fade out after the front wraps; outside the range never', () => {
|
||||
const rim = R * 0.999;
|
||||
assert.ok(strength(arrival(rim) + echo.fadeMs / 2, rim) > 0.2);
|
||||
// Inside the ring pulses are born on, nothing is ever crossed: the
|
||||
// subject and anything within 5 km never echo, at any moment.
|
||||
const inner = R * pulse.startFraction;
|
||||
for (let ms = 0; ms < pulse.periodMs; ms += 10) {
|
||||
assert.equal(strength(ms, 0), 0, 'the subject itself');
|
||||
assert.equal(strength(ms, inner - 1), 0);
|
||||
}
|
||||
assert.ok(strength(pulse.periodMs * 5, inner) > 0.99, 'the birth ring');
|
||||
for (let ms = 0; ms < pulse.periodMs; ms += 50)
|
||||
assert.equal(strength(ms, R + 1), 0);
|
||||
assert.equal(strength(0, Number.NaN), 0);
|
||||
assert.equal(strength(0, -1), 0);
|
||||
});
|
||||
|
||||
test('awarenessEchoAt reads the published field, by layer, at ground level', (t) => {
|
||||
t.after(clearAwarenessEchoField);
|
||||
const contact = Cesium.Cartesian3.fromDegrees(3.5, 27, 0);
|
||||
assert.equal(awarenessEchoAt('flights', contact, 0), 0, 'no field, no echo');
|
||||
const center = Cesium.Cartesian3.fromDegrees(3, 27, 0);
|
||||
setAwarenessEchoField({ center, radiusM: R, pulse, echo });
|
||||
assert.ok(getAwarenessEchoField());
|
||||
const d = Cesium.Cartesian3.distance(center, contact);
|
||||
const t0 = arrival(d);
|
||||
assert.ok(awarenessEchoAt('flights', contact, t0) > 0.99);
|
||||
assert.ok(awarenessEchoAt('ais-live-vessels', contact, t0) > 0.99);
|
||||
// Layers outside the echo list never light.
|
||||
assert.equal(awarenessEchoAt('cctv', contact, t0), 0);
|
||||
assert.equal(awarenessEchoAt('military-installations', contact, t0), 0);
|
||||
// An aircraft 11 km up echoes with the ground point under it.
|
||||
const aloft = Cesium.Cartesian3.fromDegrees(3.5, 27, 11_000);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
awarenessEchoAt('flights', aloft, t0 + 300) -
|
||||
awarenessEchoAt('flights', contact, t0 + 300),
|
||||
) < 0.01,
|
||||
);
|
||||
// The field's centre is read in place, so a moved subject moves the echo:
|
||||
// about 50 km farther, the contact lights at its new distance's moment.
|
||||
Cesium.Cartesian3.clone(Cesium.Cartesian3.fromDegrees(3.5, 26.1, 0), center);
|
||||
const moved = Cesium.Cartesian3.distance(center, contact);
|
||||
assert.ok(Math.abs(moved - d) > 1000);
|
||||
assert.ok(awarenessEchoAt('flights', contact, arrival(moved)) > 0.99);
|
||||
assert.equal(awarenessEchoAt('flights', null, t0), 0);
|
||||
clearAwarenessEchoField();
|
||||
assert.equal(getAwarenessEchoField(), null);
|
||||
assert.equal(awarenessEchoAt('flights', contact, t0), 0);
|
||||
});
|
||||
|
||||
test('echoes scale with the field level and rest with the pulses', (t) => {
|
||||
t.after(clearAwarenessEchoField);
|
||||
const center = Cesium.Cartesian3.fromDegrees(3, 27, 0);
|
||||
// ~100 km east of the subject, on the ground.
|
||||
const contact = Cesium.Cartesian3.fromDegrees(4.008, 27, 0);
|
||||
let level = 1;
|
||||
setAwarenessEchoField({
|
||||
center,
|
||||
radiusM: R,
|
||||
pulse,
|
||||
echo,
|
||||
level: () => level,
|
||||
});
|
||||
const d = Cesium.Cartesian3.distance(center, contact);
|
||||
const t0 = arrival(d);
|
||||
const full = awarenessEchoAt('flights', contact, t0);
|
||||
assert.ok(full > 0.99);
|
||||
level = 0.5;
|
||||
assert.ok(
|
||||
Math.abs(awarenessEchoAt('flights', contact, t0) - full / 2) < 1e-9,
|
||||
);
|
||||
assert.equal(awarenessEchoActive(t0), true);
|
||||
level = 0;
|
||||
assert.equal(awarenessEchoAt('flights', contact, t0), 0);
|
||||
// At rest the overlay skips echoes for the whole frame.
|
||||
assert.equal(awarenessEchoActive(t0), false);
|
||||
clearAwarenessEchoField();
|
||||
assert.equal(awarenessEchoActive(t0), false);
|
||||
});
|
||||
|
||||
test('near the subject an echo is no brighter than the fading-in front', () => {
|
||||
const fading = { ...pulse, fadeInFraction: 0.08 };
|
||||
const at = (distanceM) =>
|
||||
awarenessEchoStrength(arrival(distanceM), distanceM, R, fading, echo);
|
||||
// Born at 5 km, the front reaches full strength 8% of the way out.
|
||||
const full = R * (fading.startFraction + 0.08 * (1 - fading.startFraction));
|
||||
assert.equal(at(R * fading.startFraction), 0);
|
||||
const halfway = (R * fading.startFraction + full) / 2;
|
||||
assert.ok(Math.abs(at(halfway) - 0.5) < 0.01, `${at(halfway)}`);
|
||||
assert.ok(at(full + 1) > 0.99);
|
||||
assert.ok(
|
||||
at(R * 0.999) > 0.99,
|
||||
'the rim, and so the ring flash, is unchanged',
|
||||
);
|
||||
});
|
||||
@@ -53,6 +53,12 @@ import {
|
||||
isCyberContactSonarActive as isCyberSonarActive,
|
||||
isCyberContactThemeActive as isCyberMapThemeActive,
|
||||
} from '../cyberSonar.js';
|
||||
import {
|
||||
awarenessEchoActive,
|
||||
awarenessEchoBracket,
|
||||
awarenessEchoColor,
|
||||
getAwarenessEchoField,
|
||||
} from '../awarenessEcho.js';
|
||||
|
||||
/**
|
||||
* @module detection
|
||||
@@ -103,6 +109,8 @@ const SPARSE_ZONE_FRACTION = 0.5;
|
||||
const LABEL_SOLVE_INTERVAL_MS = 125;
|
||||
/** Alpha bands retain bracket batching while approximating a continuous radial fade. */
|
||||
const BRACKET_ALPHA_STEPS = 4;
|
||||
/** Finer bands for Global Context echo brackets, whose fade is animated. */
|
||||
const ECHO_ALPHA_STEPS = 8;
|
||||
/** Stable per-layer candidate safety cap; independent of density and camera bearing. */
|
||||
const LAYER_CANDIDATE_CAP = 2600;
|
||||
const LAYER_WEIGHTS = Object.freeze({
|
||||
@@ -1335,6 +1343,11 @@ function _drawOverlay(frame) {
|
||||
const tiers = _theme.tiers || null;
|
||||
const colorFor = (key) => (tiers && tiers[key]) || _theme.line;
|
||||
const bracketPaths = new Map();
|
||||
// Global Context sonar echoes: a second bracket, banded by strength, around
|
||||
// each flight or vessel a pulse front has just crossed.
|
||||
// Resting pulses light nothing, so the per-contact echo work is skipped.
|
||||
const echoField = awarenessEchoActive(now) ? getAwarenessEchoField() : null;
|
||||
const echoPaths = echoField ? new Array(ECHO_ALPHA_STEPS + 1) : null;
|
||||
const pathFor = (map, color, alpha) => {
|
||||
const band = Math.max(
|
||||
1,
|
||||
@@ -1437,6 +1450,24 @@ function _drawOverlay(frame) {
|
||||
halfH,
|
||||
);
|
||||
visibleCount++;
|
||||
if (echoPaths) {
|
||||
// Starts on the contact's bracket and spreads outward as it fades.
|
||||
const echo = awarenessEchoBracket(
|
||||
obj._layerId,
|
||||
obj.position,
|
||||
now,
|
||||
bracketAlpha,
|
||||
ECHO_ALPHA_STEPS,
|
||||
);
|
||||
if (echo)
|
||||
appendCornerBracket(
|
||||
(echoPaths[echo.band] ??= new Path2D()),
|
||||
sx,
|
||||
sy,
|
||||
halfW + echo.spreadPx,
|
||||
halfH + echo.spreadPx,
|
||||
);
|
||||
}
|
||||
if (obj.type === 'AIR')
|
||||
aircraftBracketSectors[detectionHorizontalSector(sx, width)]++;
|
||||
if (bracketAlpha >= 1) bracketOpacityCounts.full++;
|
||||
@@ -1576,6 +1607,20 @@ function _drawOverlay(frame) {
|
||||
_ctx.stroke(entry.path);
|
||||
}
|
||||
}
|
||||
if (echoPaths) {
|
||||
_ctx.lineWidth = echoField.echo.lineWidth;
|
||||
_ctx.strokeStyle = awarenessEchoColor(
|
||||
_theme.line,
|
||||
_theme === THEME_MAP._default,
|
||||
);
|
||||
for (let band = 1; band <= ECHO_ALPHA_STEPS; band++) {
|
||||
if (!echoPaths[band]) continue;
|
||||
_ctx.globalAlpha =
|
||||
fade * (band / ECHO_ALPHA_STEPS) * bracketPresentationOpacity;
|
||||
_ctx.stroke(echoPaths[band]);
|
||||
}
|
||||
_ctx.lineWidth = bracketWidth;
|
||||
}
|
||||
|
||||
const renderEntries = _labelArbiter.renderEntries(candidateMap, now);
|
||||
const fadingCount = countFadingRenderEntries(renderEntries);
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// src/data/detectionAwarenessEcho.test.mjs — Global Context sonar echoes pulse
|
||||
// a contact's own detection bracket: a second bracket that starts on it and
|
||||
// spreads outward as it fades, in the detection style's own colour.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
awarenessEchoBracket,
|
||||
awarenessEchoColor,
|
||||
clearAwarenessEchoField,
|
||||
setAwarenessEchoField,
|
||||
} from '../awarenessEcho.js';
|
||||
import { DETECTION_THEME_MAP } from '../overlays/worldOverlayTokens.js';
|
||||
|
||||
const STEPS = 8;
|
||||
const pulse = { count: 3, periodMs: 9000, startFraction: 0.02 };
|
||||
const echo = {
|
||||
fadeMs: 1400,
|
||||
layerIds: ['flights', 'military', 'ais-live-vessels'],
|
||||
spreadPx: 8,
|
||||
color: 'rgb(98, 181, 255)',
|
||||
};
|
||||
const center = Cesium.Cartesian3.fromDegrees(3, 27, 0);
|
||||
const field = { center, radiusM: 250_000, pulse, echo };
|
||||
|
||||
/** The moment pulse 0's front reaches the ground under `position`. */
|
||||
function arrivalAt(position) {
|
||||
const ground = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(position);
|
||||
const d = Cesium.Cartesian3.distance(center, ground);
|
||||
return (
|
||||
((d / 250_000 - pulse.startFraction) / (1 - pulse.startFraction)) *
|
||||
pulse.periodMs +
|
||||
pulse.periodMs * 3
|
||||
);
|
||||
}
|
||||
|
||||
test('the echo bracket pulses outward from the contact bracket and fades', (t) => {
|
||||
t.after(clearAwarenessEchoField);
|
||||
setAwarenessEchoField(field);
|
||||
const position = Cesium.Cartesian3.fromDegrees(3.5, 27, 10_000);
|
||||
const arrival = arrivalAt(position);
|
||||
const at = (nowMs, bracketAlpha = 1) =>
|
||||
awarenessEchoBracket('flights', position, nowMs, bracketAlpha, STEPS);
|
||||
|
||||
// The moment the front arrives: on the bracket, strongest band.
|
||||
const fresh = at(arrival);
|
||||
assert.ok(fresh);
|
||||
assert.ok(Math.abs(fresh.spreadPx) < 0.01, `${fresh.spreadPx}`);
|
||||
assert.equal(fresh.band, STEPS);
|
||||
// Half way through the fade: dimmer and spread outward, but not past
|
||||
// the field's spread.
|
||||
const half = at(arrival + echo.fadeMs / 2);
|
||||
assert.ok(half.spreadPx > echo.spreadPx * 0.5);
|
||||
assert.ok(half.spreadPx < echo.spreadPx);
|
||||
assert.ok(half.band < STEPS && half.band >= 1);
|
||||
// The bracket's own dimming (keyhole fade, Cyber sonar sweep) carries
|
||||
// over, and the echo is never drawn brighter than its bracket: a bracket
|
||||
// too dim for even one band draws no echo.
|
||||
assert.equal(at(arrival, 0.25).band, 2);
|
||||
assert.equal(at(arrival, 0.05), null);
|
||||
for (let alpha = 0.05; alpha <= 1; alpha += 0.05) {
|
||||
const echoed = at(arrival + echo.fadeMs / 3, alpha);
|
||||
if (echoed)
|
||||
assert.ok(
|
||||
echoed.band / STEPS <= alpha + 0.5 / STEPS + 1e-9,
|
||||
`band ${echoed.band} for a bracket at ${alpha}`,
|
||||
);
|
||||
}
|
||||
// Faded out, or between fronts: no echo bracket.
|
||||
assert.equal(at(arrival + echo.fadeMs + 5), null);
|
||||
});
|
||||
|
||||
test('no echo field, or a layer that does not echo, draws nothing extra', (t) => {
|
||||
t.after(clearAwarenessEchoField);
|
||||
const position = Cesium.Cartesian3.fromDegrees(3.01, 27, 0);
|
||||
clearAwarenessEchoField();
|
||||
for (let now = 0; now < pulse.periodMs; now += 25)
|
||||
assert.equal(
|
||||
awarenessEchoBracket('flights', position, now, 1, STEPS),
|
||||
null,
|
||||
);
|
||||
setAwarenessEchoField(field);
|
||||
for (let now = 0; now < pulse.periodMs; now += 25)
|
||||
for (const layerId of ['cctv', 'satellites', 'traffic'])
|
||||
assert.equal(
|
||||
awarenessEchoBracket(layerId, position, now, 1, STEPS),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('echoes take the detection style colour except on the default style', (t) => {
|
||||
t.after(clearAwarenessEchoField);
|
||||
assert.equal(
|
||||
awarenessEchoColor(DETECTION_THEME_MAP._default.line, true),
|
||||
null,
|
||||
);
|
||||
setAwarenessEchoField(field);
|
||||
assert.equal(
|
||||
awarenessEchoColor(DETECTION_THEME_MAP._default.line, true),
|
||||
echo.color,
|
||||
);
|
||||
// CRT, NVG and FLIR keep their monochrome palettes.
|
||||
for (const style of ['retro', 'surveillance', 'thermal']) {
|
||||
const { line } = DETECTION_THEME_MAP[style];
|
||||
assert.equal(awarenessEchoColor(line, false), line, style);
|
||||
}
|
||||
});
|
||||
@@ -24,6 +24,10 @@ import {
|
||||
setOverlayEntries,
|
||||
} from '../overlays/worldOverlay.js';
|
||||
import { DETECTION_THEME_MAP } from '../overlays/worldOverlayTokens.js';
|
||||
import {
|
||||
clearAwarenessEchoField,
|
||||
setAwarenessEchoField,
|
||||
} from '../awarenessEcho.js';
|
||||
import { composeLabel, resolveTier } from './detectionDraw.js';
|
||||
|
||||
test('detection diagnostics count rendered fading rows instead of absent selected identities', () => {
|
||||
@@ -50,8 +54,9 @@ class MockEvent {
|
||||
}
|
||||
|
||||
class MockPath2D {
|
||||
moveTo() {}
|
||||
lineTo() {}
|
||||
constructor() { this.points = []; }
|
||||
moveTo(x, y) { this.points.push([x, y]); }
|
||||
lineTo(x, y) { this.points.push([x, y]); }
|
||||
roundRect() {}
|
||||
arcTo() {}
|
||||
closePath() {}
|
||||
@@ -98,7 +103,7 @@ function mockContext(target, trace) {
|
||||
// set at some point during the frame. globalAlpha rides along for the same
|
||||
// reason: the backdrop feather is an alpha, not a colour.
|
||||
fill(path) { record('fill', path, this.fillStyle, this.globalAlpha); },
|
||||
stroke(path) { record('stroke', path, this.strokeStyle, this.lineWidth); },
|
||||
stroke(path) { record('stroke', path, this.strokeStyle, this.lineWidth, this.globalAlpha); },
|
||||
fillRect(...args) { record('fillRect', ...args); },
|
||||
fillText(...args) { record('fillText', ...args); },
|
||||
drawImage(...args) { record('drawImage', ...args); },
|
||||
@@ -627,6 +632,231 @@ test('surveillance military tier reaches the dedicated render target as shipped
|
||||
}
|
||||
});
|
||||
|
||||
test('Global Context echo brackets reach the canvas in the detection style colour', () => {
|
||||
const env = installEnvironment();
|
||||
// Fronts every millisecond with a long fade, so the contact is lit on
|
||||
// whatever frame paints; a distinctive width picks the echo stroke out.
|
||||
const echo = {
|
||||
layerIds: ['military'],
|
||||
fadeMs: 60_000,
|
||||
color: 'rgb(1, 2, 3)',
|
||||
spreadPx: 8,
|
||||
lineWidth: 3.25,
|
||||
};
|
||||
const echoStrokes = () =>
|
||||
env.detectionCtx.calls
|
||||
.filter(([name, , , width]) => name === 'stroke' && width === echo.lineWidth)
|
||||
.map(([, , style]) => style);
|
||||
try {
|
||||
setAwarenessEchoField({
|
||||
center: Cesium.Cartesian3.fromDegrees(0, 89, 0),
|
||||
radiusM: 250_000,
|
||||
pulse: { count: 1000, periodMs: 1000, startFraction: 0 },
|
||||
echo,
|
||||
});
|
||||
initWorldOverlay(env.viewer);
|
||||
initDetection(env.viewer, [militaryLayer()], () => {});
|
||||
setMode('DENSE');
|
||||
setDetectionStyle('normal');
|
||||
settleFrame(env);
|
||||
assert.ok(echoStrokes().length > 0, 'the echo bracket is painted');
|
||||
assert.ok(echoStrokes().every((style) => style === echo.color));
|
||||
|
||||
// CRT, NVG and FLIR keep their own palettes.
|
||||
for (const style of ['retro', 'surveillance', 'thermal']) {
|
||||
env.detectionCtx.calls.length = 0;
|
||||
setDetectionStyle(style);
|
||||
settleFrame(env);
|
||||
const strokes = echoStrokes();
|
||||
assert.ok(strokes.length > 0, style);
|
||||
assert.ok(
|
||||
strokes.every((stroke) => stroke === DETECTION_THEME_MAP[style].line),
|
||||
`${style} echoes take the style line colour, got ${strokes}`,
|
||||
);
|
||||
}
|
||||
|
||||
} finally {
|
||||
clearAwarenessEchoField();
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a Global Context echo bracket is drawn outside its contact bracket and dimmer than it', () => {
|
||||
const env = installEnvironment();
|
||||
const echo = {
|
||||
layerIds: ['military'],
|
||||
fadeMs: 60_000,
|
||||
color: 'rgb(1, 2, 3)',
|
||||
spreadPx: 8,
|
||||
lineWidth: 3.25,
|
||||
};
|
||||
// Fronts every millisecond keep the echo at full strength; a level of 0.5
|
||||
// halves it, so it sits 4 px out and draws at half the bracket's alpha.
|
||||
try {
|
||||
setAwarenessEchoField({
|
||||
center: Cesium.Cartesian3.fromDegrees(0, 89, 0),
|
||||
radiusM: 250_000,
|
||||
pulse: { count: 1000, periodMs: 1000, startFraction: 0 },
|
||||
echo,
|
||||
level: () => 0.5,
|
||||
});
|
||||
initWorldOverlay(env.viewer);
|
||||
initDetection(env.viewer, [militaryLayer()], () => {});
|
||||
setMode('DENSE');
|
||||
setDetectionStyle('normal');
|
||||
settleFrame(env);
|
||||
env.detectionCtx.calls.length = 0;
|
||||
settleFrame(env);
|
||||
const strokes = env.detectionCtx.calls.filter(([name]) => name === 'stroke');
|
||||
const echoStroke = strokes.find(([, , style, width]) => style === echo.color && width === echo.lineWidth);
|
||||
assert.ok(echoStroke, 'the echo bracket is painted');
|
||||
const bracketStroke = strokes.find(([, path, style, width]) =>
|
||||
path instanceof MockPath2D && path.points.length && width !== echo.lineWidth && style !== echo.color);
|
||||
assert.ok(bracketStroke, 'the contact bracket is painted');
|
||||
const extent = (path) => {
|
||||
const xs = path.points.map(([x]) => x);
|
||||
const ys = path.points.map(([, y]) => y);
|
||||
return { halfW: (Math.max(...xs) - Math.min(...xs)) / 2, halfH: (Math.max(...ys) - Math.min(...ys)) / 2 };
|
||||
};
|
||||
const echoBox = extent(echoStroke[1]);
|
||||
const bracketBox = extent(bracketStroke[1]);
|
||||
assert.ok(Math.abs(echoBox.halfW - bracketBox.halfW - echo.spreadPx / 2) < 1e-3,
|
||||
`echo ${echoBox.halfW} vs bracket ${bracketBox.halfW}`);
|
||||
assert.ok(Math.abs(echoBox.halfH - bracketBox.halfH - echo.spreadPx / 2) < 1e-3);
|
||||
const echoAlpha = echoStroke[4];
|
||||
const bracketAlpha = bracketStroke[4];
|
||||
assert.ok(echoAlpha > 0 && echoAlpha < bracketAlpha, `${echoAlpha} vs ${bracketAlpha}`);
|
||||
assert.ok(Math.abs(echoAlpha - bracketAlpha / 2) < 1e-6, `${echoAlpha} vs ${bracketAlpha}`);
|
||||
} finally {
|
||||
clearAwarenessEchoField();
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('under the Cyber sonar sweep an echo is never brighter than its own bracket', () => {
|
||||
const env = installEnvironment();
|
||||
// The cyber theme with its HUD open turns the contact sonar on; its sweep
|
||||
// dims brackets it is not passing over.
|
||||
env.document.documentElement = {
|
||||
// The lowest sweep floor, so dimmed brackets drop a whole alpha band.
|
||||
dataset: { uiTheme: 'cyber', cyberSonarOpacity: '35' },
|
||||
style: { setProperty() {}, removeProperty() {} },
|
||||
};
|
||||
const hud = env.document.createElement('div');
|
||||
hud.id = 'intel-hud';
|
||||
hud.classList = { contains: (name) => name === 'active' };
|
||||
env.document.body.appendChild(hud);
|
||||
const echo = {
|
||||
layerIds: ['military'],
|
||||
fadeMs: 60_000,
|
||||
color: 'rgb(1, 2, 3)',
|
||||
spreadPx: 8,
|
||||
lineWidth: 3.25,
|
||||
};
|
||||
const contact = {
|
||||
id: 'military',
|
||||
getDetectableObjects: () => [{
|
||||
position: new Cesium.Cartesian3(0.5, 0.3, 6_356_752),
|
||||
sourceId: 'sonar-pin',
|
||||
id: 'SONAR',
|
||||
metric: 'FL300',
|
||||
type: 'AIR',
|
||||
tier: 'military',
|
||||
}],
|
||||
};
|
||||
try {
|
||||
setAwarenessEchoField({
|
||||
center: Cesium.Cartesian3.fromDegrees(0, 89, 0),
|
||||
radiusM: 250_000,
|
||||
pulse: { count: 1000, periodMs: 1000, startFraction: 0 },
|
||||
echo,
|
||||
level: () => 1,
|
||||
});
|
||||
initWorldOverlay(env.viewer);
|
||||
initDetection(env.viewer, [contact], () => {});
|
||||
setMode('DENSE');
|
||||
setDetectionStyle('normal');
|
||||
settleFrame(env);
|
||||
let dimmed = 0;
|
||||
let compared = 0;
|
||||
for (let frame = 0; frame < 40; frame++) {
|
||||
env.detectionCtx.calls.length = 0;
|
||||
settleFrame(env);
|
||||
const strokes = env.detectionCtx.calls.filter(([name]) => name === 'stroke');
|
||||
const echoStroke = strokes.find(([, , style, width]) => style === echo.color && width === echo.lineWidth);
|
||||
const bracketStroke = strokes.find(([, path, style, width]) =>
|
||||
path instanceof MockPath2D && path.points.length && width !== echo.lineWidth && style !== echo.color);
|
||||
if (!bracketStroke) continue;
|
||||
const bracketAlpha = bracketStroke[4];
|
||||
if (bracketAlpha < 0.99) dimmed++;
|
||||
if (!echoStroke) continue;
|
||||
compared++;
|
||||
assert.ok(
|
||||
echoStroke[4] <= bracketAlpha + 1e-9,
|
||||
`echo ${echoStroke[4]} over bracket ${bracketAlpha} on frame ${frame}`,
|
||||
);
|
||||
}
|
||||
assert.ok(dimmed > 0, 'the sweep dimmed the bracket on some frame');
|
||||
assert.ok(compared > 0, 'an echo was painted');
|
||||
} finally {
|
||||
clearAwarenessEchoField();
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('resting Global Context pulses skip echo work for the whole frame, not per contact', () => {
|
||||
const env = installEnvironment();
|
||||
// Six echo-eligible flights on screen; the identity camera maps x/y
|
||||
// straight to device coordinates.
|
||||
const flights = Array.from({ length: 6 }, (_, index) => ({
|
||||
position: new Cesium.Cartesian3(-0.5 + index * 0.2, 0, 6_356_752),
|
||||
sourceId: `flight-${index}`,
|
||||
id: `ECHO${index}`,
|
||||
metric: `FL${300 + index}`,
|
||||
type: 'AIR',
|
||||
}));
|
||||
const layer = { id: 'flights', getDetectableObjects: () => flights };
|
||||
let levelCalls = 0;
|
||||
try {
|
||||
setAwarenessEchoField({
|
||||
center: Cesium.Cartesian3.fromDegrees(0, 89, 0),
|
||||
radiusM: 250_000,
|
||||
pulse: { count: 1000, periodMs: 1000, startFraction: 0 },
|
||||
echo: {
|
||||
layerIds: ['flights'],
|
||||
fadeMs: 60_000,
|
||||
color: 'rgb(1, 2, 3)',
|
||||
spreadPx: 8,
|
||||
lineWidth: 3.25,
|
||||
},
|
||||
level: () => {
|
||||
levelCalls++;
|
||||
return 0;
|
||||
},
|
||||
});
|
||||
initWorldOverlay(env.viewer);
|
||||
initDetection(env.viewer, [layer], () => {});
|
||||
setMode('DENSE');
|
||||
settleFrame(env);
|
||||
levelCalls = 0;
|
||||
settleFrame(env);
|
||||
const painted = getDetectionDiagnostics().visibleCount;
|
||||
assert.equal(painted, flights.length, 'every flight is on screen');
|
||||
// One check per painted frame, however many contacts are on screen.
|
||||
assert.ok(levelCalls >= 1, 'the frame asks whether echoes are live');
|
||||
assert.ok(levelCalls < painted, `${levelCalls} level checks for ${painted} contacts`);
|
||||
assert.ok(
|
||||
!env.detectionCtx.calls.some(
|
||||
([name, , style]) => name === 'stroke' && style === 'rgb(1, 2, 3)',
|
||||
),
|
||||
'no echoes while the pulses rest',
|
||||
);
|
||||
} finally {
|
||||
clearAwarenessEchoField();
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('pathological detection paint holds alternate frames without freezing shared lanes', () => {
|
||||
// Opts into the telemetry banner: the held-frame assertions count banner paints.
|
||||
const env = installEnvironment({ search: '?detectDebug=1' });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { cameraPoseSignature } from '../../data/iconOrientation.js';
|
||||
import { AWARENESS_RANGE_PULSE } from './policy.js';
|
||||
|
||||
export function createLifecycle({
|
||||
state: layerState,
|
||||
@@ -8,6 +9,86 @@ export function createLifecycle({
|
||||
}) {
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
|
||||
/**
|
||||
* Note the user handling the map's camera (pointer, wheel or touch on the
|
||||
* Cesium canvas, where its camera controller listens), so a camera move the
|
||||
* user made can wake the range pulses and one the app made (tracking,
|
||||
* cockpit, orbit, a fly-to) does not. Keys are left out: Cesium's camera
|
||||
* controller reads none, and typing elsewhere must not count. Nor does
|
||||
* input while the camera controller's inputs are off: the cockpit (or a
|
||||
* gizmo drag, or a drawing tool) owns the camera then, and the user's
|
||||
* gesture moves nothing.
|
||||
*/
|
||||
function noteCameraInput(event) {
|
||||
if (event?.type === 'pointermove' && !event.buttons) return;
|
||||
if (!cameraInputsEnabled()) return;
|
||||
layerState.lastCameraInputMs = Date.now();
|
||||
if (event?.type === 'pointerdown') activePointers.add(event.pointerId);
|
||||
if (event?.type === 'pointerdown' || event?.type === 'touchstart')
|
||||
followGesture(true);
|
||||
}
|
||||
|
||||
// A drag can leave the canvas, and Cesium follows it at document level
|
||||
// (in Firefox, and wherever there are no pointer events). So does this,
|
||||
// from a gesture's start on the canvas to its end, so a long gesture keeps
|
||||
// the input window open the whole way.
|
||||
const GESTURE_MOVE_EVENTS = ['pointermove', 'touchmove'];
|
||||
const GESTURE_END_EVENTS = [
|
||||
'pointerup',
|
||||
'pointercancel',
|
||||
'touchend',
|
||||
'touchcancel',
|
||||
];
|
||||
let followingGesture = false;
|
||||
const activePointers = new Set();
|
||||
|
||||
function followGesture(on) {
|
||||
if (followingGesture === on) return;
|
||||
followingGesture = on;
|
||||
if (!on) activePointers.clear();
|
||||
const listen = on ? 'addEventListener' : 'removeEventListener';
|
||||
for (const type of GESTURE_MOVE_EVENTS)
|
||||
globalThis.document?.[listen]?.(type, noteCameraInput, { passive: true });
|
||||
for (const type of GESTURE_END_EVENTS)
|
||||
globalThis.document?.[listen]?.(type, endGesture, { passive: true });
|
||||
globalThis[listen]?.('blur', dropGesture);
|
||||
globalThis.document?.[listen]?.('visibilitychange', dropGesture);
|
||||
}
|
||||
|
||||
// A gesture ends with its last contact: lifting one finger of a pinch
|
||||
// leaves Cesium a one-finger drag.
|
||||
function endGesture(event) {
|
||||
noteCameraInput(event);
|
||||
activePointers.delete(event?.pointerId);
|
||||
if (activePointers.size || event?.touches?.length) return;
|
||||
followGesture(false);
|
||||
}
|
||||
|
||||
// Losing the window or the page mid-gesture means its end may never
|
||||
// arrive here, so stop following it and drop its pending input.
|
||||
function dropGesture(event) {
|
||||
if (
|
||||
event?.type === 'visibilitychange' &&
|
||||
document.visibilityState !== 'hidden'
|
||||
)
|
||||
return;
|
||||
followGesture(false);
|
||||
layerState.lastCameraInputMs = Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
function cameraInputsEnabled() {
|
||||
const controller = layerState.viewer?.scene?.screenSpaceCameraController;
|
||||
return controller?.enableInputs !== false;
|
||||
}
|
||||
|
||||
const CAMERA_INPUT_EVENTS = [
|
||||
'pointerdown',
|
||||
'pointermove',
|
||||
'pointerup',
|
||||
'wheel',
|
||||
'touchstart',
|
||||
];
|
||||
|
||||
/**
|
||||
* Quantized camera-pose signature, or '' when the camera cannot report a full
|
||||
* pose yet. An unknown pose reads as PARKED, so a camera that is still coming
|
||||
@@ -50,10 +131,18 @@ export function createLifecycle({
|
||||
'gev:awareness-subject-cleared',
|
||||
layerState.subjectClearListener,
|
||||
);
|
||||
const input = layerState.viewer.canvas ?? layerState.viewer.scene?.canvas;
|
||||
for (const type of CAMERA_INPUT_EVENTS)
|
||||
input?.addEventListener?.(type, noteCameraInput, { passive: true });
|
||||
layerState.cameraInputTarget = input ?? null;
|
||||
layerState.preRenderRemover =
|
||||
layerState.viewer.scene.preRender.addEventListener(() => {
|
||||
if (!layerState.enabled) return;
|
||||
const now = Date.now();
|
||||
// Another owner took the camera: a gesture begun before it did must
|
||||
// not wake the pulses on that owner's first move.
|
||||
if (!cameraInputsEnabled())
|
||||
layerState.lastCameraInputMs = Number.NEGATIVE_INFINITY;
|
||||
// "Did the camera move" uses the SAME quantized pose signature the fleet
|
||||
// rotation pass gates on (iconOrientation.cameraPoseSignature) rather than
|
||||
// camera.changed, whose granularity is globally degraded by other layers
|
||||
@@ -62,6 +151,14 @@ export function createLifecycle({
|
||||
if (poseSig !== layerState.lastCameraPoseSig) {
|
||||
layerState.lastCameraPoseSig = poseSig;
|
||||
layerState.lastCameraPoseChangeMs = now;
|
||||
// A camera move the user made runs the range pulses again; parked,
|
||||
// or moved by the app (tracking, cockpit, orbit, a fly-to), they
|
||||
// rest.
|
||||
if (
|
||||
now - layerState.lastCameraInputMs <
|
||||
AWARENESS_RANGE_PULSE.inputWakeMs
|
||||
)
|
||||
parts.rendering.wakePulses();
|
||||
}
|
||||
const decision = parts.model.awarenessRefreshDecision({
|
||||
nowMs: now,
|
||||
@@ -108,6 +205,13 @@ export function createLifecycle({
|
||||
'gev:awareness-subject-cleared',
|
||||
layerState.subjectClearListener,
|
||||
);
|
||||
for (const type of CAMERA_INPUT_EVENTS)
|
||||
layerState.cameraInputTarget?.removeEventListener?.(
|
||||
type,
|
||||
noteCameraInput,
|
||||
);
|
||||
layerState.cameraInputTarget = null;
|
||||
followGesture(false);
|
||||
}
|
||||
layerState.preRenderRemover?.();
|
||||
layerState.preRenderRemover = null;
|
||||
|
||||
@@ -49,13 +49,86 @@ export const CONTEXT_RIM_HEIGHT_M = 2500;
|
||||
* the FLIR, NVG and CRT styles. A bright core inside a dark halo keeps
|
||||
* luminance contrast on light and dark ground alike, and luminance is what
|
||||
* the monochrome styles keep. The core is the Context panel's blue; the halo
|
||||
* is the map-card ink. Widths are screen pixels; `outlineWidth` is per side. */
|
||||
* is the map-card ink. Widths are screen pixels; `outlineWidth` is per side.
|
||||
* It is drawn as an unpickable primitive, so clicks on its edge reach the
|
||||
* contacts underneath.
|
||||
* While the sonar pulses run, the ring dims to `restOpacity` and flashes
|
||||
* to full as each pulse reaches it, fading over `flashMs`. `restOpacity`
|
||||
* keeps the 250 km edge readable between flashes, in screenshots and for
|
||||
* low-vision viewers. Once the pulses rest, and without pulses (reduced
|
||||
* motion, or a scene that cannot animate), it stays on screen at full. */
|
||||
export const AWARENESS_RANGE_RING_STYLE = Object.freeze({
|
||||
color: 'rgba(98, 181, 255, 0.95)',
|
||||
outlineColor: 'rgba(4, 12, 16, 0.8)',
|
||||
width: 4,
|
||||
outlineWidth: 1,
|
||||
segments: 128,
|
||||
flashMs: 1800,
|
||||
restOpacity: 0.4,
|
||||
});
|
||||
|
||||
/** @constant Sonar-style pulses that grow slowly from the subject to the
|
||||
* range ring and are almost gone when they reach it. `count` pulses share
|
||||
* one `periodMs`, evenly staggered, so a new one starts every
|
||||
* `periodMs / count`. Each starts at `startFraction` of the radius, fades in
|
||||
* over `fadeInFraction` of its travel, then fades as (1 - travel) to the
|
||||
* `fadeOutPower` down to `endOpacityFraction` of `peakOpacity`, so a pulse
|
||||
* is dim but still visible when it reaches the ring and the ring flashes.
|
||||
* Each line is `width` CSS pixels wide, its outer `outlineWidth` a dark
|
||||
* halo, in the ring's colours, as Cesium's polyline outline material draws.
|
||||
* Behind each line a radial gradient in the same blue fades inward over
|
||||
* `gradientDepthFraction` of the radius, at most
|
||||
* `gradientOpacity` strong. One unpickable disc draws the lines and the
|
||||
* gradient, so pulses never catch a click meant for a contact; its shader
|
||||
* takes at most four pulses. The disc follows the subject by a model-matrix
|
||||
* rotation, so it stays concentric with the ring, and is rebuilt only after
|
||||
* the subject moves `gradientRebuildM` from where it was built; while the
|
||||
* pulses rest the hidden disc is left alone and catches up when they wake. The
|
||||
* disc is hidden while the camera is below its height, where it would sweep
|
||||
* the sky.
|
||||
* The pulses run for `activeMs` (three ring flashes) after a selection or
|
||||
* a camera move, fading in and out over `settleMs`, then rest: the ring
|
||||
* stays on screen, static, and nothing asks for frames, so a parked view
|
||||
* goes quiet again. Only a camera move within `inputWakeMs` of the user
|
||||
* handling the map (pointer, wheel or touch on the canvas, which covers a
|
||||
* drag's inertia, while the camera controls take input) wakes them; a moving subject and the app's own camera moves
|
||||
* (tracking, cockpit, orbit, a fly-to) do not. Below the disc's height they
|
||||
* rest too. While they run they never hold
|
||||
* continuous rendering; each drawn frame arms one more request after the
|
||||
* Cyber sonar's 80 ms cadence, so the two never beat. When something else
|
||||
* already renders continuously they update every frame. Skipped under
|
||||
* prefers-reduced-motion. */
|
||||
export const AWARENESS_RANGE_PULSE = Object.freeze({
|
||||
count: 3,
|
||||
periodMs: 9000,
|
||||
startFraction: 0.02,
|
||||
fadeInFraction: 0.08,
|
||||
fadeOutPower: 1.5,
|
||||
endOpacityFraction: 0.35,
|
||||
peakOpacity: 0.6,
|
||||
width: 3,
|
||||
outlineWidth: 1,
|
||||
gradientDepthFraction: 0.35,
|
||||
gradientOpacity: 0.22,
|
||||
gradientGranularityDeg: 0.25,
|
||||
gradientRebuildM: 20000,
|
||||
activeMs: 9000,
|
||||
settleMs: 1200,
|
||||
inputWakeMs: 1500,
|
||||
});
|
||||
|
||||
/** @constant Sonar echoes on contact brackets. When a pulse front reaches a
|
||||
* flight, military aircraft or AIS vessel in the window, the detection
|
||||
* overlay draws a second bracket in `color` around that contact's own
|
||||
* bracket. It starts on the bracket and spreads outward by up to `spreadPx`
|
||||
* as it fades over `fadeMs`, so the frame pulses. Only `layerIds` echo;
|
||||
* mapped installations have no detection bracket. */
|
||||
export const AWARENESS_RANGE_ECHO = Object.freeze({
|
||||
layerIds: ['flights', 'military', 'ais-live-vessels'],
|
||||
fadeMs: 1400,
|
||||
color: 'rgb(98, 181, 255)',
|
||||
spreadPx: 8,
|
||||
lineWidth: 1.75,
|
||||
});
|
||||
|
||||
export const VESSEL_FOCUS_RADIUS_M = 3000;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import {
|
||||
CYBER_SONAR_RENDER_INTERVAL_MS,
|
||||
createCyberSonarSampler,
|
||||
isCyberContactSonarActive as isCyberSonarActive,
|
||||
} from '../../cyberSonar.js';
|
||||
@@ -12,10 +13,17 @@ import {
|
||||
import { bearingBetweenCoordinates } from '../../cockpitMath.js';
|
||||
import {
|
||||
AWARENESS_PAGE_SIZE,
|
||||
AWARENESS_RANGE_ECHO,
|
||||
AWARENESS_RANGE_PULSE,
|
||||
AWARENESS_RANGE_RING_STYLE,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
} from './policy.js';
|
||||
import { formatAwarenessDirection } from './presentation.js';
|
||||
import {
|
||||
awarenessEchoStrength,
|
||||
clearAwarenessEchoField,
|
||||
setAwarenessEchoField,
|
||||
} from '../../awarenessEcho.js';
|
||||
|
||||
/**
|
||||
* A closed ring of positions `radiusM` along the surface from `groundCenter`,
|
||||
@@ -70,6 +78,273 @@ export function awarenessRangeRingPositions(
|
||||
return positions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where pulse `index` is at `nowMs`: its radius and opacity. Pulses travel at
|
||||
* constant speed from `startFraction` of the range to the full range, fade in
|
||||
* over `fadeInFraction` of the way, then fade as (1 - travel) to the
|
||||
* `fadeOutPower` down to `endOpacityFraction` of the peak, so each is dim
|
||||
* but still visible when it reaches the range ring. The opacity already
|
||||
* includes `peakOpacity`.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {number} index Pulse number, 0 to `count - 1`.
|
||||
* @param {number} [radiusM] Range the pulses grow to.
|
||||
* @param {object} [pulse] Timing and shape, see `AWARENESS_RANGE_PULSE`.
|
||||
* @returns {{radiusM: number, alpha: number}}
|
||||
*/
|
||||
export function awarenessPulseState(
|
||||
nowMs,
|
||||
index,
|
||||
radiusM = AWARENESS_RADIUS_M,
|
||||
pulse = AWARENESS_RANGE_PULSE,
|
||||
) {
|
||||
const cycle = nowMs / pulse.periodMs + index / pulse.count;
|
||||
const phase = cycle - Math.floor(cycle);
|
||||
return {
|
||||
radiusM:
|
||||
radiusM * (pulse.startFraction + (1 - pulse.startFraction) * phase),
|
||||
alpha:
|
||||
pulse.peakOpacity *
|
||||
Math.min(1, phase / pulse.fadeInFraction) *
|
||||
(pulse.endOpacityFraction +
|
||||
(1 - pulse.endOpacityFraction) * (1 - phase) ** pulse.fadeOutPower),
|
||||
};
|
||||
}
|
||||
|
||||
const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
|
||||
|
||||
/** Whether the viewer asked the system for less motion. */
|
||||
function prefersReducedMotion() {
|
||||
return globalThis.matchMedia?.(REDUCED_MOTION_QUERY)?.matches ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far the pulses are switched on at `nowMs`: 0 at rest, rising to 1 over
|
||||
* `settleMs` from `wake.startMs` and falling back to 0 over `settleMs` up to
|
||||
* `wake.untilMs`.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {{startMs: number, untilMs: number}} wake Window from `wakeAwarenessPulses`.
|
||||
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
|
||||
* @returns {number} 0 to 1.
|
||||
*/
|
||||
export function awarenessPulseLevel(
|
||||
nowMs,
|
||||
wake,
|
||||
pulse = AWARENESS_RANGE_PULSE,
|
||||
) {
|
||||
const level = Math.min(
|
||||
(nowMs - wake.startMs) / pulse.settleMs,
|
||||
(wake.untilMs - nowMs) / pulse.settleMs,
|
||||
);
|
||||
return Math.max(0, Math.min(1, level));
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the pulses for `activeMs` from `nowMs`. A wake while they already run
|
||||
* keeps their current level, so they never jump back to full mid-fade.
|
||||
* @param {{startMs: number, untilMs: number}} wake Updated in place.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
|
||||
* @returns {{startMs: number, untilMs: number}} `wake`.
|
||||
*/
|
||||
export function wakeAwarenessPulses(
|
||||
wake,
|
||||
nowMs,
|
||||
pulse = AWARENESS_RANGE_PULSE,
|
||||
) {
|
||||
wake.startMs =
|
||||
nowMs - awarenessPulseLevel(nowMs, wake, pulse) * pulse.settleMs;
|
||||
wake.untilMs = nowMs + pulse.activeMs;
|
||||
return wake;
|
||||
}
|
||||
|
||||
/**
|
||||
* How strongly the 250 km ring shows at `nowMs` while pulses run: 1 as a
|
||||
* pulse front reaches it, fading over `flashMs`, so the ring appears once
|
||||
* per arriving pulse instead of standing on screen.
|
||||
* @param {number} nowMs Monotonic clock in milliseconds.
|
||||
* @returns {number} 0 to 1.
|
||||
*/
|
||||
export function awarenessRingFlash(nowMs) {
|
||||
return awarenessEchoStrength(
|
||||
nowMs,
|
||||
AWARENESS_RADIUS_M,
|
||||
AWARENESS_RADIUS_M,
|
||||
AWARENESS_RANGE_PULSE,
|
||||
{ fadeMs: AWARENESS_RANGE_RING_STYLE.flashMs },
|
||||
);
|
||||
}
|
||||
|
||||
/** Most pulses the pulse shader draws; its uniforms are vec4s. */
|
||||
export const AWARENESS_PULSE_GRADIENT_MAX = 4;
|
||||
|
||||
/** The pulse disc's Cesium material type, one cached template per page. */
|
||||
const AWARENESS_PULSE_MATERIAL_TYPE = 'GevAwarenessPulseGradient';
|
||||
|
||||
// Ellipse texture coordinates put the centre at (0.5, 0.5) and the rim at
|
||||
// distance 0.5, so `r` is the fraction of the range. Each pulse is a line
|
||||
// `lineWidth` CSS pixels wide whose outer `haloWidth` is a dark halo, half
|
||||
// on each side, as Cesium's polyline outline material draws it, with a band
|
||||
// behind it that is strongest at the line and fades to nothing `depth`
|
||||
// inward. Widths come from the screen-space gradient of `r`, as Cesium's
|
||||
// contour material measures its lines; without derivatives the lines are
|
||||
// left out and only the band shows.
|
||||
const PULSE_GRADIENT_SOURCE = `
|
||||
uniform vec4 color;
|
||||
uniform vec4 lineColor;
|
||||
uniform vec4 haloColor;
|
||||
uniform vec4 radii;
|
||||
uniform vec4 alphas;
|
||||
uniform float depth;
|
||||
uniform float lineWidth;
|
||||
uniform float haloWidth;
|
||||
vec4 over(vec4 top, vec4 under) {
|
||||
float a = top.a + under.a * (1.0 - top.a);
|
||||
if (a <= 0.0) return vec4(0.0);
|
||||
return vec4((top.rgb * top.a + under.rgb * under.a * (1.0 - top.a)) / a, a);
|
||||
}
|
||||
czm_material czm_getMaterial(czm_materialInput materialInput) {
|
||||
czm_material material = czm_getDefaultMaterial(materialInput);
|
||||
float r = length(materialInput.st - vec2(0.5)) * 2.0;
|
||||
float band = 0.0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
float inside = radii[i] - r;
|
||||
if (inside >= 0.0 && inside <= depth) {
|
||||
float t = 1.0 - inside / depth;
|
||||
band += alphas[i] * t * t;
|
||||
}
|
||||
}
|
||||
vec4 result = vec4(color.rgb, clamp(band * color.a, 0.0, 1.0));
|
||||
#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))
|
||||
// Change in r per CSS pixel: the gradient's length per device pixel,
|
||||
// times the device pixels in one CSS pixel.
|
||||
float cssPx = max(length(vec2(dFdx(r), dFdy(r))), 1e-7) * czm_pixelRatio;
|
||||
float outerHalf = lineWidth * 0.5;
|
||||
float coreHalf = max(lineWidth - haloWidth, 0.0) * 0.5;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
float d = abs(radii[i] - r) / cssPx;
|
||||
float cover = clamp(outerHalf + 0.5 - d, 0.0, 1.0);
|
||||
if (cover <= 0.0) continue;
|
||||
float core = clamp(coreHalf + 0.5 - d, 0.0, 1.0);
|
||||
vec4 pulse = mix(haloColor, lineColor, core);
|
||||
result = over(vec4(pulse.rgb, pulse.a * cover * alphas[i]), result);
|
||||
}
|
||||
#endif
|
||||
material.diffuse = result.rgb;
|
||||
material.alpha = result.a;
|
||||
return material;
|
||||
}
|
||||
`;
|
||||
|
||||
/**
|
||||
* The pulses: one flat, translucent, unpickable disc the size of the range
|
||||
* ring whose shader draws each pulse line and the band behind it. Drawing
|
||||
* them here rather than as entities keeps them out of picking, so clicks and
|
||||
* taps near a pulse still reach the contact underneath. Moving pulses only
|
||||
* change its uniforms; the disc is rebuilt only when the subject moves.
|
||||
* @param {Cesium.Cartesian3} groundCenter Disc centre on the ellipsoid.
|
||||
* @param {Cesium.Material} material Shared pulse-gradient material.
|
||||
* @returns {Cesium.Primitive}
|
||||
*/
|
||||
function createPulseGradient(groundCenter, material) {
|
||||
return new Cesium.Primitive({
|
||||
geometryInstances: new Cesium.GeometryInstance({
|
||||
geometry: new Cesium.EllipseGeometry({
|
||||
center: groundCenter,
|
||||
semiMajorAxis: AWARENESS_RADIUS_M,
|
||||
semiMinorAxis: AWARENESS_RADIUS_M,
|
||||
height: CONTEXT_RIM_HEIGHT_M,
|
||||
granularity: Cesium.Math.toRadians(
|
||||
AWARENESS_RANGE_PULSE.gradientGranularityDeg,
|
||||
),
|
||||
vertexFormat:
|
||||
Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat,
|
||||
}),
|
||||
}),
|
||||
appearance: new Cesium.MaterialAppearance({
|
||||
material,
|
||||
flat: true,
|
||||
translucent: true,
|
||||
faceForward: true,
|
||||
}),
|
||||
asynchronous: false,
|
||||
allowPicking: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The ring's polyline geometry: `AWARENESS_RANGE_RING_STYLE.width` screen
|
||||
* pixels, straight chords between the given positions (they already follow
|
||||
* the surface), in the material appearance's vertex format.
|
||||
* @param {Cesium.Cartesian3[]} positions Ring positions.
|
||||
* @returns {object} PolylineGeometry options.
|
||||
*/
|
||||
export function awarenessRingGeometryOptions(positions) {
|
||||
return {
|
||||
positions,
|
||||
width: AWARENESS_RANGE_RING_STYLE.width,
|
||||
arcType: Cesium.ArcType.NONE,
|
||||
vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The 250 km ring as an unpickable polyline primitive in the ring's outline
|
||||
* material, so a click or tap on its edge reaches the contact underneath.
|
||||
* Its positions are geometry, so a moved subject rebuilds it; the material
|
||||
* is shared between builds so a flash keeps going.
|
||||
* @param {Cesium.Cartesian3[]} positions Ring positions.
|
||||
* @param {Cesium.Material} material Shared PolylineOutline material.
|
||||
* @returns {Cesium.Primitive}
|
||||
*/
|
||||
function createRingPrimitive(positions, material) {
|
||||
return new Cesium.Primitive({
|
||||
geometryInstances: new Cesium.GeometryInstance({
|
||||
geometry: new Cesium.PolylineGeometry(
|
||||
awarenessRingGeometryOptions(positions),
|
||||
),
|
||||
}),
|
||||
appearance: new Cesium.PolylineMaterialAppearance({
|
||||
material,
|
||||
translucent: true,
|
||||
}),
|
||||
asynchronous: false,
|
||||
allowPicking: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The rotation about the Earth's centre that carries `from` onto `to`, as a
|
||||
* model matrix, so a disc built around `from` sits around `to`.
|
||||
* @param {Cesium.Cartesian3} from Where the disc was built.
|
||||
* @param {Cesium.Cartesian3} to Where it should be.
|
||||
* @param {Cesium.Matrix4} [result]
|
||||
* @returns {Cesium.Matrix4}
|
||||
*/
|
||||
export function discFollowMatrix(from, to, result = new Cesium.Matrix4()) {
|
||||
const a = Cesium.Cartesian3.normalize(from, new Cesium.Cartesian3());
|
||||
const b = Cesium.Cartesian3.normalize(to, new Cesium.Cartesian3());
|
||||
const axis = Cesium.Cartesian3.cross(a, b, new Cesium.Cartesian3());
|
||||
const sin = Cesium.Cartesian3.magnitude(axis);
|
||||
if (sin < 1e-12) return Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY, result);
|
||||
const angle = Math.atan2(sin, Cesium.Cartesian3.dot(a, b));
|
||||
const rotation = Cesium.Matrix3.fromQuaternion(
|
||||
Cesium.Quaternion.fromAxisAngle(
|
||||
Cesium.Cartesian3.divideByScalar(axis, sin, axis),
|
||||
angle,
|
||||
),
|
||||
);
|
||||
return Cesium.Matrix4.fromRotationTranslation(
|
||||
rotation,
|
||||
Cesium.Cartesian3.ZERO,
|
||||
result,
|
||||
);
|
||||
}
|
||||
|
||||
/** Camera height above the ellipsoid, or NaN when the scene cannot say. */
|
||||
function cameraHeightM(scene) {
|
||||
return scene.camera?.positionCartographic?.height ?? Number.NaN;
|
||||
}
|
||||
|
||||
export function createRendering({
|
||||
state: layerState,
|
||||
services,
|
||||
@@ -328,7 +603,62 @@ export function createRendering({
|
||||
presentDirection({ hidden: false, ring, heading, labels, markers });
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the range pulses again for `activeMs`, after a camera move. Call it
|
||||
* during a frame (lifecycle's preRender): that frame's postRender arms the
|
||||
* next request, so waking asks for no extra frame of its own.
|
||||
*/
|
||||
function wakePulses() {
|
||||
const wake = layerState.visual?.wake;
|
||||
if (!wake) return;
|
||||
wakeAwarenessPulses(wake, performance.now());
|
||||
followPulseDisc();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the pulse disc centred on the subject. Within `gradientRebuildM` of
|
||||
* where it was built, the disc is rotated about the Earth's centre onto
|
||||
* the subject by its model matrix, which keeps it concentric with the ring
|
||||
* at no build cost; the ellipsoid curves a little differently from that
|
||||
* sphere, a few tens of metres in height at 20 km. Further away it is
|
||||
* rebuilt, which costs a few milliseconds.
|
||||
*/
|
||||
function followPulseDisc() {
|
||||
const { gradient, gradientCenter, center } = layerState.visual;
|
||||
if (!gradient) return;
|
||||
if (
|
||||
Cesium.Cartesian3.distance(gradientCenter, center) <
|
||||
AWARENESS_RANGE_PULSE.gradientRebuildM
|
||||
) {
|
||||
gradient.modelMatrix = discFollowMatrix(
|
||||
gradientCenter,
|
||||
center,
|
||||
gradient.modelMatrix,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const primitives = layerState.viewer.scene.primitives;
|
||||
layerState.visual.gradient = primitives.add(
|
||||
createPulseGradient(center, gradient.appearance.material),
|
||||
);
|
||||
// Primitive.destroy leaves the material alone, so the new disc keeps
|
||||
// sharing it.
|
||||
primitives.remove(gradient);
|
||||
Cesium.Cartesian3.clone(center, gradientCenter);
|
||||
}
|
||||
|
||||
function clearVisual() {
|
||||
layerState.visual?.stopPulses?.();
|
||||
layerState.visual?.removeMotionListener?.();
|
||||
if (layerState.visual?.gradient && layerState.viewer)
|
||||
layerState.viewer.scene.primitives.remove(layerState.visual.gradient);
|
||||
if (layerState.visual?.ringPrimitive && layerState.viewer) {
|
||||
layerState.viewer.scene.primitives.remove?.(
|
||||
layerState.visual.ringPrimitive,
|
||||
);
|
||||
governorRequestRender('awareness-visual');
|
||||
}
|
||||
clearAwarenessEchoField();
|
||||
if (layerState.visual?.entities && layerState.viewer) {
|
||||
for (const entity of layerState.visual.entities)
|
||||
layerState.viewer.entities.remove(entity);
|
||||
@@ -348,7 +678,12 @@ export function createRendering({
|
||||
0,
|
||||
);
|
||||
const key = `${subject.layerId}:${subject.id}`;
|
||||
if (layerState.visual?.key === key) {
|
||||
const reducedMotion = prefersReducedMotion();
|
||||
// A reduced-motion change rebuilds the visual, with or without pulses.
|
||||
if (
|
||||
layerState.visual?.key === key &&
|
||||
layerState.visual.reducedMotion === reducedMotion
|
||||
) {
|
||||
// Move the ring only after a meaningful displacement so live tracking
|
||||
// does not rebuild its geometry for sub-pixel motion every 750 ms.
|
||||
if (
|
||||
@@ -360,9 +695,22 @@ export function createRendering({
|
||||
AWARENESS_RADIUS_M,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
);
|
||||
for (const entity of layerState.visual.entities)
|
||||
entity.polyline.positions.setValue(positions);
|
||||
// The echo field reads `visual.center` in place and follows on its
|
||||
// own. The pulse disc follows by its model matrix and is rebuilt only
|
||||
// every `gradientRebuildM`: a build costs a few milliseconds.
|
||||
layerState.visual.ringPositions = positions;
|
||||
const { ringPrimitive } = layerState.visual;
|
||||
if (ringPrimitive) {
|
||||
const primitives = layerState.viewer.scene.primitives;
|
||||
layerState.visual.ringPrimitive = primitives.add(
|
||||
createRingPrimitive(positions, ringPrimitive.appearance.material),
|
||||
);
|
||||
primitives.remove(ringPrimitive);
|
||||
} else layerState.visual.ring.polyline.positions.setValue(positions);
|
||||
Cesium.Cartesian3.clone(groundCenter, layerState.visual.center);
|
||||
// A resting disc is hidden, so it catches up when the pulses wake.
|
||||
if (performance.now() < layerState.visual.wake?.untilMs)
|
||||
followPulseDisc();
|
||||
// Content actually changed — buy exactly one frame instead of holding.
|
||||
governorRequestRender('awareness-visual');
|
||||
}
|
||||
@@ -371,35 +719,188 @@ export function createRendering({
|
||||
clearVisual();
|
||||
|
||||
const entities = [];
|
||||
const scene = layerState.viewer.scene;
|
||||
// A viewer without a primitive collection or a preRender hook (headless
|
||||
// tools, partial stubs) gets the static ring only, as the Cyber sonar
|
||||
// scene does. So does a viewer who prefers reduced motion.
|
||||
const animate = Boolean(
|
||||
!reducedMotion &&
|
||||
scene?.primitives?.add &&
|
||||
scene?.preRender?.addEventListener &&
|
||||
scene?.postRender?.addEventListener,
|
||||
);
|
||||
// Pulses run from now until `wake.untilMs`, then rest.
|
||||
const wake = animate
|
||||
? wakeAwarenessPulses(
|
||||
{ startMs: -Infinity, untilMs: -Infinity },
|
||||
performance.now(),
|
||||
)
|
||||
: null;
|
||||
// From a camera below the rim height the disc would sweep across the sky,
|
||||
// so it is hidden there, and the pulses rest with it: no flash, no
|
||||
// echoes, no frames.
|
||||
const belowRim = () => cameraHeightM(scene) < CONTEXT_RIM_HEIGHT_M;
|
||||
const levelAt = (nowMs) =>
|
||||
wake && !belowRim() ? awarenessPulseLevel(nowMs, wake) : 0;
|
||||
|
||||
// A polyline, not an ellipse outline: WebGL draws ellipse outlines at
|
||||
// 1 px whatever `outlineWidth` says, and the ring needs a halo.
|
||||
const ring = AWARENESS_RANGE_RING_STYLE;
|
||||
entities.push(
|
||||
layerState.viewer.entities.add({
|
||||
const core = Cesium.Color.fromCssColorString(ring.color);
|
||||
const halo = Cesium.Color.fromCssColorString(ring.outlineColor);
|
||||
const ringPositions = awarenessRangeRingPositions(
|
||||
groundCenter,
|
||||
AWARENESS_RADIUS_M,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
);
|
||||
// While pulses run, the ring flashes as each one arrives and otherwise
|
||||
// dims to `restOpacity`; as they settle it returns to full and stays.
|
||||
const ringAlpha = (nowMs) => {
|
||||
const pulsed = Math.max(ring.restOpacity, awarenessRingFlash(nowMs));
|
||||
return 1 - levelAt(nowMs) * (1 - pulsed);
|
||||
};
|
||||
let ringEntity = null;
|
||||
let ringMaterial = null;
|
||||
let ringPrimitive = null;
|
||||
if (scene?.primitives?.add) {
|
||||
ringMaterial = Cesium.Material.fromType('PolylineOutline', {
|
||||
color: core.clone(),
|
||||
outlineColor: halo.clone(),
|
||||
outlineWidth: ring.outlineWidth,
|
||||
});
|
||||
ringPrimitive =
|
||||
scene.primitives.add(
|
||||
createRingPrimitive(ringPositions, ringMaterial),
|
||||
) ?? null;
|
||||
}
|
||||
if (!ringPrimitive) {
|
||||
// Headless tools and partial stubs have no primitive collection; they
|
||||
// get the static ring as an entity.
|
||||
ringEntity = layerState.viewer.entities.add({
|
||||
polyline: {
|
||||
positions: new Cesium.ConstantProperty(
|
||||
awarenessRangeRingPositions(
|
||||
groundCenter,
|
||||
AWARENESS_RADIUS_M,
|
||||
CONTEXT_RIM_HEIGHT_M,
|
||||
),
|
||||
),
|
||||
positions: new Cesium.ConstantProperty(ringPositions),
|
||||
width: ring.width,
|
||||
arcType: Cesium.ArcType.NONE,
|
||||
material: new Cesium.PolylineOutlineMaterialProperty({
|
||||
color: Cesium.Color.fromCssColorString(ring.color),
|
||||
outlineColor: Cesium.Color.fromCssColorString(ring.outlineColor),
|
||||
color: core,
|
||||
outlineColor: halo,
|
||||
outlineWidth: ring.outlineWidth,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
entities.push(ringEntity);
|
||||
}
|
||||
|
||||
const center = Cesium.Cartesian3.clone(groundCenter);
|
||||
let gradient = null;
|
||||
let stopPulses = null;
|
||||
if (animate) {
|
||||
const pulse = AWARENESS_RANGE_PULSE;
|
||||
const count = Math.min(pulse.count, AWARENESS_PULSE_GRADIENT_MAX);
|
||||
const uniforms = {
|
||||
color: core.clone(),
|
||||
lineColor: core.clone(),
|
||||
haloColor: halo.clone(),
|
||||
radii: new Cesium.Cartesian4(),
|
||||
alphas: new Cesium.Cartesian4(),
|
||||
depth: pulse.gradientDepthFraction,
|
||||
lineWidth: pulse.width,
|
||||
haloWidth: pulse.outlineWidth,
|
||||
};
|
||||
uniforms.color.alpha = pulse.gradientOpacity;
|
||||
// A named type: Cesium caches every material type for the page's
|
||||
// lifetime, so an unnamed fabric (a fresh GUID each time) would leave
|
||||
// one entry per new visual. Built from the cached template, the
|
||||
// uniforms come back as plain copies; restore this visual's own.
|
||||
const material = new Cesium.Material({
|
||||
fabric: {
|
||||
type: AWARENESS_PULSE_MATERIAL_TYPE,
|
||||
uniforms,
|
||||
source: PULSE_GRADIENT_SOURCE,
|
||||
},
|
||||
translucent: true,
|
||||
});
|
||||
Object.assign(material.uniforms, uniforms);
|
||||
gradient = scene.primitives.add(
|
||||
createPulseGradient(groundCenter, material),
|
||||
);
|
||||
const radii = [0, 0, 0, 0];
|
||||
const alphas = [0, 0, 0, 0];
|
||||
const removePreRender = scene.preRender.addEventListener(() => {
|
||||
const nowMs = performance.now();
|
||||
const level = levelAt(nowMs);
|
||||
const alpha = ringAlpha(nowMs);
|
||||
ringMaterial.uniforms.color.alpha = core.alpha * alpha;
|
||||
ringMaterial.uniforms.outlineColor.alpha = halo.alpha * alpha;
|
||||
// The disc is looked up each frame: a subject move swaps it.
|
||||
const disc = layerState.visual?.gradient;
|
||||
if (disc) disc.show = level > 0;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const state = awarenessPulseState(nowMs, index);
|
||||
radii[index] = state.radiusM / AWARENESS_RADIUS_M;
|
||||
alphas[index] = state.alpha * level;
|
||||
}
|
||||
Cesium.Cartesian4.fromArray(radii, 0, material.uniforms.radii);
|
||||
Cesium.Cartesian4.fromArray(alphas, 0, material.uniforms.alphas);
|
||||
});
|
||||
// Each drawn frame, whoever asked for it, arms one request a Cyber
|
||||
// sonar interval later, as the Cyber sonar scene does. Requests never
|
||||
// land within 80 ms of a frame, so they cannot beat the detection
|
||||
// lane's 80 ms gate, and they stop once the pulses rest.
|
||||
let timer = null;
|
||||
const removePostRender = scene.postRender.addEventListener(() => {
|
||||
globalThis.clearTimeout(timer);
|
||||
timer = null;
|
||||
if (performance.now() < wake.untilMs && !belowRim())
|
||||
timer = globalThis.setTimeout(() => {
|
||||
timer = null;
|
||||
governorRequestRender('awareness-pulse');
|
||||
}, CYBER_SONAR_RENDER_INTERVAL_MS);
|
||||
});
|
||||
stopPulses = () => {
|
||||
removePreRender();
|
||||
removePostRender();
|
||||
globalThis.clearTimeout(timer);
|
||||
timer = null;
|
||||
};
|
||||
// The detection overlay pulses the brackets of flights and vessels a
|
||||
// front crosses; it reads the centre in place, so it follows too.
|
||||
setAwarenessEchoField({
|
||||
center,
|
||||
radiusM: AWARENESS_RADIUS_M,
|
||||
pulse,
|
||||
echo: AWARENESS_RANGE_ECHO,
|
||||
level: levelAt,
|
||||
});
|
||||
}
|
||||
|
||||
// Turning reduced motion on or off mid-session rebuilds the visual.
|
||||
const motionQuery = globalThis.matchMedia?.(REDUCED_MOTION_QUERY);
|
||||
const onMotionChange = () => {
|
||||
if (layerState.subject) renderVisual(layerState.subject);
|
||||
};
|
||||
// Safari before 14 has only the older addListener / removeListener.
|
||||
if (motionQuery?.addEventListener)
|
||||
motionQuery.addEventListener('change', onMotionChange);
|
||||
else motionQuery?.addListener?.(onMotionChange);
|
||||
|
||||
layerState.visual = {
|
||||
key,
|
||||
entities,
|
||||
center: Cesium.Cartesian3.clone(groundCenter),
|
||||
ring: ringEntity,
|
||||
ringPrimitive,
|
||||
ringPositions,
|
||||
center,
|
||||
gradient,
|
||||
gradientCenter: Cesium.Cartesian3.clone(groundCenter),
|
||||
reducedMotion,
|
||||
wake,
|
||||
stopPulses,
|
||||
removeMotionListener: () => {
|
||||
if (motionQuery?.removeEventListener)
|
||||
motionQuery.removeEventListener('change', onMotionChange);
|
||||
else motionQuery?.removeListener?.(onMotionChange);
|
||||
},
|
||||
};
|
||||
governorRequestRender('awareness-visual');
|
||||
}
|
||||
@@ -413,5 +914,6 @@ export function createRendering({
|
||||
updateDirectionOverlay,
|
||||
clearVisual,
|
||||
renderVisual,
|
||||
wakePulses,
|
||||
};
|
||||
}
|
||||
@@ -59,6 +59,10 @@ export function createState({ services }) {
|
||||
lastCameraPoseSig: '',
|
||||
/** When the pose signature last changed bins (hysteresis anchor). */
|
||||
lastCameraPoseChangeMs: 0,
|
||||
/** When the viewer last handled the camera (pointer, wheel, touch, key). */
|
||||
lastCameraInputMs: Number.NEGATIVE_INFINITY,
|
||||
/** Element the camera-input listeners are attached to. */
|
||||
cameraInputTarget: null,
|
||||
/** Whether the view currently counts as moving (hysteretic, not per-frame). */
|
||||
cameraMoving: false,
|
||||
lastEvaluatedPosition: null,
|
||||
|
||||
Reference in new issue
Block a user