mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 11:42:21 +00:00
Merge main into byrdit/recent-imagery-dateline
This commit is contained in:
commit
46f8ea16c0
105 files changed
+6960
-1269
No files matched your search
@@ -10,7 +10,8 @@ import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
|
||||
import { applicationPinia } from '../ui/vueRuntime.js';
|
||||
import { heightsOf } from '../queries/heights.js';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import { distance } from '../geo/vector.js';
|
||||
import { viewPlanes } from '../geo/frustum.js';
|
||||
import { distance, dot } from '../geo/vector.js';
|
||||
import {
|
||||
canvasOf as sceneCanvasOf,
|
||||
findCamera,
|
||||
@@ -87,11 +88,12 @@ export function createScreenAnnotationRenderer(
|
||||
const arrowMarkers = new Map();
|
||||
let viewBox = null;
|
||||
|
||||
// The eye this frame is projected from (the camera port's pose), and the
|
||||
// query port and canvas it is projected through, read once per pass.
|
||||
// Read the camera pose, query port, canvas and view-frustum planes once
|
||||
// per projection pass.
|
||||
let pose = null;
|
||||
let passQuery = null;
|
||||
let passCanvas = null;
|
||||
let cullingPlanes = null;
|
||||
// The renderer's canvas; a viewer with no renderer bound, its own.
|
||||
const canvasOf = () => sceneCanvasOf(viewer);
|
||||
const records = new Map(); // anno.id -> { key, anno, group, parts }
|
||||
@@ -109,6 +111,18 @@ export function createScreenAnnotationRenderer(
|
||||
const heightCache = new Map();
|
||||
const HEIGHT_CACHE_SOFT = 600; // target size; over this we evict keys not used this frame
|
||||
const HEIGHT_CACHE_HARD = 8000; // absolute ceiling (one big ring + others) — never exceeded
|
||||
// Accepted surface-height range; samples outside it are treated as misses.
|
||||
const MIN_SURFACE_HEIGHT = -430;
|
||||
const MAX_SURFACE_HEIGHT = 9000;
|
||||
const HEIGHT_SAMPLE_BUDGET = 32; // clampNow calls per projection pass
|
||||
const HEIGHT_RETRY_MS = 1000; // minimum interval between misses per anchor
|
||||
// Fair sampling: keys refused by an exhausted budget queue in arrival order,
|
||||
// and each pass reserves budget for the oldest queued keys first, so a fixed
|
||||
// iteration order cannot starve anchors beyond the first budget's worth.
|
||||
const heightQueue = new Set();
|
||||
const heightReserved = new Set(); // queued keys this pass serves first
|
||||
const heightRefused = new Set(); // keys refused during this pass
|
||||
let heightBudget = HEIGHT_SAMPLE_BUDGET; // unreserved slots left this pass
|
||||
let projGen = 0; // bumped each projection frame; entries used this frame are "hot"
|
||||
function trimHeightCache() {
|
||||
if (heightCache.size <= HEIGHT_CACHE_SOFT) return;
|
||||
@@ -136,12 +150,20 @@ export function createScreenAnnotationRenderer(
|
||||
return PALETTE[anno.color] || PALETTE.primary;
|
||||
}
|
||||
|
||||
// Best-effort surface height under a coordinate (clamps onto the 3D tiles).
|
||||
// Returns 0 until the tile loads, then caches the validated height.
|
||||
function groundHeight(lon, lat) {
|
||||
const key = `${lon.toFixed(5)},${lat.toFixed(5)}`;
|
||||
const cached = heightCache.get(key);
|
||||
if (cached && cached.settled) {
|
||||
function clearHeights() {
|
||||
heightCache.clear();
|
||||
heightQueue.clear();
|
||||
}
|
||||
|
||||
function heightKey(lon, lat) {
|
||||
return `${lon.toFixed(5)},${lat.toFixed(5)}`;
|
||||
}
|
||||
|
||||
// Best-effort surface height under a coordinate (clamps onto the 3D tiles):
|
||||
// the validated height once the tile loads, null until then.
|
||||
// `key` and `cached` are the caller's cache lookup for this coordinate.
|
||||
function groundHeight(lon, lat, key, cached) {
|
||||
if (cached?.settled) {
|
||||
// Mark hot for this frame + bump to most-recently-used so heights for live
|
||||
// marks survive eviction while places we've navigated away from age out.
|
||||
cached.gen = projGen;
|
||||
@@ -149,6 +171,19 @@ export function createScreenAnnotationRenderer(
|
||||
heightCache.set(key, cached);
|
||||
return cached.h;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (cached && now < cached.nextAttempt) {
|
||||
cached.gen = projGen;
|
||||
return null;
|
||||
}
|
||||
if (heightReserved.has(key)) {
|
||||
heightReserved.delete(key);
|
||||
} else if (heightBudget > 0) {
|
||||
heightBudget--;
|
||||
} else {
|
||||
heightRefused.add(key);
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const heights = heightsOf(viewer);
|
||||
if (heights.supported().clamp) {
|
||||
@@ -156,7 +191,11 @@ export function createScreenAnnotationRenderer(
|
||||
const c = heights.clampNow(fromDegrees(lon, lat, 0));
|
||||
if (c) {
|
||||
const h = toLonLatH(c)?.height;
|
||||
if (Number.isFinite(h) && h > -430 && h < 9000) {
|
||||
if (
|
||||
Number.isFinite(h) &&
|
||||
h > MIN_SURFACE_HEIGHT &&
|
||||
h < MAX_SURFACE_HEIGHT
|
||||
) {
|
||||
heightCache.set(key, { h, settled: true, gen: projGen });
|
||||
trimHeightCache();
|
||||
return h;
|
||||
@@ -166,10 +205,13 @@ export function createScreenAnnotationRenderer(
|
||||
} catch {
|
||||
/* tiles not ready */
|
||||
}
|
||||
const fallback = cached ? cached.h : 0;
|
||||
heightCache.set(key, { h: fallback, settled: false, gen: projGen });
|
||||
heightCache.set(key, {
|
||||
settled: false,
|
||||
gen: projGen,
|
||||
nextAttempt: now + HEIGHT_RETRY_MS,
|
||||
});
|
||||
trimHeightCache();
|
||||
return fallback;
|
||||
return null;
|
||||
}
|
||||
|
||||
function add(anno) {
|
||||
@@ -313,7 +355,7 @@ export function createScreenAnnotationRenderer(
|
||||
} catch {
|
||||
/* the board is unreachable */
|
||||
}
|
||||
if (records.size === 0) heightCache.clear();
|
||||
if (records.size === 0) clearHeights();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -365,22 +407,32 @@ export function createScreenAnnotationRenderer(
|
||||
// Area-type updates route through the hybrid proxy only.
|
||||
}
|
||||
|
||||
function project(lon, lat, allowOffscreen = false) {
|
||||
// The window position of a point at its surface height (0 m until that is
|
||||
// sampled), or null when it is not in view. A point of an arrow, route or
|
||||
// area (`connector`) is sampled even outside the view, so the part of the
|
||||
// mark that is in view runs to the real height of the part that is not.
|
||||
function project(lon, lat, allowOffscreen = false, connector = false) {
|
||||
if (!pose) return null;
|
||||
// Anchor at the real surface height (cached + validated), so marks sit on
|
||||
// the ground/building instead of at sea level. The settle-once cache keeps
|
||||
// it stable (no per-frame jitter that earlier broke nearby projections).
|
||||
const world = fromDegrees(lon, lat, groundHeight(lon, lat));
|
||||
if (!pose) return null;
|
||||
const key = heightKey(lon, lat);
|
||||
const cached = heightCache.get(key);
|
||||
let sample = true;
|
||||
if (!cached?.settled) {
|
||||
// Unsettled: before sampling, cull only if the whole height range is hidden.
|
||||
const low = fromDegrees(lon, lat, MIN_SURFACE_HEIGHT);
|
||||
const high = fromDegrees(lon, lat, MAX_SURFACE_HEIGHT);
|
||||
if (heightRangeHidden(low, high)) return null;
|
||||
// A lone point outside the view is not sampled; the entry keeps its
|
||||
// retry time.
|
||||
sample = connector || !rangeOutsideView(low, high);
|
||||
if (!sample && cached) cached.gen = projGen;
|
||||
}
|
||||
const height = sample ? groundHeight(lon, lat, key, cached) : null;
|
||||
const world = fromDegrees(lon, lat, height ?? 0);
|
||||
// Reject points behind the camera (they produce wrapped/extreme coords).
|
||||
const eye = pose.position;
|
||||
const look = pose.direction;
|
||||
if (
|
||||
(world.x - eye.x) * look.x +
|
||||
(world.y - eye.y) * look.y +
|
||||
(world.z - eye.z) * look.z <=
|
||||
0
|
||||
)
|
||||
return null;
|
||||
if (behindEye(world)) return null;
|
||||
// Reject points beyond the globe horizon.
|
||||
const query = passQuery;
|
||||
if (!query || query.isOccluded(world)) return null;
|
||||
@@ -398,6 +450,36 @@ export function createScreenAnnotationRenderer(
|
||||
return { x: win.x, y: win.y };
|
||||
}
|
||||
|
||||
// Points along one surface normal are linear in height, and each rejection
|
||||
// region (behind the camera plane; the occluder's cone beyond the horizon
|
||||
// plane) is convex. So when both height-range endpoints fail the SAME test,
|
||||
// every intermediate height fails it too. Mixed failures prove nothing.
|
||||
function heightRangeHidden(low, high) {
|
||||
if (behindEye(low) && behindEye(high)) return true;
|
||||
return Boolean(passQuery?.isOccluded(low) && passQuery.isOccluded(high));
|
||||
}
|
||||
|
||||
// Whether the height range lies wholly outside one view-frustum plane, so
|
||||
// no accepted height under the point is in view.
|
||||
function rangeOutsideView(low, high) {
|
||||
if (!cullingPlanes) return false;
|
||||
for (const { normal, w } of cullingPlanes)
|
||||
if (dot(normal, low) + w < 0 && dot(normal, high) + w < 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Whether `point` is on or behind the camera plane (needs a pose).
|
||||
function behindEye(point) {
|
||||
const eye = pose.position;
|
||||
const look = pose.direction;
|
||||
return (
|
||||
(point.x - eye.x) * look.x +
|
||||
(point.y - eye.y) * look.y +
|
||||
(point.z - eye.z) * look.z <=
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
// Tracked-entity z-order: the tracked aircraft is a Cesium billboard in the
|
||||
// CANVAS, which sits BELOW this SVG overlay (z-90, HTML over canvas). So a screen mark
|
||||
// could hide it. After layout, any mark whose ACTUAL projected bounding box (rings,
|
||||
@@ -477,8 +559,16 @@ export function createScreenAnnotationRenderer(
|
||||
publish();
|
||||
return;
|
||||
}
|
||||
heightReserved.clear();
|
||||
for (const key of heightQueue) {
|
||||
if (heightReserved.size >= HEIGHT_SAMPLE_BUDGET) break;
|
||||
heightReserved.add(key);
|
||||
}
|
||||
heightBudget = HEIGHT_SAMPLE_BUDGET - heightReserved.size;
|
||||
heightRefused.clear();
|
||||
projGen += 1; // new frame: entries touched below are "hot" and survive trimming
|
||||
pose = findCamera(viewer)?.pose() ?? null;
|
||||
cullingPlanes = viewPlanes(pose);
|
||||
passQuery = findQuery(viewer);
|
||||
passCanvas = canvasOf();
|
||||
const trackedRect = trackedEntityRect();
|
||||
@@ -515,7 +605,9 @@ export function createScreenAnnotationRenderer(
|
||||
const polygons = anno.polygons?.length ? anno.polygons : [[anno.ring]];
|
||||
for (const polygon of polygons) {
|
||||
const projectedRings = polygon.map((ring) =>
|
||||
ring.map(([lon, lat]) => project(lon, lat, polygon.length > 1)),
|
||||
ring.map(([lon, lat]) =>
|
||||
project(lon, lat, polygon.length > 1, true),
|
||||
),
|
||||
);
|
||||
// Keep the historical visible-outer projection, but never fill over
|
||||
// an unprojectable hole or hide another independently visible part.
|
||||
@@ -549,8 +641,8 @@ export function createScreenAnnotationRenderer(
|
||||
group.display = 'none';
|
||||
}
|
||||
} else if (anno.type === 'arrow' && parts.path) {
|
||||
const a = project(anno.anchor.lon, anno.anchor.lat);
|
||||
const b = project(anno.to.lon, anno.to.lat);
|
||||
const a = project(anno.anchor.lon, anno.anchor.lat, false, true);
|
||||
const b = project(anno.to.lon, anno.to.lat, false, true);
|
||||
if (a && b) {
|
||||
// gentle arc so the connector reads as a drawn gesture, not a ruler line
|
||||
const mx = (a.x + b.x) / 2;
|
||||
@@ -575,7 +667,9 @@ export function createScreenAnnotationRenderer(
|
||||
group.display = 'none';
|
||||
}
|
||||
} else if (anno.type === 'route' && parts.poly) {
|
||||
const projected = anno.path.map((pt) => project(pt.lon, pt.lat));
|
||||
const projected = anno.path.map((pt) =>
|
||||
project(pt.lon, pt.lat, false, true),
|
||||
);
|
||||
const pts = [];
|
||||
for (const p of projected) {
|
||||
if (p) pts.push(`${p.x.toFixed(1)},${p.y.toFixed(1)}`);
|
||||
@@ -637,6 +731,11 @@ export function createScreenAnnotationRenderer(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Still-refused queued keys keep their place; new refusals join the back.
|
||||
// Keys no longer requesting a sample (settled, culled, removed) drop out.
|
||||
for (const key of heightQueue)
|
||||
if (!heightRefused.has(key)) heightQueue.delete(key);
|
||||
for (const key of heightRefused) heightQueue.add(key);
|
||||
|
||||
// Keep clustered callouts readable.
|
||||
const placed = [];
|
||||
@@ -824,7 +923,7 @@ export function createScreenAnnotationRenderer(
|
||||
records.delete(anno.id);
|
||||
publish();
|
||||
// Board emptied → drop accumulated height samples (natural reset point).
|
||||
if (records.size === 0) heightCache.clear();
|
||||
if (records.size === 0) clearHeights();
|
||||
}
|
||||
|
||||
function sync() {
|
||||
@@ -847,7 +946,7 @@ export function createScreenAnnotationRenderer(
|
||||
records.clear();
|
||||
leaving.clear();
|
||||
byKey.clear();
|
||||
heightCache.clear();
|
||||
clearHeights();
|
||||
}
|
||||
|
||||
// Claim the board; from here on only this renderer's own board changes.
|
||||
|
||||
@@ -178,10 +178,17 @@ test('an arrow defines its arrowhead and drops the dash once drawn on', async (t
|
||||
test('outline upgrade preserves the existing SVG group identity', async (t) => {
|
||||
const { store, svg, groups } = board(t);
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.ZERO,
|
||||
directionWC: Cesium.Cartesian3.ZERO,
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(-97.5, 31.2, 1000000),
|
||||
directionWC: Cesium.Cartesian3.normalize(
|
||||
Cesium.Cartesian3.negate(
|
||||
Cesium.Cartesian3.fromDegrees(-97.5, 31.2),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
positionCartographic: { height: 1000 },
|
||||
};
|
||||
projectTo(t, { x: 100, y: 100 });
|
||||
const sampledAnchors = [];
|
||||
const scene = sceneFor(camera, {
|
||||
canvas: { clientWidth: 1280, clientHeight: 720, width: 1280, height: 720 },
|
||||
@@ -586,3 +593,537 @@ test('a mark hidden from Draw is not drawn or placed, and comes back when shown'
|
||||
await settle();
|
||||
assert.equal(drawn(), true, 'shown again, it is drawn');
|
||||
});
|
||||
|
||||
test('hidden and back-facing annotations do not sample; visible unresolved heights have bounded retries', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1000 });
|
||||
projectTo(t, { x: 100, y: 100 });
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 100000),
|
||||
directionWC: new Cesium.Cartesian3(-1, 0, 0),
|
||||
upWC: new Cesium.Cartesian3(0, 0, 1),
|
||||
positionCartographic: { height: 100000 },
|
||||
};
|
||||
let samples = 0;
|
||||
const postRender = new Cesium.Event();
|
||||
const scene = {
|
||||
camera,
|
||||
canvas: { width: 800, height: 600 },
|
||||
postRender,
|
||||
sampleHeightSupported: true,
|
||||
sampleHeight() {
|
||||
samples++;
|
||||
},
|
||||
};
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
const mark = (id, lon) => ({
|
||||
id,
|
||||
type: 'label',
|
||||
anchor: { lon, lat: 0 },
|
||||
label: id,
|
||||
});
|
||||
renderer.add(mark('far-side', 180));
|
||||
for (let i = 0; i < 100; i++) postRender.raiseEvent();
|
||||
assert.equal(samples, 0);
|
||||
renderer.add(mark('near-side', 0));
|
||||
for (let i = 0; i < 100; i++) postRender.raiseEvent();
|
||||
assert.equal(samples, 1);
|
||||
t.mock.timers.tick(999);
|
||||
postRender.raiseEvent();
|
||||
assert.equal(samples, 1, 'no retry within a second of the miss');
|
||||
t.mock.timers.tick(1);
|
||||
postRender.raiseEvent();
|
||||
assert.equal(samples, 2, 'one retry once a second has passed');
|
||||
for (let i = 0; i < 9; i++) {
|
||||
t.mock.timers.tick(1000);
|
||||
postRender.raiseEvent();
|
||||
}
|
||||
assert.equal(samples, 11);
|
||||
renderer.update(mark('near-side', 0), { empty: true });
|
||||
t.mock.timers.tick(1000);
|
||||
postRender.raiseEvent();
|
||||
assert.equal(samples, 11, 'hidden records do not sample');
|
||||
// With no perspective frustum (no view planes), only the range's
|
||||
// behind-camera test keeps this anchor from sampling.
|
||||
camera.directionWC = new Cesium.Cartesian3(1, 0, 0);
|
||||
camera.frustum = new Cesium.OrthographicOffCenterFrustum();
|
||||
renderer.update(mark('near-side', 0));
|
||||
postRender.raiseEvent();
|
||||
assert.equal(samples, 11, 'behind-camera anchors do not sample');
|
||||
delete camera.frustum;
|
||||
// Turned 45 degrees east: the anchor is in front and above the horizon,
|
||||
// but outside the 60-degree frustum at every accepted height.
|
||||
camera.directionWC = new Cesium.Cartesian3(-Math.SQRT1_2, Math.SQRT1_2, 0);
|
||||
postRender.raiseEvent();
|
||||
assert.equal(samples, 11, 'outside-frustum anchors do not sample');
|
||||
camera.directionWC = new Cesium.Cartesian3(-1, 0, 0);
|
||||
const before = samples;
|
||||
renderer.add({
|
||||
id: 'large-area',
|
||||
type: 'area',
|
||||
label: 'Area',
|
||||
ring: Array.from({ length: 100 }, (_, i) => [0.001 + i / 10000, 0]),
|
||||
anchor: { lon: 0, lat: 0 },
|
||||
});
|
||||
assert.equal(
|
||||
samples - before,
|
||||
32,
|
||||
'a projection pass caps synchronous surface work',
|
||||
);
|
||||
renderer.destroy();
|
||||
assert.equal(postRender.numberOfListeners, 0);
|
||||
});
|
||||
|
||||
function cartographicLon(carto) {
|
||||
return Number(Cesium.Math.toDegrees(carto.longitude).toFixed(5));
|
||||
}
|
||||
|
||||
/** A board with no view mounted: tests read the store's marks. Animation frames run at once. */
|
||||
function samplingBoard(t) {
|
||||
const previousRaf = globalThis.requestAnimationFrame;
|
||||
globalThis.requestAnimationFrame = (fn) => {
|
||||
fn();
|
||||
return 1;
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.requestAnimationFrame = previousRaf;
|
||||
});
|
||||
return useScreenAnnotationsStore(createPinia());
|
||||
}
|
||||
|
||||
/** The screen renderer over a viewer double around `scene`. */
|
||||
function samplingRenderer(store, scene) {
|
||||
return createScreenAnnotationRenderer(
|
||||
{ scene, camera: scene.camera, trackedEntity: null },
|
||||
{ store, activeTrackedReadoutId: () => null },
|
||||
);
|
||||
}
|
||||
|
||||
function squareFrustum() {
|
||||
const frustum = new Cesium.PerspectiveFrustum();
|
||||
frustum.fov = Cesium.Math.toRadians(60);
|
||||
frustum.aspectRatio = 1;
|
||||
frustum.near = 1;
|
||||
frustum.far = 1e8;
|
||||
return frustum;
|
||||
}
|
||||
|
||||
const metresEast = (m) => Number((m / 111319.49).toFixed(5)); // degrees of longitude at the equator
|
||||
const metresNorth = (m) => Number((m / 110574).toFixed(5)); // degrees of latitude at the equator
|
||||
const at = (p, h) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, h);
|
||||
|
||||
/**
|
||||
* A camera double `height` m above (0, 0) looking due east (+Y), pitched
|
||||
* `pitchDeg` up (+X is up there).
|
||||
*/
|
||||
function eastwardCamera(height, pitchDeg = 0) {
|
||||
const p = Cesium.Math.toRadians(pitchDeg);
|
||||
return {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, height),
|
||||
directionWC: new Cesium.Cartesian3(Math.sin(p), Math.cos(p), 0),
|
||||
upWC: new Cesium.Cartesian3(Math.cos(p), -Math.sin(p), 0),
|
||||
positionCartographic: { height },
|
||||
frustum: squareFrustum(),
|
||||
};
|
||||
}
|
||||
|
||||
/** The drawn end point of the board's only arrow, or null when it is hidden. */
|
||||
function arrowEnd(store) {
|
||||
const [mark] = store.board.marks;
|
||||
const path = mark.children.find((child) => child?.attrs?.class?.includes('gev-anno-arrow'));
|
||||
const end = path?.attrs.d?.match(/(-?[\d.]+) (-?[\d.]+)$/);
|
||||
return mark.display === '' && end ? { x: Number(end[1]), y: Number(end[2]) } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Project through `camera` (position, direction, up, square frustum) onto an
|
||||
* 800 x 800 canvas for the test's length; returns that projection.
|
||||
*/
|
||||
function projectThrough(t, camera, size = 800) {
|
||||
const tan = Math.tan(camera.frustum.fov / 2);
|
||||
const toWindow = (world) => {
|
||||
const right = Cesium.Cartesian3.cross(camera.directionWC, camera.upWC, new Cesium.Cartesian3());
|
||||
const v = Cesium.Cartesian3.subtract(world, camera.positionWC, new Cesium.Cartesian3());
|
||||
const z = Cesium.Cartesian3.dot(v, camera.directionWC);
|
||||
return {
|
||||
x: ((Cesium.Cartesian3.dot(v, right) / z / tan + 1) / 2) * size,
|
||||
y: ((1 - Cesium.Cartesian3.dot(v, camera.upWC) / z / tan) / 2) * size,
|
||||
};
|
||||
};
|
||||
projectTo(t, (_scene, world) => toWindow(world));
|
||||
return toWindow;
|
||||
}
|
||||
|
||||
/** Whether `point`'s accepted heights (a 9.5 km sphere holds them) are all outside `camera`'s frustum. */
|
||||
function outsideFrustum(camera, point) {
|
||||
const volume = camera.frustum.computeCullingVolume(camera.positionWC, camera.directionWC, camera.upWC);
|
||||
return volume.computeVisibility(new Cesium.BoundingSphere(point, 9500)) === Cesium.Intersect.OUTSIDE;
|
||||
}
|
||||
|
||||
/**
|
||||
* An 800 x 800 scene over `camera` whose surface under a longitude is
|
||||
* `surface(lon)`; `sampled` lists the sampled longitudes.
|
||||
*/
|
||||
function surfaceScene(camera, surface) {
|
||||
const sampled = [];
|
||||
const postRender = new Cesium.Event();
|
||||
const scene = {
|
||||
camera,
|
||||
canvas: { width: 800, height: 800 },
|
||||
postRender,
|
||||
sampleHeightSupported: true,
|
||||
sampleHeight(cartographic) {
|
||||
const lon = cartographicLon(cartographic);
|
||||
sampled.push(lon);
|
||||
return surface(lon);
|
||||
},
|
||||
};
|
||||
return { scene, postRender, sampled };
|
||||
}
|
||||
|
||||
test('an arrow with one endpoint outside a real frustum keeps its visible connector', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
// 30 km straight down over (0, 0): east is +Y, north is +Z in ECEF here.
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 30000),
|
||||
directionWC: new Cesium.Cartesian3(-1, 0, 0),
|
||||
upWC: new Cesium.Cartesian3(0, 0, 1),
|
||||
positionCartographic: { height: 30000 },
|
||||
frustum: squareFrustum(),
|
||||
};
|
||||
const toWindow = projectThrough(t, camera);
|
||||
// 35 km east: in front of the camera and the horizon, but outside the
|
||||
// frustum at every accepted height.
|
||||
const far = { lon: metresEast(35000), lat: 0 };
|
||||
assert.ok(outsideFrustum(camera, at(far, 0)));
|
||||
const farWin = toWindow(at(far, 0));
|
||||
assert.ok(farWin.x > 800 && farWin.x < 1600, 'far end off-screen right, inside the 2w limit');
|
||||
const { scene, postRender, sampled } = surfaceScene(camera, () => 0);
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
renderer.add({
|
||||
id: 'partial-arrow',
|
||||
type: 'arrow',
|
||||
label: 'Ridge',
|
||||
anchor: { lon: 0, lat: 0 },
|
||||
to: far,
|
||||
});
|
||||
postRender.raiseEvent();
|
||||
const [mark] = store.board.marks;
|
||||
assert.equal(mark.display, '', 'the arrow stays drawn');
|
||||
const path = mark.children.find((child) => child.attrs.class?.includes('gev-anno-arrow'));
|
||||
assert.ok(path.attrs.d.startsWith('M 400.0 400.0 Q '));
|
||||
assert.ok(path.attrs.d.endsWith(` ${farWin.x.toFixed(1)} ${farWin.y.toFixed(1)}`));
|
||||
assert.deepEqual([...new Set(sampled)], [0, far.lon], 'the off-view end samples too');
|
||||
});
|
||||
|
||||
// The far end lies outside the frustum and beyond the horizon at 0 m, but
|
||||
// above it at its real 100 m height: it is sampled, so the arrow keeps its
|
||||
// connector and label.
|
||||
test('an arrow whose far end is past the horizon only at 0 m keeps its connector', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
const camera = eastwardCamera(100);
|
||||
const toWindow = projectThrough(t, camera);
|
||||
const near = { lon: metresEast(2000), lat: 0 };
|
||||
const bearing = Cesium.Math.toRadians(50);
|
||||
const far = {
|
||||
lon: metresEast(56000 * Math.cos(bearing)),
|
||||
lat: metresNorth(56000 * Math.sin(bearing)),
|
||||
};
|
||||
const surface = { [near.lon]: 10, [far.lon]: 100 };
|
||||
const { scene, postRender } = surfaceScene(camera, (lon) => surface[lon]);
|
||||
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, camera.positionWC);
|
||||
assert.equal(occluder.isPointVisible(at(far, 100)), true, 'far end above the horizon at 100 m');
|
||||
assert.equal(occluder.isPointVisible(at(far, 0)), false, 'far end past the horizon at 0 m');
|
||||
assert.ok(outsideFrustum(camera, at(far, 0)), 'far end outside the frustum at every accepted height');
|
||||
const farWin = toWindow(at(far, 100));
|
||||
assert.ok(farWin.x > -800 && farWin.x < 0, 'far end off-screen left, inside [-w, 2w]');
|
||||
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
renderer.add({
|
||||
id: 'long-arrow',
|
||||
type: 'arrow',
|
||||
label: 'Ridge',
|
||||
anchor: near,
|
||||
to: far,
|
||||
});
|
||||
for (let i = 0; i < 3; i++) postRender.raiseEvent();
|
||||
const [mark] = store.board.marks;
|
||||
assert.equal(mark.display, '', 'the arrow stays drawn');
|
||||
const path = mark.children.find((child) => child.attrs.class?.includes('gev-anno-arrow'));
|
||||
assert.match(path.attrs.d, /^M 400\.0 4\d\d\.\d Q /, 'the connector starts at the on-screen end');
|
||||
});
|
||||
|
||||
test('an arrow whose end crosses the 2h screen limit only at 0 m keeps its connector', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
const camera = eastwardCamera(18000);
|
||||
const toWindow = projectThrough(t, camera);
|
||||
const start = { lon: metresEast(40000), lat: 0 };
|
||||
const end = { lon: metresEast(10000), lat: 0 };
|
||||
const { scene, postRender, sampled } = surfaceScene(camera, (lon) => (lon === end.lon ? 1500 : 0));
|
||||
assert.ok(toWindow(at(start, 0)).y < 800, 'start on screen');
|
||||
assert.ok(outsideFrustum(camera, at(end, 0)), 'end sphere outside the frustum');
|
||||
assert.ok(toWindow(at(end, 1500)).y < 1600, 'end inside the limit at its real height');
|
||||
assert.ok(toWindow(at(end, 0)).y > 1600, 'end past the limit at 0 m');
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
renderer.add({ id: 'a', type: 'arrow', label: 'Ridge', anchor: start, to: end });
|
||||
for (let i = 0; i < 3; i++) postRender.raiseEvent();
|
||||
assert.equal(store.board.marks[0].display, '', 'the partly visible arrow stays drawn');
|
||||
assert.deepEqual([...new Set(sampled)], [start.lon, end.lon], 'the off-view end samples too');
|
||||
});
|
||||
|
||||
test('an upward-looking arrow keeps a far end that is behind the eye only at 0 m', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
const camera = eastwardCamera(100, 59);
|
||||
projectThrough(t, camera);
|
||||
// Roofs: 132 m 19 m east (in view), 145 m 12 m west (above the view).
|
||||
const start = { lon: metresEast(19), lat: 0 };
|
||||
const end = { lon: metresEast(-12), lat: 0 };
|
||||
const { scene, postRender } = surfaceScene(camera, (lon) => (lon === start.lon ? 132 : 145));
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
renderer.add({ id: 'up', type: 'arrow', label: 'Tower', anchor: start, to: end });
|
||||
for (let i = 0; i < 4; i++) postRender.raiseEvent();
|
||||
const drawn = arrowEnd(store);
|
||||
assert.ok(drawn, 'the arrow from the on-screen roof is drawn');
|
||||
assert.ok(drawn.y < 0 && drawn.y > -800, `the connector leaves through the top edge (end y ${drawn.y})`);
|
||||
});
|
||||
|
||||
test('an arrow crossing the view between two off-view ends on a plateau is drawn', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
const camera = eastwardCamera(4000);
|
||||
projectThrough(t, camera);
|
||||
// Both ends 2 km ahead and 2 km to either side on a 4000 m plateau: at 0 m
|
||||
// both fall past the 2h limit, at 4000 m the arc crosses the screen.
|
||||
const a = { lon: metresEast(2000), lat: metresNorth(2000) };
|
||||
const b = { lon: metresEast(2000), lat: metresNorth(-2000) };
|
||||
const { scene, postRender } = surfaceScene(camera, () => 4000);
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
renderer.add({ id: 'plateau', type: 'arrow', label: 'Pass', anchor: a, to: b });
|
||||
for (let i = 0; i < 4; i++) postRender.raiseEvent();
|
||||
const drawn = arrowEnd(store);
|
||||
assert.ok(drawn, 'the arrow is drawn');
|
||||
assert.ok(Math.abs(drawn.y - 400) < 5, `the connector crosses at eye level (end y ${drawn.y})`);
|
||||
});
|
||||
|
||||
test('an arrow to an off-view peak points at the peak, not at 0 m below it', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
const camera = eastwardCamera(4000);
|
||||
projectThrough(t, camera);
|
||||
// From a 4000 m plateau 2 km ahead to a 4500 m peak just left of the view.
|
||||
const start = { lon: metresEast(2000), lat: 0 };
|
||||
const end = { lon: metresEast(1000), lat: metresNorth(900) };
|
||||
const { scene, postRender } = surfaceScene(camera, (lon) => (lon === start.lon ? 4000 : 4500));
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
renderer.add({ id: 'peak', type: 'arrow', label: 'Peak', anchor: start, to: end });
|
||||
for (let i = 0; i < 4; i++) postRender.raiseEvent();
|
||||
const drawn = arrowEnd(store);
|
||||
assert.ok(drawn, 'the arrow is drawn');
|
||||
assert.ok(
|
||||
Math.abs(drawn.x + 223.8) < 2 && Math.abs(drawn.y - 53.8) < 2,
|
||||
`end at the 4500 m projection (-223.8, 53.8), got (${drawn.x}, ${drawn.y})`,
|
||||
);
|
||||
});
|
||||
|
||||
test('a lone label beyond the horizon just outside the view stays hidden', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
const camera = eastwardCamera(100);
|
||||
const toWindow = projectThrough(t, camera);
|
||||
const bearing = Cesium.Math.toRadians(34);
|
||||
const anchor = {
|
||||
lon: metresEast(200000 * Math.cos(bearing)),
|
||||
lat: metresNorth(200000 * Math.sin(bearing)),
|
||||
};
|
||||
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, camera.positionWC);
|
||||
assert.equal(occluder.isPointVisible(at(anchor, 0)), false, 'beyond the horizon at 0 m');
|
||||
assert.ok(outsideFrustum(camera, at(anchor, 0)), 'sphere outside the frustum');
|
||||
assert.ok(toWindow(at(anchor, 0)).x > -800, 'projection inside [-w, 2w]');
|
||||
const { scene, postRender } = surfaceScene(camera, () => 0);
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
renderer.add({ id: 'l', type: 'label', label: 'Far city', anchor });
|
||||
for (let i = 0; i < 3; i++) postRender.raiseEvent();
|
||||
assert.equal(store.board.marks[0].display, 'none', 'its callout does not peek in at the left edge');
|
||||
});
|
||||
|
||||
test('an arrow wholly beyond the horizon is not drawn across the screen', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
const camera = eastwardCamera(100);
|
||||
projectThrough(t, camera);
|
||||
const a = { lon: metresEast(80000), lat: metresNorth(67000) };
|
||||
const b = { lon: metresEast(80000), lat: metresNorth(-67000) };
|
||||
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, camera.positionWC);
|
||||
for (const point of [a, b]) {
|
||||
assert.equal(occluder.isPointVisible(at(point, 0)), false, 'end beyond the horizon at 0 m');
|
||||
assert.ok(outsideFrustum(camera, at(point, 0)), 'end sphere outside the frustum');
|
||||
}
|
||||
const { scene, postRender } = surfaceScene(camera, () => 0);
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
renderer.add({ id: 'x', type: 'arrow', label: 'Ghost', anchor: a, to: b });
|
||||
for (let i = 0; i < 3; i++) postRender.raiseEvent();
|
||||
assert.equal(store.board.marks[0].display, 'none', 'no ghost connector');
|
||||
});
|
||||
|
||||
test('a visible area ring keeps a vertex past the horizon only at 0 m', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
const camera = eastwardCamera(100);
|
||||
const toWindow = projectThrough(t, camera);
|
||||
const bearing = Cesium.Math.toRadians(50);
|
||||
const far = { lon: metresEast(56000 * Math.cos(bearing)), lat: metresNorth(56000 * Math.sin(bearing)) };
|
||||
const nearLon = metresEast(2000);
|
||||
const vertices = [
|
||||
{ lon: nearLon, lat: metresNorth(300) },
|
||||
{ lon: nearLon, lat: metresNorth(-300) },
|
||||
far,
|
||||
];
|
||||
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, camera.positionWC);
|
||||
assert.ok(outsideFrustum(camera, at(far, 0)));
|
||||
assert.equal(occluder.isPointVisible(at(far, 0)), false);
|
||||
assert.equal(occluder.isPointVisible(at(far, 100)), true);
|
||||
const { scene, postRender, sampled } = surfaceScene(camera, (lon) => (lon === far.lon ? 100 : 10));
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
renderer.add({
|
||||
id: 'triangle', type: 'area', label: 'Ridge', anchor: vertices[0],
|
||||
ring: vertices.map(({ lon, lat }) => [lon, lat]),
|
||||
});
|
||||
postRender.raiseEvent();
|
||||
const [mark] = store.board.marks;
|
||||
assert.equal(mark.display, '', 'the triangle stays drawn');
|
||||
const path = mark.children.find((child) => child.attrs.class?.includes('gev-anno-area'));
|
||||
const coords = vertices.map((p) => {
|
||||
const { x, y } = toWindow(at(p, p === far ? 100 : 10));
|
||||
return `${x.toFixed(1)},${y.toFixed(1)}`;
|
||||
});
|
||||
assert.equal(path.attrs.d, `M ${coords.join(' L ')} Z`, 'the far vertex sits at its real height');
|
||||
assert.deepEqual(sampled, [nearLon, nearLon, far.lon], 'the off-view vertex samples too');
|
||||
});
|
||||
|
||||
test('a low-angle cached roof stays visible when range endpoints fail different tests', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
projectTo(t, { x: 400, y: 380 });
|
||||
// Camera 1 m above the ellipsoid, heading east, pitched 25 degrees down.
|
||||
const pitch = Cesium.Math.toRadians(25);
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1),
|
||||
directionWC: new Cesium.Cartesian3(-Math.sin(pitch), Math.cos(pitch), 0),
|
||||
upWC: new Cesium.Cartesian3(Math.cos(pitch), Math.sin(pitch), 0),
|
||||
positionCartographic: { height: 1 },
|
||||
frustum: squareFrustum(),
|
||||
};
|
||||
const roofLon = 4000 / 111319.49;
|
||||
let samples = 0;
|
||||
const postRender = new Cesium.Event();
|
||||
const scene = {
|
||||
camera,
|
||||
canvas: { width: 800, height: 800 },
|
||||
postRender,
|
||||
sampleHeightSupported: true,
|
||||
sampleHeight() {
|
||||
samples++;
|
||||
return 20;
|
||||
},
|
||||
};
|
||||
// Sanity: height 0 is beyond the horizon and 9000 m is behind the camera,
|
||||
// while the 20 m roof itself is in front and above the horizon.
|
||||
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, camera.positionWC);
|
||||
const ahead = (h) => {
|
||||
const p = Cesium.Cartesian3.fromDegrees(roofLon, 0, h);
|
||||
const v = Cesium.Cartesian3.subtract(p, camera.positionWC, new Cesium.Cartesian3());
|
||||
return Cesium.Cartesian3.dot(v, camera.directionWC) > 0;
|
||||
};
|
||||
assert.equal(occluder.isPointVisible(Cesium.Cartesian3.fromDegrees(roofLon, 0, 0)), false);
|
||||
assert.equal(ahead(9000), false);
|
||||
assert.equal(ahead(20), true);
|
||||
assert.equal(occluder.isPointVisible(Cesium.Cartesian3.fromDegrees(roofLon, 0, 20)), true);
|
||||
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
renderer.add({ id: 'roof', type: 'label', label: 'Roof', anchor: { lon: roofLon, lat: 0 } });
|
||||
assert.equal(samples, 1, 'the unknown height is sampled, not culled');
|
||||
assert.equal(store.board.marks[0].display, '');
|
||||
for (let i = 0; i < 5; i++) postRender.raiseEvent();
|
||||
assert.equal(samples, 1, 'the settled height is reused');
|
||||
assert.equal(store.board.marks[0].display, '', 'the cached roof point is tested and shown');
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('height retries beyond the first budget are served under sparse passes', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1000 });
|
||||
projectTo(t, { x: 100, y: 100 });
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 100000),
|
||||
directionWC: new Cesium.Cartesian3(-1, 0, 0),
|
||||
positionCartographic: { height: 100000 },
|
||||
};
|
||||
const lons = Array.from({ length: 33 }, (_, i) => Number(((i + 1) / 1000).toFixed(3)));
|
||||
const last = lons.at(-1);
|
||||
let tilesReady = false;
|
||||
let pass = [];
|
||||
const postRender = new Cesium.Event();
|
||||
const scene = {
|
||||
camera,
|
||||
canvas: { width: 800, height: 600 },
|
||||
postRender,
|
||||
sampleHeightSupported: true,
|
||||
sampleHeight(cartographic) {
|
||||
const lon = cartographicLon(cartographic);
|
||||
pass.push(lon);
|
||||
return tilesReady && lon === last ? 12 : undefined;
|
||||
},
|
||||
};
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
for (const lon of lons) {
|
||||
renderer.add({ id: `p${lon}`, type: 'label', label: 'P', anchor: { lon, lat: 0 } });
|
||||
}
|
||||
assert.ok(pass.includes(last), 'every point gets its initial miss');
|
||||
tilesReady = true; // tiles under the final point arrive after its miss
|
||||
const lastSamples = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
t.mock.timers.tick(1000);
|
||||
pass = [];
|
||||
postRender.raiseEvent();
|
||||
assert.ok(pass.length <= 32, `pass ${i} keeps the 32-sample budget`);
|
||||
lastSamples.push(pass.filter((lon) => lon === last).length);
|
||||
}
|
||||
assert.ok(lastSamples.slice(0, 2).includes(1), 'the 33rd point is served within two passes');
|
||||
assert.equal(lastSamples.at(-1), 0, 'and then stays settled');
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('points refused longest are sampled before newer refusals', (t) => {
|
||||
const store = samplingBoard(t);
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1000 });
|
||||
projectTo(t, { x: 100, y: 100 });
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 100000),
|
||||
directionWC: new Cesium.Cartesian3(-1, 0, 0),
|
||||
positionCartographic: { height: 100000 },
|
||||
};
|
||||
const lons = Array.from({ length: 65 }, (_, i) => Number(((i + 1) / 1000).toFixed(3)));
|
||||
let pass = [];
|
||||
const { scene, postRender } = surfaceScene(camera, (lon) => {
|
||||
pass.push(lon);
|
||||
});
|
||||
const renderer = samplingRenderer(store, scene);
|
||||
t.after(() => renderer.destroy());
|
||||
for (const lon of lons) {
|
||||
renderer.add({ id: `p${lon}`, type: 'label', label: 'P', anchor: { lon, lat: 0 } });
|
||||
}
|
||||
assert.deepEqual(pass, lons, 'every point gets its first miss');
|
||||
const passes = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
t.mock.timers.tick(1000);
|
||||
pass = [];
|
||||
postRender.raiseEvent();
|
||||
passes.push(pass);
|
||||
}
|
||||
assert.deepEqual(passes[0], lons.slice(0, 32), 'a pass serves the first 32 in board order');
|
||||
assert.deepEqual(passes[1], lons.slice(32, 64), 'the next serves the 32 refused longest');
|
||||
assert.deepEqual(passes[2], [...lons.slice(0, 31), lons[64]], 'then the rest of the queue, before newer refusals');
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import { initGeoFileImport } from '../ui/geoFileImport.js';
|
||||
import { useDisplayStore } from '../ui/stores/display.js';
|
||||
import { applicationPinia } from '../ui/vueRuntime.js';
|
||||
import { createContextCardOpener } from '../ui/stores/entityCard.js';
|
||||
import { initImageryBoxTool } from '../ui/imageryBoxTool.js';
|
||||
import { createRecentImageryPanel } from '../ui/recentImagery.js';
|
||||
import { createDataLibrary } from '../library/controller.js';
|
||||
@@ -349,6 +350,8 @@ export function createApplicationTools({
|
||||
dataManager,
|
||||
sceneDirector,
|
||||
annotations,
|
||||
// A voice or chat selection opens its card in Context, as a click does.
|
||||
contextCard: createContextCardOpener(applicationPinia()),
|
||||
});
|
||||
defer(() => {
|
||||
voiceCommands.stop({ removeUi: true });
|
||||
|
||||
@@ -1165,7 +1165,10 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
|
||||
mobileCockpit[1],
|
||||
/@media \(min-width: 390px\) and \(min-height: 240px\),\s*\(min-height: 450px\) \{\s*body\.cockpit-mode\.mobile-shell/,
|
||||
);
|
||||
assert.match(css, /\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/);
|
||||
assert.match(
|
||||
css,
|
||||
/\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/,
|
||||
);
|
||||
assert.match(
|
||||
mobileCockpit[1],
|
||||
/body\.cockpit-mode \.cockpit-utility-control\.is-expanded[\s\S]*?top:\s*96px;/,
|
||||
@@ -1185,8 +1188,14 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
|
||||
});
|
||||
|
||||
test('the unread Stories announcement waits until Cockpit closes', () => {
|
||||
assert.match(css, /body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/);
|
||||
const storiesView = fs.readFileSync(path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'), 'utf8');
|
||||
assert.match(
|
||||
css,
|
||||
/body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/,
|
||||
);
|
||||
const storiesView = fs.readFileSync(
|
||||
path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(
|
||||
storiesView,
|
||||
/async function openExplore\(\) \{[^}]*?if \(await store\.controller\.open\(\)\) markPopSeen\(\);/,
|
||||
@@ -1374,12 +1383,17 @@ test('voice Cockpit entry honours a requested contact layer before it enters', (
|
||||
|
||||
const retarget = ui.slice(
|
||||
ui.indexOf(' _retargetCockpitEntryLayer({'),
|
||||
ui.indexOf(' * Controls cockpit entry/exit and context navigation.'),
|
||||
ui.indexOf(' controlCockpit(\n'),
|
||||
);
|
||||
assert.match(
|
||||
retarget,
|
||||
/militaryAwarenessLayer\.navigateNext\(\{\s*targetLayer,\s*aircraftClass,\s*origin: 'voice',\s*\}\)/,
|
||||
'retargeting reuses filtered navigation with durable voice selection authority',
|
||||
/layer\.trackById\?\.\(match\.icao24, \{ origin: 'voice' \}\)/,
|
||||
'retargeting follows the match with durable voice selection authority',
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
retarget,
|
||||
/militaryAwarenessLayer/,
|
||||
'retargeting needs nothing from Contacts',
|
||||
);
|
||||
assert.match(
|
||||
retarget,
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
// Live HLS through the real /api/cctv middleware. Leases are random
|
||||
// per-playback ids, not bound to the socket address, and a viewer refused for
|
||||
// capacity leaves the camera's health as it was.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { HLS_LIMITS } from '../../server/providers/cctv/stream.js';
|
||||
import { mountCctvProvider } from '../testSupport/cctvProviderHarness.mjs';
|
||||
|
||||
const perSession = HLS_LIMITS.leasesPerSession;
|
||||
const SAME_ORIGIN = { host: 'localhost:4173', 'sec-fetch-site': 'same-origin' };
|
||||
const camera = (id) => ({
|
||||
id,
|
||||
name: id,
|
||||
lat: 30.27,
|
||||
lon: -97.74,
|
||||
feedType: 'hls',
|
||||
url: `https://cams.upstream.invalid/${id}/list.m3u8`,
|
||||
});
|
||||
const PLAYLIST =
|
||||
'#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:12\n#EXTINF:2,\na.ts\n#EXTINF:2,\nb.ts\n#EXTINF:2,\nc.ts\n';
|
||||
const lease = (index) =>
|
||||
`00000000-0000-4000-8000-${String(index).padStart(12, '0')}`;
|
||||
|
||||
/** Mount the provider over three HLS cameras; `failing` upstreams answer 500. */
|
||||
function mount(t, failing = []) {
|
||||
const upstream = [];
|
||||
const app = mountCctvProvider(t, {
|
||||
cameras: ['cam-a', 'cam-b', 'cam-c'].map(camera),
|
||||
fetch: async (url) => {
|
||||
upstream.push(String(url));
|
||||
if (failing.some((id) => String(url).includes(`/${id}/`)))
|
||||
return new Response('', { status: 500 });
|
||||
return new Response(String(url).endsWith('.m3u8') ? PLAYLIST : 'abc');
|
||||
},
|
||||
});
|
||||
return { ...app, upstream };
|
||||
}
|
||||
|
||||
/** Open a playlist and return the first segment path it lists. */
|
||||
async function openPlaylist(call, cameraId, leaseId, remoteAddress) {
|
||||
const res = await call(
|
||||
`/media/${cameraId}?lease=${leaseId}`,
|
||||
SAME_ORIGIN,
|
||||
'GET',
|
||||
remoteAddress,
|
||||
);
|
||||
assert.equal(res.statusCode, 200, `playlist ${cameraId} ${leaseId}`);
|
||||
const segment = res.body
|
||||
.split('\n')
|
||||
.find((line) => line.startsWith('/api/cctv/media/'));
|
||||
assert.ok(segment, 'the playlist lists a segment');
|
||||
return segment.replace('/api/cctv', '');
|
||||
}
|
||||
|
||||
test('viewers behind one shared address get every slot, and no more', async (t) => {
|
||||
assert.equal(HLS_LIMITS.sessions, 2, 'the test fills both sessions');
|
||||
const { call, health } = mount(t);
|
||||
const shared = '::ffff:172.17.0.1';
|
||||
let segment;
|
||||
for (let index = 0; index < 2 * perSession; index++)
|
||||
segment = await openPlaylist(
|
||||
call,
|
||||
index < perSession ? 'cam-a' : 'cam-b',
|
||||
lease(index),
|
||||
shared,
|
||||
);
|
||||
assert.equal(
|
||||
(await call(segment, SAME_ORIGIN, 'GET', shared)).statusCode,
|
||||
200,
|
||||
);
|
||||
const before = await health('cam-a');
|
||||
// A ninth viewer of a full session and a third session are both refused,
|
||||
// without reporting a camera whose upstream is fine as degraded.
|
||||
for (const cameraId of ['cam-a', 'cam-c']) {
|
||||
const refused = await call(
|
||||
`/media/${cameraId}?lease=${lease(2 * perSession)}`,
|
||||
SAME_ORIGIN,
|
||||
'GET',
|
||||
shared,
|
||||
);
|
||||
assert.equal(refused.statusCode, 503, cameraId);
|
||||
assert.equal(refused.headers['Retry-After'], '2');
|
||||
}
|
||||
assert.deepEqual(await health('cam-a'), before);
|
||||
assert.equal(await health('cam-c'), undefined);
|
||||
// A released slot is free for the next viewer.
|
||||
await call(`/media/cam-a?lease=${lease(0)}`, SAME_ORIGIN, 'DELETE', shared);
|
||||
await openPlaylist(call, 'cam-a', lease(2 * perSession), shared);
|
||||
});
|
||||
|
||||
test('a lease keeps working after its viewer reconnects from another address', async (t) => {
|
||||
const { call } = mount(t);
|
||||
await openPlaylist(call, 'cam-a', lease(0), '192.168.1.20');
|
||||
const segment = await openPlaylist(call, 'cam-a', lease(0), '192.168.1.21');
|
||||
assert.equal(
|
||||
(await call(segment, SAME_ORIGIN, 'GET', '192.168.1.21')).statusCode,
|
||||
200,
|
||||
);
|
||||
// A second viewer keeps the session alive, so the 404 below is the released
|
||||
// lease and not a stopped session.
|
||||
const other = await openPlaylist(call, 'cam-a', lease(1), '192.168.1.30');
|
||||
const release = await call(
|
||||
`/media/cam-a?lease=${lease(0)}`,
|
||||
SAME_ORIGIN,
|
||||
'DELETE',
|
||||
'192.168.1.21',
|
||||
);
|
||||
assert.equal(release.statusCode, 204);
|
||||
assert.equal(
|
||||
(await call(segment, SAME_ORIGIN, 'GET', '192.168.1.21')).statusCode,
|
||||
404,
|
||||
);
|
||||
assert.equal(
|
||||
(await call(other, SAME_ORIGIN, 'GET', '192.168.1.30')).statusCode,
|
||||
200,
|
||||
);
|
||||
});
|
||||
|
||||
test('ninth viewer frame fallback preserves active camera health', async (t) => {
|
||||
const { call, health } = mount(t);
|
||||
let segment;
|
||||
for (let index = 0; index < perSession; index++)
|
||||
segment = await openPlaylist(call, 'cam-a', lease(index));
|
||||
const before = await health('cam-a');
|
||||
assert.equal(before.status, 'ok');
|
||||
const refused = await call(
|
||||
`/media/cam-a?lease=${lease(perSession)}`,
|
||||
SAME_ORIGIN,
|
||||
);
|
||||
assert.equal(refused.statusCode, 503);
|
||||
const frame = await call(
|
||||
'/frame/cam-a?label=cam-a&lat=30.27&lon=-97.74',
|
||||
SAME_ORIGIN,
|
||||
);
|
||||
assert.equal(frame.statusCode, 200);
|
||||
assert.equal(
|
||||
(await call(segment, SAME_ORIGIN)).statusCode,
|
||||
200,
|
||||
'admitted viewer still plays',
|
||||
);
|
||||
assert.deepEqual(await health('cam-a'), before);
|
||||
});
|
||||
|
||||
test('third camera frame fallback keeps absent health', async (t) => {
|
||||
const { call, health, upstream } = mount(t);
|
||||
await openPlaylist(call, 'cam-a', lease(0));
|
||||
await openPlaylist(call, 'cam-b', lease(1));
|
||||
const refused = await call(`/media/cam-c?lease=${lease(2)}`, SAME_ORIGIN);
|
||||
assert.equal(refused.statusCode, 503);
|
||||
assert.equal(await health('cam-c'), undefined);
|
||||
const frame = await call(
|
||||
'/frame/cam-c?label=cam-c&lat=30.27&lon=-97.74',
|
||||
SAME_ORIGIN,
|
||||
);
|
||||
assert.equal(frame.statusCode, 200);
|
||||
assert.equal(upstream.filter((url) => url.includes('/cam-c/')).length, 0);
|
||||
assert.equal(
|
||||
await health('cam-c'),
|
||||
undefined,
|
||||
'the fallback frame wrote cam-c health',
|
||||
);
|
||||
});
|
||||
|
||||
test('a failing HLS upstream with free slots is still reported degraded', async (t) => {
|
||||
const { call, health } = mount(t, ['cam-c']);
|
||||
const res = await call(`/media/cam-c?lease=${lease(0)}`, SAME_ORIGIN);
|
||||
assert.equal(res.statusCode, 503);
|
||||
assert.equal(res.headers['Retry-After'], '2');
|
||||
const row = await health('cam-c');
|
||||
assert.deepEqual(
|
||||
{ status: row.status, message: row.message },
|
||||
{ status: 'degraded', message: 'Live HLS unavailable' },
|
||||
);
|
||||
});
|
||||
|
||||
test('a cross-site request can neither read nor release a live HLS lease', async (t) => {
|
||||
const { call } = mount(t);
|
||||
const segment = await openPlaylist(call, 'cam-a', lease(0));
|
||||
const crossSite = { host: 'localhost:4173', 'sec-fetch-site': 'cross-site' };
|
||||
assert.equal((await call(segment, crossSite)).statusCode, 403);
|
||||
assert.equal(
|
||||
(await call(`/media/cam-a?lease=${lease(0)}`, crossSite, 'DELETE'))
|
||||
.statusCode,
|
||||
403,
|
||||
);
|
||||
assert.equal((await call(segment, SAME_ORIGIN)).statusCode, 200);
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
fetchHlsBytes,
|
||||
parseHlsMedia,
|
||||
HLS_LIMITS,
|
||||
HlsCapacityError,
|
||||
} from '../../server/providers/cctv/stream.js';
|
||||
const playlist =
|
||||
'#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:12\n#EXTINF:2,\na.ts\n#EXTINF:2,\nb.ts\n#EXTINF:2,\nc.ts\n';
|
||||
@@ -144,7 +145,7 @@ test('one session is reserved before await; disk-free cache and capacity remain
|
||||
manager.ensure('a', base),
|
||||
]);
|
||||
assert.equal(a, b);
|
||||
await assert.rejects(manager.ensure('b', base));
|
||||
await assert.rejects(manager.ensure('b', base), HlsCapacityError);
|
||||
assert.equal(await manager.waitReady(a), true);
|
||||
assert.deepEqual(manager.stats(), { sessions: 1, bytes: 6 });
|
||||
const text = await manager.buildPlaylist(a, 'a');
|
||||
@@ -261,7 +262,10 @@ test('two consumers share downloads but release and abandoned expiry are indepen
|
||||
await manager.waitReady(a);
|
||||
assert.equal(downloads, 4); // One manifest and three segments, not per consumer.
|
||||
assert.equal(a.leases.size, 2);
|
||||
await assert.rejects(manager.ensure('camera', base, 'viewer-c'));
|
||||
await assert.rejects(
|
||||
manager.ensure('camera', base, 'viewer-c'),
|
||||
HlsCapacityError,
|
||||
);
|
||||
manager.release('camera', 'viewer-a');
|
||||
assert.equal(manager.stats().sessions, 1);
|
||||
assert.equal(manager.getSegment('camera', a.token, 0, 'viewer-a'), null);
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Readable } from 'node:stream';
|
||||
import { cctvProxy } from '../../server/providers/cctv.js';
|
||||
import { mountCctvProvider } from '../testSupport/cctvProviderHarness.mjs';
|
||||
|
||||
const STILL = {
|
||||
id: 'still-fixture',
|
||||
@@ -63,113 +63,17 @@ function upstreamResponse({ status = 200, headers = {}, body = 'payload' }) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Collects what a handler wrote, the way a Node ServerResponse would. */
|
||||
function recordingResponse() {
|
||||
const chunks = [];
|
||||
let finished;
|
||||
const done = new Promise((resolve) => {
|
||||
finished = resolve;
|
||||
});
|
||||
const res = {
|
||||
statusCode: 0,
|
||||
headers: {},
|
||||
writableEnded: false,
|
||||
body: '',
|
||||
writeHead(status, headers) {
|
||||
res.statusCode = status;
|
||||
res.headers = { ...res.headers, ...headers };
|
||||
},
|
||||
setHeader(name, value) {
|
||||
res.headers[name] = value;
|
||||
},
|
||||
write(chunk) {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
return true;
|
||||
},
|
||||
end(chunk) {
|
||||
if (chunk) chunks.push(Buffer.from(chunk));
|
||||
res.writableEnded = true;
|
||||
res.body = Buffer.concat(chunks).toString('utf8');
|
||||
finished();
|
||||
},
|
||||
on() {},
|
||||
once() {},
|
||||
emit() {},
|
||||
destroy() {},
|
||||
};
|
||||
return { res, done };
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount the real provider over the fixture cameras and answer every upstream
|
||||
* request from the supplied function.
|
||||
*/
|
||||
/** Mount the real provider over the fixture cameras, recording upstream requests. */
|
||||
function mount(t, respond) {
|
||||
const before = {
|
||||
json: process.env.CCTV_SOURCES_JSON,
|
||||
file: process.env.CCTV_SOURCES_FILE,
|
||||
austin: process.env.CCTV_FORCE_AUSTIN,
|
||||
serverKey: process.env.GOOGLE_MAPS_SERVER_API_KEY,
|
||||
browserKey: process.env.GOOGLE_MAPS_API_KEY,
|
||||
rateLimit: process.env.GEV_RATELIMIT_GOOGLE_PER_MIN,
|
||||
};
|
||||
process.env.CCTV_SOURCES_JSON = JSON.stringify([
|
||||
STILL,
|
||||
STILL_ALIAS,
|
||||
VIDEO,
|
||||
WEBM,
|
||||
MJPEG,
|
||||
]);
|
||||
process.env.CCTV_SOURCES_FILE = 'absent-source-file.json';
|
||||
process.env.CCTV_FORCE_AUSTIN = '0';
|
||||
// No Street View key: a /frame miss lands on the synthetic billboard rather
|
||||
// than a network call this file does not model.
|
||||
delete process.env.GOOGLE_MAPS_SERVER_API_KEY;
|
||||
delete process.env.GOOGLE_MAPS_API_KEY;
|
||||
// The default Google budget, whatever the shell sets.
|
||||
delete process.env.GEV_RATELIMIT_GOOGLE_PER_MIN;
|
||||
const nativeFetch = globalThis.fetch;
|
||||
const requests = [];
|
||||
globalThis.fetch = async (url, init = {}) => {
|
||||
requests.push({ url: String(url), redirect: init.redirect });
|
||||
return respond({ url: String(url), init });
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.fetch = nativeFetch;
|
||||
for (const [name, value] of [
|
||||
['CCTV_SOURCES_JSON', before.json],
|
||||
['CCTV_SOURCES_FILE', before.file],
|
||||
['CCTV_FORCE_AUSTIN', before.austin],
|
||||
['GOOGLE_MAPS_SERVER_API_KEY', before.serverKey],
|
||||
['GOOGLE_MAPS_API_KEY', before.browserKey],
|
||||
['GEV_RATELIMIT_GOOGLE_PER_MIN', before.rateLimit],
|
||||
]) {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
});
|
||||
|
||||
let handler = null;
|
||||
cctvProxy().configureServer({
|
||||
middlewares: {
|
||||
use: (_route, fn) => {
|
||||
handler = fn;
|
||||
},
|
||||
const app = mountCctvProvider(t, {
|
||||
cameras: [STILL, STILL_ALIAS, VIDEO, WEBM, MJPEG],
|
||||
fetch: async (url, init = {}) => {
|
||||
requests.push({ url: String(url), redirect: init.redirect });
|
||||
return respond({ url: String(url), init });
|
||||
},
|
||||
});
|
||||
assert.ok(handler, 'the CCTV provider must mount a middleware');
|
||||
|
||||
const call = async (path, headers = {}, socket) => {
|
||||
const { res, done } = recordingResponse();
|
||||
await handler({ url: path, headers, method: 'GET', on() {}, socket }, res);
|
||||
await done;
|
||||
return res;
|
||||
};
|
||||
const health = async (id) => {
|
||||
const res = await call('/health');
|
||||
return JSON.parse(res.body).cameras.find((entry) => entry.id === id);
|
||||
};
|
||||
return { call, health, requests };
|
||||
return { ...app, requests };
|
||||
}
|
||||
|
||||
test('a still camera is refused by /media without any upstream request', async (t) => {
|
||||
@@ -405,24 +309,35 @@ test('every CCTV route refuses cross-site requests and admits the app itself', a
|
||||
}),
|
||||
);
|
||||
const host = 'localhost:5173';
|
||||
const paths = [
|
||||
'/sources',
|
||||
'/health',
|
||||
`/stream/${STILL.id}`,
|
||||
`/frame/${STILL.id}`,
|
||||
`/media/${VIDEO.id}`,
|
||||
const lease = '00000000-0000-4000-8000-000000000000';
|
||||
const routes = [
|
||||
['GET', '/sources'],
|
||||
['GET', '/health'],
|
||||
['GET', `/stream/${STILL.id}`],
|
||||
['GET', `/frame/${STILL.id}`],
|
||||
['GET', `/media/${VIDEO.id}`],
|
||||
['GET', `/media/${VIDEO.id}/seg_0.ts?lease=${lease}`],
|
||||
['DELETE', `/media/${VIDEO.id}?lease=${lease}`],
|
||||
];
|
||||
// A catalog refresh would fetch the live packs: a refused request must not
|
||||
// start one.
|
||||
process.env.CCTV_FORCE_AUSTIN = '1';
|
||||
for (const headers of [
|
||||
{ host, 'sec-fetch-site': 'cross-site' },
|
||||
{ host, 'sec-fetch-site': 'same-site' },
|
||||
{ host, origin: 'https://elsewhere.example' },
|
||||
{ host, origin: 'null' },
|
||||
])
|
||||
for (const path of paths) {
|
||||
const res = await app.call(path, headers);
|
||||
assert.equal(res.statusCode, 403, `${path} ${JSON.stringify(headers)}`);
|
||||
for (const [method, path] of routes) {
|
||||
const res = await app.call(path, headers, method);
|
||||
assert.equal(
|
||||
res.statusCode,
|
||||
403,
|
||||
`${method} ${path} ${JSON.stringify(headers)}`,
|
||||
);
|
||||
}
|
||||
assert.deepEqual(app.requests, [], 'a refused request reached an upstream');
|
||||
process.env.CCTV_FORCE_AUSTIN = '0';
|
||||
for (const headers of [
|
||||
{ host, 'sec-fetch-site': 'same-origin' },
|
||||
{ host, origin: `http://${host}` },
|
||||
@@ -578,9 +493,11 @@ test('the Street View fallback spends a per-IP Google budget, and only with a ke
|
||||
app.requests.filter(({ url }) =>
|
||||
url.startsWith('https://maps.googleapis.com/'),
|
||||
).length;
|
||||
const first = { remoteAddress: '203.0.113.7' };
|
||||
const frameSource = async (socket) =>
|
||||
(await app.call(`/frame/${STILL.id}`, {}, socket)).headers['X-CCTV-Source'];
|
||||
const first = '203.0.113.7';
|
||||
const frameSource = async (address) =>
|
||||
(await app.call(`/frame/${STILL.id}`, {}, 'GET', address)).headers[
|
||||
'X-CCTV-Source'
|
||||
];
|
||||
|
||||
// Without a key nothing is spent.
|
||||
for (let i = 0; i < 3; i++)
|
||||
@@ -590,7 +507,9 @@ test('the Street View fallback spends a per-IP Google budget, and only with a ke
|
||||
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
|
||||
// Neither an unknown id nor a forwarded request spends the window.
|
||||
assert.equal(
|
||||
(await app.call('/frame/not-a-camera', {}, first)).headers['X-CCTV-Source'],
|
||||
(await app.call('/frame/not-a-camera', {}, 'GET', first)).headers[
|
||||
'X-CCTV-Source'
|
||||
],
|
||||
'synthetic',
|
||||
);
|
||||
assert.equal(
|
||||
@@ -598,6 +517,7 @@ test('the Street View fallback spends a per-IP Google budget, and only with a ke
|
||||
await app.call(
|
||||
`/frame/${STILL.id}`,
|
||||
{ 'x-forwarded-for': '203.0.113.9' },
|
||||
'GET',
|
||||
first,
|
||||
)
|
||||
).headers['X-CCTV-Source'],
|
||||
@@ -614,14 +534,11 @@ test('the Street View fallback spends a per-IP Google budget, and only with a ke
|
||||
assert.equal(streetViewCalls(), 2, 'no Google call over the budget');
|
||||
|
||||
// Another address has a budget of its own.
|
||||
assert.equal(
|
||||
await frameSource({ remoteAddress: '203.0.113.8' }),
|
||||
'streetview',
|
||||
);
|
||||
assert.equal(await frameSource('203.0.113.8'), 'streetview');
|
||||
assert.equal(streetViewCalls(), 3);
|
||||
|
||||
// Addresses within one IPv6 /64 share a budget.
|
||||
const v6 = (remoteAddress) => frameSource({ remoteAddress });
|
||||
const v6 = frameSource;
|
||||
assert.deepEqual(
|
||||
[await v6('2001:db8::1'), await v6('2001:db8::2'), await v6('2001:db8::3')],
|
||||
['streetview', 'streetview', 'synthetic'],
|
||||
|
||||
@@ -9,7 +9,7 @@ import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import { Readable, Writable } from 'node:stream';
|
||||
import { cctvProxy } from '../../server/providers/cctv.js';
|
||||
import { mountCctvProvider } from '../testSupport/cctvProviderHarness.mjs';
|
||||
import { proxyMediaResponse } from '../../server/providers/cctv/media.js';
|
||||
import { sanitizeCctvRangeHeader } from '../../server/providers/cctv/range.js';
|
||||
import { CCTV_MEDIA_MAX_BODY_BYTES as CAP } from '../../server/providers/cctv/constants.js';
|
||||
@@ -131,99 +131,21 @@ function upstreamResponse({ status = 206, headers = {}, body = 'payload' }) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Collects what a handler wrote, the way a Node ServerResponse would. */
|
||||
function recordingResponse() {
|
||||
const chunks = [];
|
||||
let finished;
|
||||
const done = new Promise((resolve) => {
|
||||
finished = resolve;
|
||||
});
|
||||
const res = {
|
||||
statusCode: 0,
|
||||
headers: {},
|
||||
writableEnded: false,
|
||||
body: '',
|
||||
writeHead(status, headers) {
|
||||
res.statusCode = status;
|
||||
res.headers = headers || {};
|
||||
},
|
||||
write(chunk) {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
return true;
|
||||
},
|
||||
end(chunk) {
|
||||
if (chunk) chunks.push(Buffer.from(chunk));
|
||||
res.writableEnded = true;
|
||||
res.body = Buffer.concat(chunks).toString('utf8');
|
||||
finished();
|
||||
},
|
||||
on() {},
|
||||
once() {},
|
||||
emit() {},
|
||||
destroy() {},
|
||||
};
|
||||
return { res, done };
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount the real provider, serve one camera, and answer its upstream from the
|
||||
* supplied function.
|
||||
*/
|
||||
/** Mount the real provider over the fixture cameras, recording upstream requests. */
|
||||
function mount(t, respond) {
|
||||
const before = {
|
||||
json: process.env.CCTV_SOURCES_JSON,
|
||||
file: process.env.CCTV_SOURCES_FILE,
|
||||
austin: process.env.CCTV_FORCE_AUSTIN,
|
||||
};
|
||||
process.env.CCTV_SOURCES_JSON = JSON.stringify([CAMERA]);
|
||||
process.env.CCTV_SOURCES_FILE = 'absent-source-file.json';
|
||||
process.env.CCTV_FORCE_AUSTIN = '0';
|
||||
const nativeFetch = globalThis.fetch;
|
||||
const requests = [];
|
||||
globalThis.fetch = async (url, init = {}) => {
|
||||
requests.push({
|
||||
url: String(url),
|
||||
headers: init.headers || {},
|
||||
signal: init.signal || null,
|
||||
});
|
||||
return respond({ url: String(url), init });
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.fetch = nativeFetch;
|
||||
for (const [name, value] of [
|
||||
['CCTV_SOURCES_JSON', before.json],
|
||||
['CCTV_SOURCES_FILE', before.file],
|
||||
['CCTV_FORCE_AUSTIN', before.austin],
|
||||
]) {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
});
|
||||
|
||||
let handler = null;
|
||||
const plugin = cctvProxy();
|
||||
plugin.configureServer({
|
||||
middlewares: {
|
||||
use: (_route, fn) => {
|
||||
handler = fn;
|
||||
},
|
||||
const app = mountCctvProvider(t, {
|
||||
cameras: [CAMERA],
|
||||
fetch: async (url, init = {}) => {
|
||||
requests.push({
|
||||
url: String(url),
|
||||
headers: init.headers || {},
|
||||
signal: init.signal || null,
|
||||
});
|
||||
return respond({ url: String(url), init });
|
||||
},
|
||||
});
|
||||
assert.ok(handler, 'the CCTV provider must mount a middleware');
|
||||
|
||||
/** Drive one request through the mounted handler. */
|
||||
const call = async (path, headers = {}) => {
|
||||
const { res, done } = recordingResponse();
|
||||
await handler({ url: path, headers, method: 'GET', on() {} }, res);
|
||||
await done;
|
||||
return res;
|
||||
};
|
||||
/** Read the camera's current health entry. */
|
||||
const health = async () => {
|
||||
const res = await call('/health');
|
||||
return JSON.parse(res.body).cameras.find(({ id }) => id === CAMERA.id);
|
||||
};
|
||||
return { call, health, requests, handler: (req, res) => handler(req, res) };
|
||||
return { ...app, requests, health: () => app.health(CAMERA.id) };
|
||||
}
|
||||
|
||||
test('a canonical range reaches the upstream and its 206 is passed through', async (t) => {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// Reproduction: a viewer refused for HLS capacity is shown its fallback frame
|
||||
// under a badge that still reads the shared live health ("LIVE · OK").
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { HLS_LIMITS } from '../../server/providers/cctv/stream.js';
|
||||
import { mountCctvProvider } from '../testSupport/cctvProviderHarness.mjs';
|
||||
import { presentCctvSourceBadge } from '../ui/cctvFrames.js';
|
||||
import { presentCctvPanel } from '../ui/cctvPresentation.js';
|
||||
|
||||
const SAME_ORIGIN = { host: 'localhost:4173', 'sec-fetch-site': 'same-origin' };
|
||||
const PLAYLIST =
|
||||
'#EXTM3U\n#EXT-X-TARGETDURATION:2\n#EXT-X-MEDIA-SEQUENCE:12\n#EXTINF:2,\na.ts\n#EXTINF:2,\nb.ts\n#EXTINF:2,\nc.ts\n';
|
||||
const lease = (index) =>
|
||||
`00000000-0000-4000-8000-${String(index).padStart(12, '0')}`;
|
||||
const camera = (id) => ({
|
||||
id,
|
||||
name: id,
|
||||
lat: 30.27,
|
||||
lon: -97.74,
|
||||
feedType: 'hls',
|
||||
url: `https://cams.upstream.invalid/${id}/list.m3u8`,
|
||||
});
|
||||
|
||||
test('a capacity-refused viewer is not shown its fallback frame as live and ok', async (t) => {
|
||||
assert.equal(HLS_LIMITS.sessions, 2);
|
||||
const { call, health } = mountCctvProvider(t, {
|
||||
cameras: ['cam-a', 'cam-b', 'cam-c'].map(camera),
|
||||
fetch: async (url) =>
|
||||
new Response(String(url).endsWith('.m3u8') ? PLAYLIST : 'abc'),
|
||||
});
|
||||
const open = (id, index) =>
|
||||
call(`/media/${id}?lease=${lease(index)}`, SAME_ORIGIN);
|
||||
// cam-c played earlier and was released: its row is live/ok.
|
||||
assert.equal((await open('cam-c', 0)).statusCode, 200);
|
||||
assert.equal(
|
||||
(await call(`/media/cam-c?lease=${lease(0)}`, SAME_ORIGIN, 'DELETE'))
|
||||
.statusCode,
|
||||
204,
|
||||
);
|
||||
// Two other viewers now hold both camera sessions.
|
||||
assert.equal((await open('cam-a', 1)).statusCode, 200);
|
||||
assert.equal((await open('cam-b', 2)).statusCode, 200);
|
||||
// The cam-c viewer is refused and falls back to the frame.
|
||||
const refused = await open('cam-c', 3);
|
||||
assert.equal(refused.statusCode, 503);
|
||||
const frame = await call('/frame/cam-c', SAME_ORIGIN);
|
||||
assert.equal(frame.statusCode, 200);
|
||||
assert.equal(frame.headers['X-CCTV-Source'], 'synthetic');
|
||||
assert.match(frame.body, /UPSTREAM UNAVAILABLE/);
|
||||
const row = await health('cam-c');
|
||||
// The badge the panel derives for this viewer, in image (fallback) mode.
|
||||
const shown = {
|
||||
feedType: 'hls',
|
||||
isVideo: false,
|
||||
sourceKind: row?.sourceKind || 'configured',
|
||||
sourceStatus: row?.status || 'unknown',
|
||||
sourceMessage: row?.message || '',
|
||||
};
|
||||
const badge = presentCctvSourceBadge(shown, true, {
|
||||
loading: false,
|
||||
error: false,
|
||||
hasFrame: true,
|
||||
});
|
||||
assert.notEqual(
|
||||
badge.label,
|
||||
'LIVE · OK',
|
||||
`fallback frame (${frame.headers['X-CCTV-Source']}) labelled ${badge.label}; health message "${row?.message}"`,
|
||||
);
|
||||
const { meta } = presentCctvPanel(
|
||||
{
|
||||
enabled: true,
|
||||
activeCameraId: 'cam-c',
|
||||
activeCamera: {
|
||||
...shown,
|
||||
id: 'cam-c',
|
||||
city: 'Austin',
|
||||
headingDeg: 0,
|
||||
fovDeg: 60,
|
||||
rangeM: 100,
|
||||
},
|
||||
},
|
||||
true,
|
||||
);
|
||||
assert.doesNotMatch(meta, /Live HLS connected/);
|
||||
});
|
||||
@@ -74,7 +74,12 @@ function collections(adv = '10') {
|
||||
}
|
||||
function install(options = {}, preview = false) {
|
||||
let handler;
|
||||
const plugin = cycloneProxy({ now: () => NOW, ...options });
|
||||
// JTWC has its own tests below; these cover NHC alone.
|
||||
const plugin = cycloneProxy({
|
||||
now: () => NOW,
|
||||
readJtwc: async () => [],
|
||||
...options,
|
||||
});
|
||||
plugin[preview ? 'configurePreviewServer' : 'configureServer']({
|
||||
middlewares: {
|
||||
use(path, callback) {
|
||||
@@ -297,7 +302,7 @@ test('dev and preview serve only fixed bounded NOAA queries, caching a complete
|
||||
const snapshot = body(await request());
|
||||
assert.equal(snapshot.unavailable, false);
|
||||
assert.equal(snapshot.stale, false);
|
||||
assert.match(snapshot.coverage, /not worldwide/);
|
||||
assert.match(snapshot.coverage, /JTWC: western North Pacific/);
|
||||
assert.equal(snapshot.storms[0].geometryStatus, 'current');
|
||||
assert.equal(snapshot.fetchedAt, NOW);
|
||||
assert.equal(calls.length, 4);
|
||||
@@ -491,3 +496,157 @@ test('shared refresh caps waiting consumers and rejects redirects without exposi
|
||||
});
|
||||
assert.equal(body(await redirected.request()).unavailable, true);
|
||||
});
|
||||
|
||||
function jtwcStorm(overrides = {}) {
|
||||
return {
|
||||
id: 'sh042027',
|
||||
agency: 'jtwc',
|
||||
name: 'Xavier',
|
||||
classification: 'TC',
|
||||
basin: 'SH',
|
||||
position: { longitude: -164.5, latitude: -11.6 },
|
||||
positionAt: TIME,
|
||||
advisoryNumber: '15',
|
||||
issuedAt: TIME,
|
||||
windKt: 45,
|
||||
pressureHpa: 995,
|
||||
movement: { directionDegrees: 245, speedKt: 4 },
|
||||
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
|
||||
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
|
||||
geometryStatus: 'pending',
|
||||
geometryAdvisoryNumber: null,
|
||||
forecastPoints: [],
|
||||
track: null,
|
||||
cone: null,
|
||||
dangerArea: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test('JTWC storms join NHC’s, and NHC’s advisory wins for a storm both list', async () => {
|
||||
const crossing = jtwcStorm({
|
||||
id: 'ep152026',
|
||||
basin: 'EP',
|
||||
name: 'JTWC copy',
|
||||
});
|
||||
const { request } = install({
|
||||
fetchImpl: fetcher(),
|
||||
readJtwc: async () => [jtwcStorm(), crossing],
|
||||
});
|
||||
const snapshot = body(await request());
|
||||
assert.deepEqual(
|
||||
snapshot.storms.map((storm) => [storm.id, storm.agency, storm.name]),
|
||||
[
|
||||
['ep152026', 'nhc', 'Fifteen-E'],
|
||||
['sh042027', 'jtwc', 'Xavier'],
|
||||
],
|
||||
);
|
||||
assert.equal(snapshot.stale, false);
|
||||
assert.match(snapshot.source, /JTWC/);
|
||||
assert.match(snapshot.attribution, /Joint Typhoon Warning Center/);
|
||||
});
|
||||
|
||||
test('JTWC reads go through the bounded fetch with no redirects', async () => {
|
||||
const calls = [];
|
||||
const { request } = install({
|
||||
fetchImpl: async (url, options) => {
|
||||
calls.push({ url, options });
|
||||
if (url.includes('jtwc.rss'))
|
||||
return new Response(
|
||||
'<rss><item><guid>NWPAC-NIO-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>EPAC-CPAC-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>SH-WARNINGS</guid>No Current Tropical Cyclone Warnings</item></rss>',
|
||||
);
|
||||
return fetcher()(url, options);
|
||||
},
|
||||
readJtwc: undefined,
|
||||
});
|
||||
const snapshot = body(await request());
|
||||
assert.equal(snapshot.stale, false);
|
||||
const jtwc = calls.filter(({ url }) => url.includes('metoc.navy.mil'));
|
||||
assert.deepEqual(
|
||||
jtwc.map(({ url }) => url),
|
||||
['https://www.metoc.navy.mil/jtwc/rss/jtwc.rss'],
|
||||
);
|
||||
assert.equal(jtwc[0].options.redirect, 'error');
|
||||
});
|
||||
|
||||
test('a failed JTWC read keeps its last storms and leaves NHC’s answer fresh', async () => {
|
||||
let fail = false;
|
||||
let clock = NOW;
|
||||
const { request } = install({
|
||||
fetchImpl: fetcher(),
|
||||
now: () => clock,
|
||||
readJtwc: async () => {
|
||||
if (fail) throw new Error('jtwc down');
|
||||
return [jtwcStorm()];
|
||||
},
|
||||
});
|
||||
assert.equal(body(await request()).storms.length, 2);
|
||||
fail = true;
|
||||
clock += 6 * 60_000;
|
||||
const kept = body(await request());
|
||||
assert.equal(kept.stale, false);
|
||||
assert.equal(kept.reason, null);
|
||||
assert.deepEqual(
|
||||
kept.storms.map((storm) => storm.id),
|
||||
['ep152026', 'sh042027'],
|
||||
);
|
||||
// Past their use, both advisories leave the cached answer.
|
||||
clock = Date.parse(TIME) + 13 * 3600_000 + 60_000;
|
||||
const later = body(await request());
|
||||
assert.deepEqual(
|
||||
later.storms.map((storm) => storm.id),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('a cached answer drops each storm whose own advisory is past use, not all of them', async () => {
|
||||
let up = true;
|
||||
let clock = NOW;
|
||||
const { request } = install({
|
||||
fetchImpl: async (url, options) => {
|
||||
if (!up) throw new Error('down');
|
||||
return fetcher()(url, options);
|
||||
},
|
||||
now: () => clock,
|
||||
readJtwc: async () => [
|
||||
jtwcStorm({ issuedAt: new Date(NOW - 30 * 60_000).toISOString() }),
|
||||
],
|
||||
});
|
||||
assert.equal(body(await request()).storms.length, 2);
|
||||
up = false;
|
||||
// 12 h 10 min after the NHC advisory: NHC's is past use, JTWC's is not.
|
||||
clock = Date.parse(TIME) + 12 * 3600_000 + 10 * 60_000;
|
||||
const cached = body(await request());
|
||||
assert.equal(cached.stale, true);
|
||||
assert.deepEqual(
|
||||
cached.storms.map((storm) => storm.id),
|
||||
['sh042027'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a JTWC that hangs or answers 500 leaves NHC’s answer unchanged', async (t) => {
|
||||
const nhcOnly = body(await install({ fetchImpl: fetcher() }).request());
|
||||
assert.equal(nhcOnly.stale, false);
|
||||
const jtwcCalls = [];
|
||||
for (const mode of ['500', 'hang']) {
|
||||
const { request } = install({
|
||||
readJtwc: undefined,
|
||||
jtwcTimeoutMs: 20,
|
||||
fetchImpl: async (url, options) => {
|
||||
if (!String(url).includes('metoc.navy.mil'))
|
||||
return fetcher()(url, options);
|
||||
jtwcCalls.push(mode);
|
||||
if (mode === '500') return new Response('down', { status: 500 });
|
||||
// Hangs until its own deadline aborts it.
|
||||
return new Promise((_, reject) =>
|
||||
options.signal.addEventListener('abort', () =>
|
||||
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
const answer = body(await request());
|
||||
assert.deepEqual(answer, nhcOnly, `JTWC ${mode}`);
|
||||
}
|
||||
assert.deepEqual(jtwcCalls, ['500', 'hang']);
|
||||
});
|
||||
@@ -563,7 +563,7 @@ export const DATA_CREDITS = [
|
||||
},
|
||||
{
|
||||
key: 'weather-cyclones',
|
||||
html: 'Cyclone advisories: <a href="https://www.nhc.noaa.gov/" target="_blank" rel="noopener">NOAA/NWS NHC / CPHC</a> · Atlantic and eastern/central North Pacific. Forecast center uncertainty, not storm size.',
|
||||
html: 'Cyclone advisories: <a href="https://www.nhc.noaa.gov/" target="_blank" rel="noopener">NOAA/NWS NHC / CPHC</a> · Atlantic and eastern/central North Pacific; <a href="https://www.metoc.navy.mil/jtwc/jtwc.html" target="_blank" rel="noopener">Joint Typhoon Warning Center</a> · western North Pacific, North Indian Ocean, Southern Hemisphere. The NHC cone is forecast center uncertainty, not storm size.',
|
||||
},
|
||||
{
|
||||
key: 'weather-lightning',
|
||||
|
||||
@@ -14,6 +14,35 @@ export const AWARENESS_RELATIONSHIP = Object.freeze({
|
||||
UNKNOWN: 'UNKNOWN',
|
||||
});
|
||||
|
||||
/**
|
||||
* Whether an aircraft matches a spoken class filter ("helicopter", "tanker"),
|
||||
* on its class or type fields. No filter matches everything; an aircraft
|
||||
* with no class or type matches no filter.
|
||||
* @param {object} item Aircraft summary (`getNearby` row or cohort item).
|
||||
* @param {string|null} aircraftClass Requested class.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function aircraftClassMatches(item, aircraftClass) {
|
||||
const normalize = (value) =>
|
||||
String(value || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const requested = normalize(aircraftClass);
|
||||
if (!requested) return true;
|
||||
return [
|
||||
item?.aircraftClass,
|
||||
item?.klass,
|
||||
item?.type,
|
||||
item?.typeCode,
|
||||
item?.typeName,
|
||||
]
|
||||
.map(normalize)
|
||||
.filter(Boolean)
|
||||
.some(
|
||||
(candidate) => candidate === requested || candidate.includes(requested),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search an expanding area synchronously, doubling the radius after each miss.
|
||||
* The maximum covers the farthest possible Earth-surface chord while keeping
|
||||
|
||||
@@ -47,6 +47,26 @@ export function frustumPlanes(pose) {
|
||||
return [left, rightPlane, bottom, top, nearPlane, farPlane];
|
||||
}
|
||||
|
||||
/**
|
||||
* `frustumPlanes(pose)`, or null when the pose does not describe a
|
||||
* perspective frustum: no position, direction or up, or no finite `fovy`,
|
||||
* `aspectRatio` or `near` (an orthographic camera, no camera).
|
||||
* @param {object|null|undefined} pose
|
||||
* @returns {ReturnType<typeof frustumPlanes>|null}
|
||||
*/
|
||||
export function viewPlanes(pose) {
|
||||
if (
|
||||
!pose?.position ||
|
||||
!pose.direction ||
|
||||
!pose.up ||
|
||||
!Number.isFinite(pose.fovy) ||
|
||||
!Number.isFinite(pose.aspectRatio) ||
|
||||
!Number.isFinite(pose.near)
|
||||
)
|
||||
return null;
|
||||
return frustumPlanes(pose);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a sphere is wholly outside `planes` (from `frustumPlanes`), as
|
||||
* the default renderer's `CullingVolume.computeVisibility` reports
|
||||
|
||||
@@ -1521,7 +1521,6 @@
|
||||
"FOV {value}° (DATASHEET)": "FOV {value}° (ورقة البيانات)",
|
||||
"SPEC FOV {span}° (CAPABILITY)": "FOV حسب المواصفات {span}° (القدرة)",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · المواصفات: CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "الأطلسي وشرق/وسط شمال المحيط الهادئ؛ ليست تغطية عالمية للأعاصير.",
|
||||
"Cyclone advisories unavailable": "نشرات الأعاصير غير متاحة",
|
||||
"Cyclone data unavailable": "بيانات الأعاصير غير متاحة",
|
||||
"Potential tropical cyclone": "إعصار مداري محتمل",
|
||||
@@ -1549,17 +1548,12 @@
|
||||
"Maximum sustained wind: {wind}": "أقصى سرعة للرياح المستمرة: {wind}",
|
||||
"Pressure: {pressure}": "الضغط: {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · النشرة رقم {number} · صدرت {time}",
|
||||
"No active NHC/CPHC systems": "لا توجد أنظمة مدارية نشطة لدى NHC/CPHC",
|
||||
"Advisories unavailable": "النشرات غير متاحة",
|
||||
"Cyclones · NHC / CPHC": "الأعاصير · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "الأطلسي · شرق/وسط الهادئ",
|
||||
"{storms} · {name} selected": "{storms} · المحدد: {name}",
|
||||
"Official advisory ↗": "النشرة الرسمية ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "نشرات الأعاصير النشطة من NHC وCPHC",
|
||||
"Wind unavailable": "الرياح غير متاحة",
|
||||
"Advisory center / forecast track": "المركز حسب النشرة / المسار المتوقع",
|
||||
"Center-track uncertainty cone": "مخروط عدم اليقين لمسار المركز",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "حدّد عاصفة على الخريطة، أو اخترها من القائمة لتحديدها وتحريك الكاميرا إليها. انقر على مساحة فارغة من الخريطة لإلغاء التحديد. سياق نشرات NOAA NHC/CPHC. يصف المخروط عدم اليقين في المسار المتوقع للمركز، لا حجم العاصفة ولا كامل منطقة الخطر. تشير تسميات نقاط التوقع إلى مدة التوقع بالساعات كما يوردها المصدر، لا إلى أوقات محسوبة من وقت صدور النشرة. تتبع الأشكال الهندسية السطح؛ والارتفاع لا يمثل ارتفاع الظواهر الجوية. راجع النشرة الرسمية.",
|
||||
"DRIVE": "قيادة",
|
||||
"Drive": "بالسيارة",
|
||||
"WALK": "مشي",
|
||||
@@ -4849,5 +4843,18 @@
|
||||
"Telemetry reads while the model is on screen": "تُقرأ القياسات أثناء ظهور النموذج على الشاشة",
|
||||
"Connecting to telemetry…": "جارٍ الاتصال بالقياسات…",
|
||||
"{seconds} s": "{seconds} ث",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: المحيط الأطلسي وشرق ووسط شمال المحيط الهادئ. JTWC: غرب شمال المحيط الهادئ وشمال المحيط الهندي ونصف الكرة الجنوبي.",
|
||||
"34-knot wind danger area": "منطقة خطر رياح 34 عقدة",
|
||||
"Track and 34-knot wind danger area match this warning": "المسار ومنطقة خطر رياح 34 عقدة مطابقان لهذا التحذير",
|
||||
"Track/danger area awaiting warning {number}": "المسار/منطقة الخطر بانتظار التحذير رقم {number}",
|
||||
"Track/danger area unavailable": "المسار/منطقة الخطر غير متاحين",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "تحذير JTWC: التحذير الرسمي هو تحذير المركز الإقليمي. رياح JTWC متوسطات دقيقة واحدة.",
|
||||
"No active tropical cyclone warnings": "لا توجد تحذيرات نشطة من الأعاصير المدارية",
|
||||
"Cyclones · NHC / CPHC · JTWC": "الأعاصير · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "كل الأحواض المدارية",
|
||||
"JTWC warning ↗": "تحذير JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "نشرات وتحذيرات الأعاصير النشطة",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "اختر عاصفة على الخريطة، أو اختر عاصفة من القائمة لتحديدها وتحريك الكاميرا إليها. انقر على مكان فارغ من الخريطة لإلغاء التحديد. نشرات NOAA NHC/CPHC وتحذيرات JTWC. يصف مخروط NHC عدم اليقين في المسار المتوقع للمركز، لا حجم العاصفة ولا منطقة الخطر كاملة. منطقة خطر رياح 34 عقدة لدى JTWC هي حيث قد تصل رياح بسرعة 34 عقدة، موسّعةً بخطأ توقع المسار؛ وهي ليست مخروطًا. تسميات نقاط التوقع هي ساعات المهلة لدى المصدر، لا أوقات محسوبة من وقت الإصدار. تتبع الأشكال سطح الأرض؛ والارتفاع ليس ارتفاعًا جويًا. ارجع إلى النشرة الرسمية أو إلى مركز الإنذار الإقليمي.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · التحذير {number} · صدر {time}"
|
||||
}
|
||||
@@ -1436,7 +1436,6 @@
|
||||
"FOV {value}° (DATASHEET)": "FOV {value}° (DATENBLATT)",
|
||||
"SPEC FOV {span}° (CAPABILITY)": "SPEZ. FOV {span}° (BEREICH)",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · SPEZ.: CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlantik und östlicher/zentraler Nordpazifik; keine weltweite Abdeckung von Wirbelstürmen.",
|
||||
"Cyclone advisories unavailable": "Wirbelsturm-Lageberichte nicht verfügbar",
|
||||
"Cyclone data unavailable": "Wirbelsturmdaten nicht verfügbar",
|
||||
"Potential tropical cyclone": "Potenzieller tropischer Wirbelsturm",
|
||||
@@ -1460,17 +1459,12 @@
|
||||
"Maximum sustained wind: {wind}": "Maximaler Dauerwind: {wind}",
|
||||
"Pressure: {pressure}": "Luftdruck: {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Lagebericht {number} · ausgegeben {time}",
|
||||
"No active NHC/CPHC systems": "Keine aktiven NHC/CPHC-Systeme",
|
||||
"Advisories unavailable": "Lageberichte nicht verfügbar",
|
||||
"Cyclones · NHC / CPHC": "Wirbelstürme · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "Atlantik · östl./zentr. Pazifik",
|
||||
"{storms} · {name} selected": "{storms} · {name} ausgewählt",
|
||||
"Official advisory ↗": "Offizieller Lagebericht ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "Aktive Wirbelsturm-Lageberichte von NHC und CPHC",
|
||||
"Wind unavailable": "Wind nicht verfügbar",
|
||||
"Advisory center / forecast track": "Zentrum laut Lagebericht / Vorhersagebahn",
|
||||
"Center-track uncertainty cone": "Unsicherheitskegel der Zentrumsbahn",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Einen Sturm auf der Karte auswählen oder in der Liste wählen, um ihn auszuwählen und die Kamera dorthin zu bewegen. Auf eine leere Kartenstelle klicken, um die Auswahl aufzuheben. Kontext aus Lageberichten von NOAA NHC/CPHC. Der Kegel beschreibt die Unsicherheit der vorhergesagten Zentrumsbahn, nicht die Sturmgröße oder das gesamte Gefahrengebiet. Die Beschriftungen der Vorhersagepunkte sind Vorlaufstunden der Quelle, keine aus dem Ausgabezeitpunkt berechneten Zeiten. Die Geometrie folgt der Oberfläche; die Darstellungshöhe hat keine meteorologische Bedeutung. Den offiziellen Lagebericht beachten.",
|
||||
"DRIVE": "AUTO",
|
||||
"Drive": "Auto",
|
||||
"WALK": "ZU FUSS",
|
||||
@@ -4425,5 +4419,18 @@
|
||||
"Telemetry reads while the model is on screen": "Telemetrie wird gelesen, solange das Modell zu sehen ist",
|
||||
"Connecting to telemetry…": "Verbindung zur Telemetrie…",
|
||||
"{seconds} s": "{seconds} s",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Solarflügel, Radiatoren und eine Antenne folgen der Live-Telemetrie der NASA. Die andere Antenne steht still und die Arme bewegen sich zur Veranschaulichung."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Solarflügel, Radiatoren und eine Antenne folgen der Live-Telemetrie der NASA. Die andere Antenne steht still und die Arme bewegen sich zur Veranschaulichung.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlantik und östlicher/zentraler Nordpazifik. JTWC: westlicher Nordpazifik, nördlicher Indischer Ozean und Südhalbkugel.",
|
||||
"34-knot wind danger area": "Gefahrenbereich für 34-Knoten-Wind",
|
||||
"Track and 34-knot wind danger area match this warning": "Zugbahn und 34-Knoten-Gefahrenbereich passen zu dieser Warnung",
|
||||
"Track/danger area awaiting warning {number}": "Zugbahn/Gefahrenbereich warten auf Warnung {number}",
|
||||
"Track/danger area unavailable": "Zugbahn/Gefahrenbereich nicht verfügbar",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC-Warnung: Maßgeblich ist die Warnung des regionalen Zentrums. JTWC-Winde sind 1-Minuten-Mittel.",
|
||||
"No active tropical cyclone warnings": "Keine aktiven Warnungen vor tropischen Wirbelstürmen",
|
||||
"Cyclones · NHC / CPHC · JTWC": "Wirbelstürme · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "Alle tropischen Becken",
|
||||
"JTWC warning ↗": "JTWC-Warnung ↗",
|
||||
"Active cyclone advisories and warnings": "Aktive Wirbelsturm-Lageberichte und -Warnungen",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Wähle einen Sturm auf der Karte oder in der Liste, um ihn auszuwählen und die Kamera hinzubewegen. Ein Klick auf eine leere Kartenstelle hebt die Auswahl auf. Lageberichte von NOAA NHC/CPHC und Warnungen des JTWC. Der NHC-Kegel beschreibt die Unsicherheit der vorhergesagten Zugbahn des Zentrums, nicht die Sturmgröße oder das gesamte Gefahrengebiet. Der 34-Knoten-Gefahrenbereich des JTWC ist das Gebiet, das Winde von 34 Knoten erreichen können, erweitert um den Fehler der Zugbahnvorhersage; er ist kein Kegel. Die Beschriftungen der Vorhersagepunkte sind die Vorlaufstunden der Quelle, keine aus der Ausgabe berechneten Zeiten. Die Geometrie folgt der Oberfläche; die Höhe ist keine Wetterhöhe. Maßgeblich sind der offizielle Lagebericht oder das regionale Warnzentrum.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Warnung {number} · ausgegeben {time}"
|
||||
}
|
||||
@@ -1342,7 +1342,6 @@
|
||||
"None on screen — nearby cameras are outside the view": "Ninguna en pantalla — las cámaras cercanas están fuera de la vista",
|
||||
"ALPR camera": "Cámara ALPR",
|
||||
"OpenStreetMap · community mapped": "OpenStreetMap · mapeado por la comunidad",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlántico y Pacífico Norte oriental/central; no es una cobertura mundial de ciclones.",
|
||||
"Potential tropical cyclone": "Posible ciclón tropical",
|
||||
"Post-tropical cyclone": "Ciclón postropical",
|
||||
"Hurricane": "Huracán",
|
||||
@@ -1365,17 +1364,12 @@
|
||||
"Maximum sustained wind: {wind}": "Viento máximo sostenido: {wind}",
|
||||
"Pressure: {pressure}": "Presión: {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}",
|
||||
"No active NHC/CPHC systems": "Sin sistemas activos del NHC/CPHC",
|
||||
"Advisories unavailable": "Avisos no disponibles",
|
||||
"Cyclones · NHC / CPHC": "Ciclones · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "Atlántico · Pacífico E/C",
|
||||
"{storms} · {name} selected": "{storms} · {name} seleccionado",
|
||||
"Official advisory ↗": "Aviso oficial ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "Avisos de ciclones activos del NHC y el CPHC",
|
||||
"Wind unavailable": "Viento no disponible",
|
||||
"Advisory center / forecast track": "Centro del ciclón según el aviso / trayectoria pronosticada",
|
||||
"Center-track uncertainty cone": "Cono de incertidumbre de la trayectoria del centro",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Selecciona un ciclón en el mapa, o elige uno en la lista para seleccionarlo y mover la cámara. Haz clic en un espacio vacío del mapa para borrar la selección. Contexto de avisos NOAA NHC/CPHC. El cono describe la incertidumbre de la trayectoria pronosticada del centro, no el tamaño del ciclón ni toda el área de peligro. Las etiquetas de los puntos de pronóstico son horas de anticipación de la fuente, no horas calculadas a partir de la emisión del aviso. La geometría sigue la superficie; la altura no es altitud meteorológica. Consulta el aviso oficial.",
|
||||
"Directions": "Indicaciones",
|
||||
"{mode} — reroute for {modeLower}": "{mode} — recalcular la ruta {modeLower}",
|
||||
"CLICK MAP": "CLIC EN EL MAPA",
|
||||
@@ -4531,5 +4525,18 @@
|
||||
"Telemetry reads while the model is on screen": "La telemetría se lee mientras el modelo está en pantalla",
|
||||
"Connecting to telemetry…": "Conectando con la telemetría…",
|
||||
"{seconds} s": "{seconds} s",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Los paneles, los radiadores y una antena siguen la telemetría en vivo de la NASA. La otra antena permanece quieta y los brazos se mueven a modo de ilustración."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Los paneles, los radiadores y una antena siguen la telemetría en vivo de la NASA. La otra antena permanece quieta y los brazos se mueven a modo de ilustración.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlántico y Pacífico Norte oriental/central. JTWC: Pacífico Norte occidental, océano Índico Norte y hemisferio sur.",
|
||||
"34-knot wind danger area": "Zona de peligro de vientos de 34 nudos",
|
||||
"Track and 34-knot wind danger area match this warning": "La trayectoria y la zona de peligro de 34 nudos coinciden con este aviso",
|
||||
"Track/danger area awaiting warning {number}": "Trayectoria/zona de peligro a la espera del aviso {number}",
|
||||
"Track/danger area unavailable": "Trayectoria/zona de peligro no disponibles",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Aviso del JTWC: el aviso oficial es el del centro regional. Los vientos del JTWC son promedios de 1 minuto.",
|
||||
"No active tropical cyclone warnings": "Sin avisos activos de ciclones tropicales",
|
||||
"Cyclones · NHC / CPHC · JTWC": "Ciclones · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "Todas las cuencas tropicales",
|
||||
"JTWC warning ↗": "Aviso del JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Avisos activos de ciclones",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Selecciona una tormenta en el mapa o elige una en la lista para seleccionarla y mover la cámara. Haz clic en una zona vacía del mapa para quitar la selección. Avisos de NOAA NHC/CPHC y del JTWC. El cono del NHC describe la incertidumbre de la trayectoria prevista del centro, no el tamaño de la tormenta ni toda la zona de peligro. La zona de peligro de 34 nudos del JTWC es donde pueden llegar vientos de 34 nudos, ampliada por el error de la trayectoria prevista; no es un cono. Las etiquetas de los puntos de pronóstico son horas de anticipación de la fuente, no horas calculadas desde la emisión. La geometría sigue la superficie; la altura no es altitud meteorológica. Consulta el aviso oficial o el centro de avisos regional.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
|
||||
}
|
||||
@@ -644,7 +644,6 @@
|
||||
"SRC {value}": "SRC {value}",
|
||||
"{value} CONTEXT": "CONTEXTE {value}",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · CARACT. : CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlantique et Pacifique Nord oriental/central ; pas une couverture mondiale des cyclones.",
|
||||
"Cyclone advisories unavailable": "Bulletins cycloniques indisponibles",
|
||||
"Cyclone data unavailable": "Données cycloniques indisponibles",
|
||||
"Potential tropical cyclone": "Cyclone tropical potentiel",
|
||||
@@ -669,17 +668,12 @@
|
||||
"Maximum sustained wind: {wind}": "Vent maximal soutenu : {wind}",
|
||||
"Pressure: {pressure}": "Pression : {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Bulletin {number} · émis le {time}",
|
||||
"No active NHC/CPHC systems": "Aucun système actif NHC/CPHC",
|
||||
"Advisories unavailable": "Bulletins indisponibles",
|
||||
"Cyclones · NHC / CPHC": "Cyclones · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "Atlantique · Pacifique E/C",
|
||||
"{storms} · {name} selected": "{storms} · {name} sélectionné",
|
||||
"Official advisory ↗": "Bulletin officiel ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "Bulletins cycloniques actifs du NHC et du CPHC",
|
||||
"Wind unavailable": "Vent indisponible",
|
||||
"Advisory center / forecast track": "Centre selon le bulletin / trajectoire prévue",
|
||||
"Center-track uncertainty cone": "Cône d'incertitude de la trajectoire du centre",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Sélectionnez un cyclone sur la carte, ou choisissez-en un dans la liste pour le sélectionner et déplacer la caméra. Cliquez sur une zone vide de la carte pour effacer la sélection. Contexte des bulletins NOAA NHC/CPHC. Le cône décrit l'incertitude de la trajectoire prévue du centre, pas la taille du cyclone ni toute la zone de danger. Les étiquettes des points de prévision sont les échéances de la source, pas des heures calculées depuis l'émission du bulletin. La géométrie suit la surface ; la hauteur n'est pas une altitude météorologique. Consultez le bulletin officiel.",
|
||||
"DRIVE": "VOITURE",
|
||||
"Drive": "En voiture",
|
||||
"WALK": "À PIED",
|
||||
@@ -4531,5 +4525,18 @@
|
||||
"Telemetry reads while the model is on screen": "La télémétrie est lue tant que le modèle est à l'écran",
|
||||
"Connecting to telemetry…": "Connexion à la télémétrie…",
|
||||
"{seconds} s": "{seconds} s",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Les panneaux, les radiateurs et une antenne suivent la télémétrie en direct de la NASA. L'autre antenne reste immobile et les bras bougent à titre d'illustration."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Les panneaux, les radiateurs et une antenne suivent la télémétrie en direct de la NASA. L'autre antenne reste immobile et les bras bougent à titre d'illustration.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC : Atlantique et Pacifique Nord oriental/central. JTWC : Pacifique Nord occidental, nord de l’océan Indien et hémisphère Sud.",
|
||||
"34-knot wind danger area": "Zone de danger des vents de 34 nœuds",
|
||||
"Track and 34-knot wind danger area match this warning": "La trajectoire et la zone de danger de 34 nœuds correspondent à cet avertissement",
|
||||
"Track/danger area awaiting warning {number}": "Trajectoire/zone de danger en attente de l’avertissement {number}",
|
||||
"Track/danger area unavailable": "Trajectoire/zone de danger indisponibles",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Avertissement du JTWC : l’avertissement officiel est celui du centre régional. Les vents du JTWC sont des moyennes sur 1 minute.",
|
||||
"No active tropical cyclone warnings": "Aucun avertissement de cyclone tropical en cours",
|
||||
"Cyclones · NHC / CPHC · JTWC": "Cyclones · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "Tous les bassins tropicaux",
|
||||
"JTWC warning ↗": "Avertissement du JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Bulletins et avertissements cycloniques en cours",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Sélectionnez une tempête sur la carte, ou choisissez-en une dans la liste pour la sélectionner et déplacer la caméra. Cliquez sur une zone vide de la carte pour effacer la sélection. Bulletins NOAA NHC/CPHC et avertissements du JTWC. Le cône du NHC décrit l’incertitude de la trajectoire prévue du centre, pas la taille de la tempête ni toute la zone de danger. La zone de danger de 34 nœuds du JTWC est l’endroit que peuvent atteindre des vents de 34 nœuds, élargi de l’erreur de prévision de trajectoire ; ce n’est pas un cône. Les étiquettes des points de prévision sont les échéances de la source, pas des heures calculées depuis l’émission. La géométrie suit la surface ; la hauteur n’est pas une altitude météorologique. Consultez le bulletin officiel ou le centre d’avertissement régional.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avertissement {number} · émis {time}"
|
||||
}
|
||||
@@ -532,7 +532,6 @@
|
||||
"SRC {value}": "SRC {value}",
|
||||
"{value} CONTEXT": "הקשר {value}",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · מפרט: CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "האטלנטי והפסיפיק הצפוני המזרחי/מרכזי; אין כיסוי ציקלונים עולמי.",
|
||||
"Cyclone advisories unavailable": "עדכוני ציקלונים אינם זמינים",
|
||||
"Cyclone data unavailable": "נתוני ציקלונים אינם זמינים",
|
||||
"Potential tropical cyclone": "ציקלון טרופי פוטנציאלי",
|
||||
@@ -557,17 +556,12 @@
|
||||
"Maximum sustained wind: {wind}": "רוח מתמשכת מרבית: {wind}",
|
||||
"Pressure: {pressure}": "לחץ: {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · עדכון {number} · פורסם {time}",
|
||||
"No active NHC/CPHC systems": "אין מערכות NHC/CPHC פעילות",
|
||||
"Advisories unavailable": "עדכונים אינם זמינים",
|
||||
"Cyclones · NHC / CPHC": "ציקלונים · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "האטלנטי · מזרח ומרכז הפסיפיק",
|
||||
"{storms} · {name} selected": "{storms} · {name} נבחר",
|
||||
"Official advisory ↗": "עדכון רשמי ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "עדכוני ציקלונים פעילים של NHC ו-CPHC",
|
||||
"Wind unavailable": "רוח אינה זמינה",
|
||||
"Advisory center / forecast track": "מרכז הסערה לפי העדכון / מסלול התחזית",
|
||||
"Center-track uncertainty cone": "חרוט אי-הוודאות של מסלול המרכז",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "בחר סערה במפה, או בחר סערה ברשימה כדי לבחור אותה ולהזיז את המצלמה. לחץ בשטח ריק במפה כדי לבטל את הבחירה. הקשר עדכונים של NOAA NHC/CPHC. החרוט מתאר אי-ודאות של מסלול המרכז בתחזית, לא את גודל הסערה ולא את מלוא אזור הסכנה. תוויות נקודות התחזית הן שעות חיזוי של המקור, לא זמנים שחושבו מפרסום העדכון. הגאומטריה נצמדת לפני הקרקע; הגובה אינו גובה מטאורולוגי. עיין בעדכון הרשמי.",
|
||||
"Malformed cyclone snapshot": "תמונת מצב של ציקלון פגומה",
|
||||
"Cyclone request timed out": "בקשת הציקלון חרגה מהזמן הקצוב",
|
||||
"DRIVE": "נסיעה",
|
||||
@@ -4531,5 +4525,18 @@
|
||||
"Telemetry reads while the model is on screen": "הטלמטריה נקראת כל עוד הדגם מוצג על המסך",
|
||||
"Connecting to telemetry…": "מתחבר לטלמטריה…",
|
||||
"{seconds} s": "{seconds} שנ׳",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: האוקיינוס האטלנטי ומזרח ומרכז צפון האוקיינוס השקט. JTWC: מערב צפון האוקיינוס השקט, צפון האוקיינוס ההודי וחצי הכדור הדרומי.",
|
||||
"34-knot wind danger area": "אזור סכנה של רוחות 34 קשר",
|
||||
"Track and 34-knot wind danger area match this warning": "המסלול ואזור הסכנה של 34 קשר תואמים לאזהרה הזו",
|
||||
"Track/danger area awaiting warning {number}": "מסלול/אזור סכנה ממתינים לאזהרה {number}",
|
||||
"Track/danger area unavailable": "מסלול/אזור סכנה אינם זמינים",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "אזהרת JTWC: האזהרה הרשמית היא של המרכז האזורי. רוחות JTWC הן ממוצעים של דקה אחת.",
|
||||
"No active tropical cyclone warnings": "אין אזהרות פעילות מפני ציקלונים טרופיים",
|
||||
"Cyclones · NHC / CPHC · JTWC": "ציקלונים · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "כל האגנים הטרופיים",
|
||||
"JTWC warning ↗": "אזהרת JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "עדכוני ציקלונים ואזהרות פעילים",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "בחרו סופה במפה, או בחרו סופה ברשימה כדי לסמן אותה ולהזיז אליה את המצלמה. לחיצה על מקום ריק במפה מבטלת את הבחירה. עדכוני NOAA NHC/CPHC ואזהרות JTWC. החרוט של NHC מתאר את אי-הוודאות במסלול החזוי של המרכז, לא את גודל הסופה ולא את כל אזור הסכנה. אזור הסכנה של 34 קשר של JTWC הוא המקום שאליו עשויות להגיע רוחות של 34 קשר, מורחב בשגיאת תחזית המסלול; הוא אינו חרוט. התוויות של נקודות התחזית הן שעות התחזית של המקור, לא זמנים שחושבו ממועד הפרסום. הצורות עוקבות אחר פני השטח; הגובה אינו גובה מטאורולוגי. עיינו בעדכון הרשמי או במרכז ההתרעות האזורי.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · אזהרה {number} · פורסמה {time}"
|
||||
}
|
||||
@@ -644,7 +644,6 @@
|
||||
"SRC {value}": "FONTE {value}",
|
||||
"{value} CONTEXT": "CONTESTO {value}",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · SPECIFICHE: CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlantico e Pacifico settentrionale orientale/centrale; non è una copertura mondiale dei cicloni.",
|
||||
"Cyclone advisories unavailable": "Bollettini sui cicloni non disponibili",
|
||||
"Cyclone data unavailable": "Dati sui cicloni non disponibili",
|
||||
"Potential tropical cyclone": "Potenziale ciclone tropicale",
|
||||
@@ -669,17 +668,12 @@
|
||||
"Maximum sustained wind: {wind}": "Vento massimo sostenuto: {wind}",
|
||||
"Pressure: {pressure}": "Pressione: {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Bollettino {number} · emesso {time}",
|
||||
"No active NHC/CPHC systems": "Nessun sistema NHC/CPHC attivo",
|
||||
"Advisories unavailable": "Bollettini non disponibili",
|
||||
"Cyclones · NHC / CPHC": "Cicloni · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "Atlantico · Pacifico E/C",
|
||||
"{storms} · {name} selected": "{storms} · selezione: {name}",
|
||||
"Official advisory ↗": "Bollettino ufficiale ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "Bollettini attivi sui cicloni di NHC e CPHC",
|
||||
"Wind unavailable": "Vento non disponibile",
|
||||
"Advisory center / forecast track": "Centro del ciclone da bollettino / traccia prevista",
|
||||
"Center-track uncertainty cone": "Cono di incertezza della traccia del centro",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Seleziona una tempesta sulla mappa, o scegline una nell'elenco per selezionarla e spostare la camera. Fai clic su un punto vuoto della mappa per annullare la selezione. Contesto dai bollettini NOAA NHC/CPHC. Il cono descrive l'incertezza sulla traccia prevista del centro, non le dimensioni della tempesta né l'intera area di pericolo. Le etichette dei punti di previsione indicano le scadenze di previsione in ore fornite dalla fonte, non orari calcolati dall'emissione del bollettino. La geometria segue la superficie; l'altezza non è la quota meteorologica. Consulta il bollettino ufficiale.",
|
||||
"DRIVE": "AUTO",
|
||||
"Drive": "In auto",
|
||||
"WALK": "A PIEDI",
|
||||
@@ -4531,5 +4525,18 @@
|
||||
"Telemetry reads while the model is on screen": "La telemetria viene letta finché il modello è sullo schermo",
|
||||
"Connecting to telemetry…": "Connessione alla telemetria…",
|
||||
"{seconds} s": "{seconds} s",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Pannelli, radiatori e un'antenna seguono la telemetria in diretta della NASA. L'altra antenna resta ferma e i bracci si muovono a scopo illustrativo."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Pannelli, radiatori e un'antenna seguono la telemetria in diretta della NASA. L'altra antenna resta ferma e i bracci si muovono a scopo illustrativo.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlantico e Pacifico settentrionale orientale/centrale. JTWC: Pacifico settentrionale occidentale, Oceano Indiano settentrionale ed emisfero australe.",
|
||||
"34-knot wind danger area": "Area di pericolo per venti a 34 nodi",
|
||||
"Track and 34-knot wind danger area match this warning": "Traccia e area di pericolo a 34 nodi corrispondono a questo avviso",
|
||||
"Track/danger area awaiting warning {number}": "Traccia/area di pericolo in attesa dell’avviso {number}",
|
||||
"Track/danger area unavailable": "Traccia/area di pericolo non disponibili",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Avviso JTWC: l’avviso ufficiale è quello del centro regionale. I venti JTWC sono medie su 1 minuto.",
|
||||
"No active tropical cyclone warnings": "Nessun avviso attivo di ciclone tropicale",
|
||||
"Cyclones · NHC / CPHC · JTWC": "Cicloni · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "Tutti i bacini tropicali",
|
||||
"JTWC warning ↗": "Avviso JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Bollettini e avvisi attivi sui cicloni",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Seleziona una tempesta sulla mappa o sceglila nell’elenco per selezionarla e spostare la telecamera. Fai clic su un punto vuoto della mappa per annullare la selezione. Bollettini NOAA NHC/CPHC e avvisi JTWC. Il cono NHC descrive l’incertezza della traccia prevista del centro, non le dimensioni della tempesta né l’intera area di pericolo. L’area di pericolo a 34 nodi del JTWC è dove possono arrivare venti a 34 nodi, ampliata dall’errore di previsione della traccia; non è un cono. Le etichette dei punti di previsione sono ore di anticipo della fonte, non orari calcolati dall’emissione. La geometria segue la superficie; l’altezza non è quota meteorologica. Consulta il bollettino ufficiale o il centro di allerta regionale.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avviso {number} · emesso {time}"
|
||||
}
|
||||
@@ -616,7 +616,6 @@
|
||||
"SRC {value}": "SRC {value}",
|
||||
"{value} CONTEXT": "{value}コンテキスト",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · 仕様:CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "大西洋と北太平洋東部・中部のみです。全世界のサイクロンを網羅するものではありません。",
|
||||
"Cyclone advisories unavailable": "サイクロン情報を取得できません",
|
||||
"Cyclone data unavailable": "サイクロンデータを取得できません",
|
||||
"Potential tropical cyclone": "サイクロン化のおそれがある擾乱",
|
||||
@@ -639,17 +638,12 @@
|
||||
"Maximum sustained wind: {wind}": "最大持続風速:{wind}",
|
||||
"Pressure: {pressure}": "気圧:{pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · 第{number}報 · {time}発表",
|
||||
"No active NHC/CPHC systems": "NHC/CPHCが監視中のサイクロンはありません",
|
||||
"Advisories unavailable": "サイクロン情報を取得できません",
|
||||
"Cyclones · NHC / CPHC": "サイクロン · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "大西洋 · 東部/中部太平洋",
|
||||
"{storms} · {name} selected": "{storms} · {name}を選択中",
|
||||
"Official advisory ↗": "公式情報 ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "発生中のNHCおよびCPHCサイクロン情報",
|
||||
"Wind unavailable": "風のデータを取得できません",
|
||||
"Advisory center / forecast track": "発表時の中心 / 予報進路",
|
||||
"Center-track uncertainty cone": "中心進路の予報円",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "地図上でサイクロンを選択するか、リストから選ぶと、そのサイクロンが選択されてカメラが移動します。地図の何もない場所をクリックすると選択を解除します。NOAA NHC/CPHCの情報に基づく表示です。予報円は予報される中心進路の不確かさを示すもので、サイクロンの大きさや危険範囲全体ではありません。予報点のラベルはソースの予報時間で、発表時刻から計算した時刻ではありません。図形は地表に沿って表示され、高さは気象上の高度ではありません。公式情報を確認してください。",
|
||||
"DRIVE": "車",
|
||||
"Drive": "車",
|
||||
"WALK": "徒歩",
|
||||
@@ -4319,5 +4313,18 @@
|
||||
"Telemetry reads while the model is on screen": "テレメトリはモデルが画面にある間に読み取られます",
|
||||
"Connecting to telemetry…": "テレメトリに接続中…",
|
||||
"{seconds} s": "{seconds} 秒",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。"
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC:大西洋、北太平洋東部・中部。JTWC:北西太平洋、北インド洋、南半球。",
|
||||
"34-knot wind danger area": "34ノット風の危険域",
|
||||
"Track and 34-knot wind danger area match this warning": "進路と34ノット風の危険域はこの警報と一致しています",
|
||||
"Track/danger area awaiting warning {number}": "進路/危険域は第{number}号警報待ち",
|
||||
"Track/danger area unavailable": "進路/危険域は利用できません",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC警報:公式の警報は地域センターの警報です。JTWCの風速は1分間平均です。",
|
||||
"No active tropical cyclone warnings": "発表中の熱帯低気圧警報はありません",
|
||||
"Cyclones · NHC / CPHC · JTWC": "サイクロン · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "すべての熱帯海域",
|
||||
"JTWC warning ↗": "JTWC警報 ↗",
|
||||
"Active cyclone advisories and warnings": "発表中のサイクロン情報と警報",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "地図上の嵐を選ぶか、リストから嵐を選ぶと選択され、カメラが移動します。地図の何もない場所をクリックすると選択を解除します。NOAA NHC/CPHCの情報とJTWCの警報です。NHCの予報円は中心の予報進路の不確かさを表すもので、嵐の大きさや危険域全体ではありません。JTWCの34ノット風の危険域は、34ノットの風が及ぶおそれのある範囲を進路予報の誤差分だけ広げたもので、予報円ではありません。予報点のラベルは情報源の予報時間で、発表時刻から計算した時刻ではありません。形状は地表に沿って描かれ、高さは気象上の高度ではありません。公式の情報または地域の警報センターを確認してください。",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第{number}号警報 · {time} 発表"
|
||||
}
|
||||
@@ -644,7 +644,6 @@
|
||||
"SRC {value}": "FONTE {value}",
|
||||
"{value} CONTEXT": "CONTEXTO {value}",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ESPECIFICAÇÕES: CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlântico e Pacífico Norte oriental/central; não é uma cobertura mundial de ciclones.",
|
||||
"Cyclone advisories unavailable": "Boletins de ciclones indisponíveis",
|
||||
"Cyclone data unavailable": "Dados de ciclones indisponíveis",
|
||||
"Potential tropical cyclone": "Potencial ciclone tropical",
|
||||
@@ -669,17 +668,12 @@
|
||||
"Maximum sustained wind: {wind}": "Vento máximo sustentado: {wind}",
|
||||
"Pressure: {pressure}": "Pressão: {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Boletim {number} · emitido em {time}",
|
||||
"No active NHC/CPHC systems": "Nenhum sistema ativo do NHC/CPHC",
|
||||
"Advisories unavailable": "Boletins indisponíveis",
|
||||
"Cyclones · NHC / CPHC": "Ciclones · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "Atlântico · Pacífico Leste/Central",
|
||||
"{storms} · {name} selected": "{storms} · {name} selecionado",
|
||||
"Official advisory ↗": "Boletim oficial ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "Boletins de ciclones ativos do NHC e do CPHC",
|
||||
"Wind unavailable": "Vento indisponível",
|
||||
"Advisory center / forecast track": "Centro do ciclone no boletim / trajetória prevista",
|
||||
"Center-track uncertainty cone": "Cone de incerteza da trajetória do centro",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Selecione um ciclone no mapa ou escolha um na lista para selecioná-lo e mover a câmera. Clique em um espaço vazio do mapa para limpar a seleção. Contexto dos boletins NOAA NHC/CPHC. O cone descreve a incerteza da trajetória prevista do centro, não o tamanho do ciclone nem toda a área de risco. Os rótulos dos pontos de previsão são horas de antecedência da fonte, não horários calculados a partir da emissão do boletim. A geometria acompanha a superfície; a altura não é altitude meteorológica. Consulte o boletim oficial.",
|
||||
"DRIVE": "CARRO",
|
||||
"Drive": "De carro",
|
||||
"WALK": "A PÉ",
|
||||
@@ -4531,5 +4525,18 @@
|
||||
"Telemetry reads while the model is on screen": "A telemetria é lida enquanto o modelo está no ecrã",
|
||||
"Connecting to telemetry…": "A ligar à telemetria…",
|
||||
"{seconds} s": "{seconds} s",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Painéis, radiadores e uma antena seguem a telemetria ao vivo da NASA. A outra antena fica parada e os braços se movem de forma ilustrativa."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Painéis, radiadores e uma antena seguem a telemetria ao vivo da NASA. A outra antena fica parada e os braços se movem de forma ilustrativa.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlântico e Pacífico Norte oriental/central. JTWC: Pacífico Norte ocidental, Oceano Índico Norte e Hemisfério Sul.",
|
||||
"34-knot wind danger area": "Área de perigo de ventos de 34 nós",
|
||||
"Track and 34-knot wind danger area match this warning": "A trajetória e a área de perigo de 34 nós correspondem a este aviso",
|
||||
"Track/danger area awaiting warning {number}": "Trajetória/área de perigo aguardando o aviso {number}",
|
||||
"Track/danger area unavailable": "Trajetória/área de perigo indisponíveis",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Aviso do JTWC: o aviso oficial é o do centro regional. Os ventos do JTWC são médias de 1 minuto.",
|
||||
"No active tropical cyclone warnings": "Nenhum aviso ativo de ciclone tropical",
|
||||
"Cyclones · NHC / CPHC · JTWC": "Ciclones · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "Todas as bacias tropicais",
|
||||
"JTWC warning ↗": "Aviso do JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Boletins e avisos de ciclones ativos",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Selecione uma tempestade no mapa ou escolha uma na lista para selecioná-la e mover a câmera. Clique em uma área vazia do mapa para limpar a seleção. Boletins da NOAA NHC/CPHC e avisos do JTWC. O cone do NHC descreve a incerteza da trajetória prevista do centro, não o tamanho da tempestade nem toda a área de perigo. A área de perigo de 34 nós do JTWC é onde ventos de 34 nós podem chegar, ampliada pelo erro da previsão de trajetória; não é um cone. Os rótulos dos pontos de previsão são horas de antecedência da fonte, não horários calculados a partir da emissão. A geometria acompanha a superfície; a altura não é altitude meteorológica. Consulte o boletim oficial ou o centro de alertas regional.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
|
||||
}
|
||||
@@ -1369,7 +1369,6 @@
|
||||
"None on screen — nearby cameras are outside the view": "На экране нет — ближайшие камеры вне поля зрения",
|
||||
"ALPR camera": "Камера ALPR",
|
||||
"OpenStreetMap · community mapped": "OpenStreetMap · данные сообщества",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Атлантика и восточная/центральная часть северного Тихого океана; покрытие циклонов не глобальное.",
|
||||
"Potential tropical cyclone": "Потенциальный тропический циклон",
|
||||
"Post-tropical cyclone": "Посттропический циклон",
|
||||
"Hurricane": "Ураган",
|
||||
@@ -1393,17 +1392,12 @@
|
||||
"Maximum sustained wind: {wind}": "Макс. устойчивый ветер: {wind}",
|
||||
"Pressure: {pressure}": "Давление: {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Сводка № {number} · выпущена {time}",
|
||||
"No active NHC/CPHC systems": "Нет активных систем NHC/CPHC",
|
||||
"Advisories unavailable": "Сводки недоступны",
|
||||
"Cyclones · NHC / CPHC": "Циклоны · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "Атлантика · вост./центр. Тихий океан",
|
||||
"{storms} · {name} selected": "{storms} · выбран {name}",
|
||||
"Official advisory ↗": "Официальная сводка ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "Действующие сводки NHC и CPHC о циклонах",
|
||||
"Wind unavailable": "Ветер: нет данных",
|
||||
"Advisory center / forecast track": "Центр циклона по сводке / прогнозный трек",
|
||||
"Center-track uncertainty cone": "Конус неопределённости трека центра",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Выберите шторм на карте или в списке, чтобы выделить его и переместить к нему камеру. Щёлкните по пустому месту карты, чтобы снять выделение. Контекст сводок NOAA NHC/CPHC. Конус описывает неопределённость прогнозного трека центра, а не размер шторма или всю зону опасности. Подписи прогнозных точек — заблаговременность источника в часах, а не время, рассчитанное от выпуска сводки. Геометрия следует поверхности; высота не отражает высоту погодных явлений. Сверяйтесь с официальной сводкой.",
|
||||
"Directions": "Маршруты",
|
||||
"{mode} — reroute for {modeLower}": "{mode} — перестроить маршрут: {modeLower}",
|
||||
"CLICK MAP": "ЩЁЛКНИТЕ ПО КАРТЕ",
|
||||
@@ -4637,5 +4631,18 @@
|
||||
"Telemetry reads while the model is on screen": "Телеметрия читается, пока модель на экране",
|
||||
"Connecting to telemetry…": "Подключение к телеметрии…",
|
||||
"{seconds} s": "{seconds} с",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Атлантика и восточная/центральная часть северного Тихого океана. JTWC: западная часть северного Тихого океана, северная часть Индийского океана и Южное полушарие.",
|
||||
"34-knot wind danger area": "Опасная зона ветра 34 узла",
|
||||
"Track and 34-knot wind danger area match this warning": "Трек и опасная зона ветра 34 узла соответствуют этому предупреждению",
|
||||
"Track/danger area awaiting warning {number}": "Трек и опасная зона появятся с предупреждением № {number}",
|
||||
"Track/danger area unavailable": "Трек и опасная зона недоступны",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Предупреждение JTWC: официальным является предупреждение регионального центра. Ветер JTWC — средний за 1 минуту.",
|
||||
"No active tropical cyclone warnings": "Нет действующих предупреждений о тропических циклонах",
|
||||
"Cyclones · NHC / CPHC · JTWC": "Циклоны · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "Все тропические бассейны",
|
||||
"JTWC warning ↗": "Предупреждение JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Действующие сводки и предупреждения о циклонах",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Выберите шторм на карте или в списке, чтобы выделить его и переместить камеру. Щелчок по пустому месту карты снимает выделение. Сводки NOAA NHC/CPHC и предупреждения JTWC. Конус NHC показывает неопределённость прогнозного трека центра, а не размер шторма или всю опасную зону. Опасная зона ветра 34 узла JTWC — это область, куда может дойти ветер 34 узла, расширенная на ошибку прогноза трека; это не конус. Подписи прогнозных точек — заблаговременность источника в часах, а не время, рассчитанное от выпуска. Геометрия следует поверхности; высота не является метеорологической высотой. Сверяйтесь с официальной сводкой или региональным центром предупреждений.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Предупреждение № {number} · выпущено {time}"
|
||||
}
|
||||
@@ -1352,7 +1352,6 @@
|
||||
"FOV {value}° (DATASHEET)": "FOV {value}° (DATABLAD)",
|
||||
"SPEC FOV {span}° (CAPABILITY)": "SPEC. FOV {span}° (FÖRMÅGA)",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · SPEC.: CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlanten och östra/centrala norra Stilla havet; ingen global täckning av cykloner.",
|
||||
"Cyclone advisories unavailable": "Cyklonbulletiner otillgängliga",
|
||||
"Cyclone data unavailable": "Cyklondata otillgängliga",
|
||||
"Potential tropical cyclone": "Potentiell tropisk cyklon",
|
||||
@@ -1376,17 +1375,12 @@
|
||||
"Maximum sustained wind: {wind}": "Högsta medelvind: {wind}",
|
||||
"Pressure: {pressure}": "Lufttryck: {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Bulletin {number} · utfärdad {time}",
|
||||
"No active NHC/CPHC systems": "Inga aktiva NHC/CPHC-system",
|
||||
"Advisories unavailable": "Bulletiner otillgängliga",
|
||||
"Cyclones · NHC / CPHC": "Cykloner · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "Atlanten · östra/centrala Stilla havet",
|
||||
"{storms} · {name} selected": "{storms} · {name} vald",
|
||||
"Official advisory ↗": "Officiell bulletin ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "Aktiva cyklonbulletiner från NHC och CPHC",
|
||||
"Wind unavailable": "Vind otillgänglig",
|
||||
"Advisory center / forecast track": "Centrum enligt bulletin / prognosbana",
|
||||
"Center-track uncertainty cone": "Osäkerhetskon för centrumbanan",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Välj en storm på kartan, eller välj en storm i listan för att markera den och flytta kameran dit. Klicka på en tom yta på kartan för att avmarkera. Underlag: bulletiner från NOAA NHC/CPHC. Konen beskriver osäkerheten i den prognostiserade centrumbanan, inte stormens storlek eller hela riskområdet. Etiketterna vid prognospunkterna är källans prognostimmar, inte tider beräknade från bulletinens utfärdande. Geometrin följer ytan; höjden motsvarar ingen höjd i atmosfären. Läs den officiella bulletinen.",
|
||||
"DRIVE": "BIL",
|
||||
"Drive": "Bil",
|
||||
"WALK": "GÅNG",
|
||||
@@ -4425,5 +4419,18 @@
|
||||
"Telemetry reads while the model is on screen": "Telemetri läses medan modellen syns på skärmen",
|
||||
"Connecting to telemetry…": "Ansluter till telemetri…",
|
||||
"{seconds} s": "{seconds} s",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Paneler, radiatorer och en antenn följer NASA:s telemetri i realtid. Den andra antennen står stilla och armarna rör sig som illustration."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Paneler, radiatorer och en antenn följer NASA:s telemetri i realtid. Den andra antennen står stilla och armarna rör sig som illustration.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlanten och östra/centrala norra Stilla havet. JTWC: västra norra Stilla havet, norra Indiska oceanen och södra halvklotet.",
|
||||
"34-knot wind danger area": "Riskområde för vind på 34 knop",
|
||||
"Track and 34-knot wind danger area match this warning": "Bana och riskområde för 34 knop stämmer med denna varning",
|
||||
"Track/danger area awaiting warning {number}": "Bana/riskområde väntar på varning {number}",
|
||||
"Track/danger area unavailable": "Bana/riskområde inte tillgängliga",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC-varning: den regionala centralens varning är den officiella. JTWC:s vindar är 1-minutsmedelvärden.",
|
||||
"No active tropical cyclone warnings": "Inga aktiva varningar för tropiska cykloner",
|
||||
"Cyclones · NHC / CPHC · JTWC": "Cykloner · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "Alla tropiska bassänger",
|
||||
"JTWC warning ↗": "JTWC-varning ↗",
|
||||
"Active cyclone advisories and warnings": "Aktiva cyklonbulletiner och varningar",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Välj en storm på kartan, eller välj en storm i listan för att markera den och flytta kameran. Klicka på en tom plats på kartan för att rensa markeringen. Bulletiner från NOAA NHC/CPHC och varningar från JTWC. NHC:s kon beskriver osäkerheten i centrums prognosbana, inte stormens storlek eller hela riskområdet. JTWC:s riskområde för 34 knop är där vindar på 34 knop kan nå, vidgat med felet i banprognosen; det är ingen kon. Etiketterna på prognospunkterna är källans prognostimmar, inte tider räknade från utgivningen. Geometrin följer ytan; höjden är inte väderhöjd. Läs den officiella bulletinen eller den regionala varningscentralen.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Varning {number} · utfärdad {time}"
|
||||
}
|
||||
@@ -658,7 +658,6 @@
|
||||
"SRC {value}": "ДЖЕР. {value}",
|
||||
"{value} CONTEXT": "КОНТЕКСТ: {value}",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ХАРАКТЕРИСТИКИ: CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Атлантика та східна/центральна частина північного Тихого океану; покриття циклонів не глобальне.",
|
||||
"Cyclone advisories unavailable": "Зведення про циклони недоступні",
|
||||
"Cyclone data unavailable": "Дані про циклони недоступні",
|
||||
"Potential tropical cyclone": "Потенційний тропічний циклон",
|
||||
@@ -684,17 +683,12 @@
|
||||
"Maximum sustained wind: {wind}": "Макс. середня швидкість вітру: {wind}",
|
||||
"Pressure: {pressure}": "Тиск: {pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Зведення № {number} · випущено {time}",
|
||||
"No active NHC/CPHC systems": "Немає активних систем NHC/CPHC",
|
||||
"Advisories unavailable": "Зведення недоступні",
|
||||
"Cyclones · NHC / CPHC": "Циклони · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "Атлантика · сх./центр. Тихий океан",
|
||||
"{storms} · {name} selected": "{storms} · вибрано {name}",
|
||||
"Official advisory ↗": "Офіційне зведення ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "Чинні зведення NHC і CPHC про циклони",
|
||||
"Wind unavailable": "Вітер: немає даних",
|
||||
"Advisory center / forecast track": "Центр циклону за зведенням / прогнозний трек",
|
||||
"Center-track uncertainty cone": "Конус невизначеності треку центру",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Виберіть шторм на карті або в списку, щоб виділити його й перемістити до нього камеру. Клацніть на порожньому місці карти, щоб зняти виділення. Контекст зведень NOAA NHC/CPHC. Конус описує невизначеність прогнозного треку центру, а не розмір шторму чи всю зону небезпеки. Підписи прогнозних точок показують завчасність прогнозу в годинах за даними джерела, а не час, розрахований від випуску зведення. Геометрія повторює поверхню; висота не відображає висоту погодних явищ. Звіряйтеся з офіційним зведенням.",
|
||||
"DRIVE": "АВТО",
|
||||
"Drive": "Автомобілем",
|
||||
"WALK": "ПІШКИ",
|
||||
@@ -4637,5 +4631,18 @@
|
||||
"Telemetry reads while the model is on screen": "Телеметрія читається, поки модель на екрані",
|
||||
"Connecting to telemetry…": "Підключення до телеметрії…",
|
||||
"{seconds} s": "{seconds} с",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації."
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації.",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Атлантика та східна/центральна частина північного Тихого океану. JTWC: західна частина північного Тихого океану, північна частина Індійського океану та Південна півкуля.",
|
||||
"34-knot wind danger area": "Небезпечна зона вітру 34 вузли",
|
||||
"Track and 34-knot wind danger area match this warning": "Трек і небезпечна зона вітру 34 вузли відповідають цьому попередженню",
|
||||
"Track/danger area awaiting warning {number}": "Очікуються трек і небезпечна зона для попередження № {number}",
|
||||
"Track/danger area unavailable": "Трек і небезпечна зона недоступні",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Попередження JTWC: офіційним є попередження регіонального центру. Вітер JTWC — середній за 1 хвилину.",
|
||||
"No active tropical cyclone warnings": "Немає чинних попереджень про тропічні циклони",
|
||||
"Cyclones · NHC / CPHC · JTWC": "Циклони · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "Усі тропічні басейни",
|
||||
"JTWC warning ↗": "Попередження JTWC ↗",
|
||||
"Active cyclone advisories and warnings": "Чинні зведення та попередження про циклони",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Виберіть шторм на карті або у списку, щоб виділити його й перемістити камеру. Клацання по порожньому місцю карти знімає виділення. Зведення NOAA NHC/CPHC та попередження JTWC. Конус NHC показує невизначеність прогнозного треку центру, а не розмір шторму чи всю небезпечну зону. Небезпечна зона вітру 34 вузли JTWC — це область, куди може дійти вітер 34 вузли, розширена на похибку прогнозу треку; це не конус. Підписи прогнозних точок — завчасність джерела в годинах, а не час, обчислений від випуску. Геометрія повторює поверхню; висота не є метеорологічною висотою. Звіряйтеся з офіційним зведенням або регіональним центром попереджень.",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Попередження № {number} · випущено {time}"
|
||||
}
|
||||
@@ -615,7 +615,6 @@
|
||||
"SRC {value}": "SRC {value}",
|
||||
"{value} CONTEXT": "{value} 态势",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · 规格:CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "仅覆盖大西洋及北太平洋东部和中部,并非全球气旋覆盖。",
|
||||
"Cyclone advisories unavailable": "气旋公告不可用",
|
||||
"Cyclone data unavailable": "气旋数据不可用",
|
||||
"Potential tropical cyclone": "潜在热带气旋",
|
||||
@@ -638,17 +637,12 @@
|
||||
"Maximum sustained wind: {wind}": "最大持续风速:{wind}",
|
||||
"Pressure: {pressure}": "气压:{pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · 第 {number} 号公告 · 发布于 {time}",
|
||||
"No active NHC/CPHC systems": "当前没有活跃的 NHC/CPHC 气旋",
|
||||
"Advisories unavailable": "公告不可用",
|
||||
"Cyclones · NHC / CPHC": "气旋 · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "大西洋 · 东/中太平洋",
|
||||
"{storms} · {name} selected": "{storms} · 已选择 {name}",
|
||||
"Official advisory ↗": "官方公告 ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "活跃的 NHC 与 CPHC 气旋公告",
|
||||
"Wind unavailable": "风场数据不可用",
|
||||
"Advisory center / forecast track": "公告中的气旋中心 / 预报路径",
|
||||
"Center-track uncertainty cone": "中心路径预报不确定范围",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "在地图上点选气旋,或在列表中点选气旋,即可选中并移动相机。点击空白地图区域可清除选择。内容来自 NOAA NHC/CPHC 公告。该区域表示气旋中心路径预报的不确定范围,不代表气旋大小或全部灾害影响范围。预报点标注的是数据源的预报时效(小时),不是按公告发布时刻推算的时间。几何图形贴地显示;显示高度并非气象高度。请以官方公告为准。",
|
||||
"DRIVE": "驾车",
|
||||
"Drive": "驾车",
|
||||
"WALK": "步行",
|
||||
@@ -4319,5 +4313,18 @@
|
||||
"Telemetry reads while the model is on screen": "模型显示在屏幕上时读取遥测",
|
||||
"Connecting to telemetry…": "正在连接遥测…",
|
||||
"{seconds} s": "{seconds} 秒",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。"
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC:大西洋及北太平洋东部/中部。JTWC:北太平洋西部、北印度洋及南半球。",
|
||||
"34-knot wind danger area": "34 节风危险区",
|
||||
"Track and 34-knot wind danger area match this warning": "路径和 34 节风危险区与本期警报一致",
|
||||
"Track/danger area awaiting warning {number}": "路径/危险区等待第 {number} 号警报",
|
||||
"Track/danger area unavailable": "路径/危险区不可用",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC 警报:以区域中心的警报为准。JTWC 风速为 1 分钟平均值。",
|
||||
"No active tropical cyclone warnings": "当前没有生效的热带气旋警报",
|
||||
"Cyclones · NHC / CPHC · JTWC": "气旋 · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "所有热带海域",
|
||||
"JTWC warning ↗": "JTWC 警报 ↗",
|
||||
"Active cyclone advisories and warnings": "生效的气旋公告和警报",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "在地图上选择风暴,或在列表中选择风暴以选中它并移动镜头。点击地图空白处可取消选择。NOAA NHC/CPHC 公告和 JTWC 警报。NHC 的预报不确定范围表示中心预报路径的不确定性,而不是风暴大小或整个危险区域。JTWC 的 34 节风危险区是 34 节风可能到达的范围,并按路径预报误差加宽;它不是预报不确定范围。预报点标签是数据源的预报时效(小时),不是根据发布时间计算的时刻。几何形状贴合地表;高度不是气象高度。请以官方公告或区域警报中心为准。",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 号警报 · 发布于 {time}"
|
||||
}
|
||||
@@ -615,7 +615,6 @@
|
||||
"SRC {value}": "SRC {value}",
|
||||
"{value} CONTEXT": "{value} 態勢",
|
||||
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · 規格:CCTV-DATABASE.COM",
|
||||
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "僅覆蓋大西洋及北太平洋東部和中部,並非全球氣旋覆蓋。",
|
||||
"Cyclone advisories unavailable": "氣旋公告不可用",
|
||||
"Cyclone data unavailable": "氣旋數據不可用",
|
||||
"Potential tropical cyclone": "潛在熱帶氣旋",
|
||||
@@ -638,17 +637,12 @@
|
||||
"Maximum sustained wind: {wind}": "最大持續風速:{wind}",
|
||||
"Pressure: {pressure}": "氣壓:{pressure}",
|
||||
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · 第 {number} 號公告 · 發布於 {time}",
|
||||
"No active NHC/CPHC systems": "當前沒有活躍的 NHC/CPHC 氣旋",
|
||||
"Advisories unavailable": "公告不可用",
|
||||
"Cyclones · NHC / CPHC": "氣旋 · NHC / CPHC",
|
||||
"Atlantic · E/C Pacific": "大西洋 · 東/中太平洋",
|
||||
"{storms} · {name} selected": "{storms} · 已選擇 {name}",
|
||||
"Official advisory ↗": "官方公告 ↗",
|
||||
"Active NHC and CPHC cyclone advisories": "活躍的 NHC 與 CPHC 氣旋公告",
|
||||
"Wind unavailable": "風場數據不可用",
|
||||
"Advisory center / forecast track": "公告中的氣旋中心 / 預報路徑",
|
||||
"Center-track uncertainty cone": "中心路徑預報不確定範圍",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "在地圖上點選氣旋,或在列表中點選氣旋,即可選中並移動相機。點擊空白地圖區域可清除選擇。內容來自 NOAA NHC/CPHC 公告。該區域表示氣旋中心路徑預報的不確定範圍,不代表氣旋大小或全部災害影響範圍。預報點標註的是數據源的預報時效(小時),不是按公告發布時刻推算的時間。幾何圖形貼地顯示;顯示高度並非氣象高度。請以官方公告為準。",
|
||||
"DRIVE": "駕車",
|
||||
"Drive": "駕車",
|
||||
"WALK": "步行",
|
||||
@@ -4319,5 +4313,18 @@
|
||||
"Telemetry reads while the model is on screen": "模型顯示在屏幕上時讀取遙測",
|
||||
"Connecting to telemetry…": "正在連接遙測…",
|
||||
"{seconds} s": "{seconds} 秒",
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。"
|
||||
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。",
|
||||
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC:大西洋及北太平洋東部/中部。JTWC:北太平洋西部、北印度洋及南半球。",
|
||||
"34-knot wind danger area": "34 節風危險區",
|
||||
"Track and 34-knot wind danger area match this warning": "路徑和 34 節風危險區與本期警報一致",
|
||||
"Track/danger area awaiting warning {number}": "路徑/危險區等待第 {number} 號警報",
|
||||
"Track/danger area unavailable": "路徑/危險區不可用",
|
||||
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC 警報:以區域中心的警報為準。JTWC 風速為 1 分鐘平均值。",
|
||||
"No active tropical cyclone warnings": "當前沒有生效的熱帶氣旋警報",
|
||||
"Cyclones · NHC / CPHC · JTWC": "氣旋 · NHC / CPHC · JTWC",
|
||||
"All tropical basins": "所有熱帶海域",
|
||||
"JTWC warning ↗": "JTWC 警報 ↗",
|
||||
"Active cyclone advisories and warnings": "生效的氣旋公告和警報",
|
||||
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "在地圖上選擇風暴,或在列表中選擇風暴以選中它並移動鏡頭。點擊地圖空白處可取消選擇。NOAA NHC/CPHC 公告和 JTWC 警報。NHC 的預報不確定範圍表示中心預報路徑的不確定性,而不是風暴大小或整個危險區域。JTWC 的 34 節風危險區是 34 節風可能到達的範圍,並按路徑預報誤差加寬;它不是預報不確定範圍。預報點標籤是數據源的預報時效(小時),不是根據發布時間計算的時刻。幾何形狀貼合地表;高度不是氣象高度。請以官方公告或區域警報中心為準。",
|
||||
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 號警報 · 發布於 {time}"
|
||||
}
|
||||
@@ -541,7 +541,7 @@
|
||||
"Conversation",
|
||||
"Country",
|
||||
"Cyan",
|
||||
"Cyclones · NHC / CPHC",
|
||||
"Cyclones · NHC / CPHC · JTWC",
|
||||
"DENSE",
|
||||
"DEST ---°",
|
||||
"DEST {bearing}",
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
|
||||
findByDoublingRadius,
|
||||
AWARENESS_RADIUS_M,
|
||||
aircraftClassMatches,
|
||||
} from '../../data/militaryAwarenessEngine.js';
|
||||
import {
|
||||
AWARENESS_MAX_EXAMPLES,
|
||||
@@ -52,29 +53,7 @@ export function createNavigation({
|
||||
return layerId === 'flights' || layerId === 'military';
|
||||
}
|
||||
|
||||
function normalizeAircraftClass(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function aircraftClassMatchesFilter(item, aircraftClass) {
|
||||
const requested = normalizeAircraftClass(aircraftClass);
|
||||
if (!requested) return true;
|
||||
const candidates = [
|
||||
item?.aircraftClass,
|
||||
item?.klass,
|
||||
item?.type,
|
||||
item?.typeCode,
|
||||
item?.typeName,
|
||||
]
|
||||
.map((value) => normalizeAircraftClass(value))
|
||||
.filter(Boolean);
|
||||
if (!candidates.length) return false;
|
||||
return candidates.some(
|
||||
(candidate) => candidate === requested || candidate.includes(requested),
|
||||
);
|
||||
}
|
||||
const aircraftClassMatchesFilter = aircraftClassMatches;
|
||||
|
||||
function selectNavigationTargets(
|
||||
sourceCohorts,
|
||||
@@ -265,7 +244,6 @@ export function createNavigation({
|
||||
summarizeAwarenessCohortForNavigation,
|
||||
resetNavigationVisitedCycle,
|
||||
isFlightLayer,
|
||||
normalizeAircraftClass,
|
||||
aircraftClassMatchesFilter,
|
||||
selectNavigationTargets,
|
||||
alternativeFlightAvailable,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { findCamera } from '../../render/rendererOf.js';
|
||||
import {
|
||||
FRAME_SIGNATURE_W,
|
||||
FRAME_SIGNATURE_H,
|
||||
@@ -41,6 +42,11 @@ export function fitToProjection(sourceW, sourceH) {
|
||||
};
|
||||
}
|
||||
|
||||
const PLANE_POINTS = ['mount', 'tl', 'tr', 'br', 'bl'];
|
||||
const _scratchPoints = [];
|
||||
// Keep the occluding surface below common negative geoid undulations.
|
||||
const HORIZON_MARGIN_M = 200;
|
||||
|
||||
export function createFrames({ state: layerState, services, parts, source }) {
|
||||
/**
|
||||
* FNV-1a over the RGB channels of a downsampled frame. Pure (takes the raw
|
||||
@@ -236,6 +242,22 @@ export function createFrames({ state: layerState, services, parts, source }) {
|
||||
ctx.fillText(status.slice(0, 58), 46, h - 42);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a camera's monitor plane may be on screen; what cannot be judged counts as visible.
|
||||
* @param {Object} record - Camera record.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function projectionInView(record) {
|
||||
const camera = findCamera(layerState._viewer);
|
||||
if (typeof camera?.visiblePoints !== 'function') return true;
|
||||
const placed = record.frustumPositions;
|
||||
if (!placed) return true;
|
||||
const points = _scratchPoints;
|
||||
points.length = 0;
|
||||
for (const key of PLANE_POINTS) points.push(placed[key]);
|
||||
return camera.visiblePoints(points, HORIZON_MARGIN_M) !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers a new frame fetch for an image-mode projection if the refresh
|
||||
* interval has elapsed. Active cameras refresh more frequently than idle ones.
|
||||
@@ -269,6 +291,8 @@ export function createFrames({ state: layerState, services, parts, source }) {
|
||||
// bypass a provider's explicit minimum between image requests.
|
||||
if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return;
|
||||
if (!force && sinceLastRefresh < refreshMs) return;
|
||||
// Skip before stamping lastImageRefreshAt, so the first tick back in view fetches.
|
||||
if (!force && !projectionInView(record)) return;
|
||||
runtime.lastImageRefreshAt = now;
|
||||
|
||||
const frameUrl = frameUrlFor(record.camera, refreshMs);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// 1920x1080 projection canvas, instead of being stretched to fill it.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
import { createFrames, fitToProjection } from './frames.js';
|
||||
import {
|
||||
FRAME_SIGNATURE_W,
|
||||
@@ -170,3 +171,110 @@ test('a failed pixel signature redraws rather than assuming equal content', () =
|
||||
assert.deepEqual(load(640, 480).at(-1), ['drawImage', 240, 0, 1440, 1080]);
|
||||
assert.equal(runtime.canvasStamp, 2);
|
||||
});
|
||||
|
||||
const MOUNT = { x: 0, y: 0, z: 0 };
|
||||
|
||||
function planeRecord() {
|
||||
return {
|
||||
camera: { id: 'plane' },
|
||||
position: MOUNT,
|
||||
frustumPositions: {
|
||||
mount: MOUNT,
|
||||
capCenter: { x: 1, y: 0, z: 0 },
|
||||
tl: { x: 1, y: -1, z: 1 },
|
||||
tr: { x: 1, y: 1, z: 1 },
|
||||
br: { x: 1, y: 1, z: -1 },
|
||||
bl: { x: 1, y: -1, z: -1 },
|
||||
},
|
||||
projection: {
|
||||
mode: 'image',
|
||||
image: {},
|
||||
imageLoading: false,
|
||||
imageReady: false,
|
||||
lastImageRefreshAt: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function framesFor(viewer) {
|
||||
const state = {
|
||||
_viewer: viewer,
|
||||
_healthById: new Map(),
|
||||
_activeCameraId: 'plane',
|
||||
};
|
||||
return createFrames({
|
||||
state,
|
||||
services: {},
|
||||
parts: {
|
||||
model: {
|
||||
safeNumber: (value, fallback) =>
|
||||
Number.isFinite(Number(value)) ? Number(value) : fallback,
|
||||
},
|
||||
},
|
||||
source: { getFrameUrl: () => '/api/cctv/frame?id=plane' },
|
||||
});
|
||||
}
|
||||
|
||||
function framesWithCamera(t, camera) {
|
||||
const host = {};
|
||||
t.after(bindRenderer(host, { camera }));
|
||||
return framesFor(host);
|
||||
}
|
||||
|
||||
test('a plane the renderer may show fetches its picture', (t) => {
|
||||
const visiblePoints = t.mock.fn(() => true);
|
||||
const frames = framesWithCamera(t, { visiblePoints });
|
||||
const record = planeRecord();
|
||||
frames.refreshProjectionImage(record);
|
||||
assert.match(
|
||||
record.projection.image.src,
|
||||
/^\/api\/cctv\/frame\?id=plane&projTs=/,
|
||||
);
|
||||
assert.equal(record.projection.imageLoading, true);
|
||||
assert.equal(visiblePoints.mock.callCount(), 1);
|
||||
const [points, margin] = visiblePoints.mock.calls[0].arguments;
|
||||
const { mount, tl, tr, br, bl } = record.frustumPositions;
|
||||
assert.deepEqual(points, [mount, tl, tr, br, bl]);
|
||||
assert.equal(points[0], mount);
|
||||
assert.equal(margin, 200);
|
||||
});
|
||||
|
||||
test('a plane the renderer cannot show is not fetched, but a forced refresh is', (t) => {
|
||||
const frames = framesWithCamera(t, { visiblePoints: () => false });
|
||||
const record = planeRecord();
|
||||
frames.refreshProjectionImage(record);
|
||||
assert.equal(record.projection.image.src, undefined);
|
||||
assert.equal(record.projection.lastImageRefreshAt, 0);
|
||||
frames.refreshProjectionImage(record, true);
|
||||
assert.match(record.projection.image.src, /projTs=/);
|
||||
});
|
||||
|
||||
test('a skipped refresh does not use up the interval', (t) => {
|
||||
let visible = false;
|
||||
const frames = framesWithCamera(t, { visiblePoints: () => visible });
|
||||
const record = planeRecord();
|
||||
frames.refreshProjectionImage(record);
|
||||
assert.equal(record.projection.image.src, undefined);
|
||||
visible = true;
|
||||
frames.refreshProjectionImage(record);
|
||||
assert.match(record.projection.image.src, /projTs=/);
|
||||
});
|
||||
|
||||
test('what cannot be judged counts as visible', (t) => {
|
||||
for (const frames of [
|
||||
framesWithCamera(t, { visiblePoints: () => null }),
|
||||
framesWithCamera(t, { pose: () => ({}) }),
|
||||
framesFor(null),
|
||||
]) {
|
||||
const record = planeRecord();
|
||||
frames.refreshProjectionImage(record);
|
||||
assert.match(record.projection.image.src, /projTs=/);
|
||||
}
|
||||
|
||||
const noGeometry = planeRecord();
|
||||
delete noGeometry.frustumPositions;
|
||||
const visiblePoints = t.mock.fn(() => false);
|
||||
framesWithCamera(t, { visiblePoints }).refreshProjectionImage(noGeometry);
|
||||
assert.equal(visiblePoints.mock.callCount(), 0);
|
||||
assert.match(noGeometry.projection.image.src, /projTs=/);
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { setLocale, t } from '../../i18n/index.js';
|
||||
|
||||
// The exact string the server sends (COVERAGE in server/providers/cyclones.js).
|
||||
const SERVER_COVERAGE =
|
||||
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
|
||||
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.';
|
||||
const time = '2026-09-16T03:00:00.000Z';
|
||||
const storm = {
|
||||
id: 'ep152026',
|
||||
|
||||
@@ -32,8 +32,14 @@ const utc = (value) =>
|
||||
? `${formatUtcDayMonth(value).replace('-', '-\u2060')}\u00a0${isolate(value.slice(11, 16))}\u00a0UTC`
|
||||
: t('Unavailable');
|
||||
const COVERAGE = msg(
|
||||
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.',
|
||||
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.',
|
||||
);
|
||||
// The layer's sources, and each storm's.
|
||||
const SOURCE = 'NOAA NHC / CPHC · JTWC';
|
||||
const AGENCY_SOURCES = Object.freeze({ nhc: 'NOAA NHC / CPHC', jtwc: 'JTWC' });
|
||||
const sourceOf = (storm) => AGENCY_SOURCES[storm?.agency] || AGENCY_SOURCES.nhc;
|
||||
const isJtwc = (storm) => storm?.agency === 'jtwc';
|
||||
const DANGER_AREA = msg('34-knot wind danger area');
|
||||
// The server sends the same English coverage (server/providers/cyclones.js);
|
||||
// data stays English and is translated here, where it is shown.
|
||||
const coverageText = (coverage) =>
|
||||
@@ -44,7 +50,9 @@ const SERVER_REASONS = new Set([msg('Cyclone data unavailable')]);
|
||||
const errorText = (error) =>
|
||||
error && (SERVER_REASONS.has(error) ? t(error) : translateKnown(error));
|
||||
// NHC's Tropical Cyclone Status JSON reference: PTC is post-tropical, PC is a
|
||||
// potential tropical cyclone, and subtropical systems are STS and STD.
|
||||
// potential tropical cyclone, and subtropical systems are STS and STD. JTWC
|
||||
// warns of typhoons (TY), super typhoons (STY), tropical cyclones (TC) and
|
||||
// subtropical storms and depressions (SS, SD).
|
||||
const CLASSIFICATION_NAMES = Object.freeze({
|
||||
PC: msg('Potential tropical cyclone'),
|
||||
PTC: msg('Post-tropical cyclone'),
|
||||
@@ -53,6 +61,11 @@ const CLASSIFICATION_NAMES = Object.freeze({
|
||||
TD: msg('Tropical depression'),
|
||||
STS: msg('Subtropical storm'),
|
||||
STD: msg('Subtropical depression'),
|
||||
TY: msg('Typhoon'),
|
||||
STY: msg('Super typhoon'),
|
||||
TC: msg('Tropical cyclone'),
|
||||
SS: msg('Subtropical storm'),
|
||||
SD: msg('Subtropical depression'),
|
||||
});
|
||||
const classificationName = (code) =>
|
||||
Object.hasOwn(CLASSIFICATION_NAMES, code)
|
||||
@@ -123,7 +136,7 @@ export function createCyclonesLayer({
|
||||
id: contextId,
|
||||
layerId: 'weather-cyclones',
|
||||
layerName: 'Cyclone advisories',
|
||||
source: 'NOAA NHC / CPHC',
|
||||
source: sourceOf(storm),
|
||||
label: storm.name,
|
||||
latitude: storm.position.latitude,
|
||||
longitude: storm.position.longitude,
|
||||
@@ -137,6 +150,7 @@ export function createCyclonesLayer({
|
||||
? CLASSIFICATION_NAMES[storm.classification]
|
||||
: undefined,
|
||||
basin: storm.basin,
|
||||
agency: storm.agency,
|
||||
advisoryNumber: storm.advisoryNumber,
|
||||
issuedAt: storm.issuedAt,
|
||||
positionAt: storm.positionAt,
|
||||
@@ -146,7 +160,7 @@ export function createCyclonesLayer({
|
||||
movementDirectionDegrees: storm.movement?.directionDegrees,
|
||||
movementSpeedKt: storm.movement?.speedKt,
|
||||
advisoryUrl: storm.advisoryUrl,
|
||||
// Only while the proxy serves its cache because NHC is unreachable.
|
||||
// Only while the proxy serves its cache because a source is unreachable.
|
||||
staleCacheFetchedAt:
|
||||
snapshot.stale && Number.isFinite(snapshot.fetchedAt)
|
||||
? new Date(snapshot.fetchedAt).toISOString()
|
||||
@@ -205,7 +219,7 @@ export function createCyclonesLayer({
|
||||
id: 'weather-cyclones',
|
||||
name: 'Cyclone advisories',
|
||||
icon: '◉',
|
||||
source: 'NOAA NHC / CPHC',
|
||||
source: SOURCE,
|
||||
updateInterval: 300_000,
|
||||
init(nextViewer) {
|
||||
viewer = nextViewer;
|
||||
@@ -361,13 +375,28 @@ export function createCyclonesLayer({
|
||||
snapshot && !snapshot.unavailable && snapshot.storms.length === 0;
|
||||
const geometry =
|
||||
storm &&
|
||||
(coherentCycloneGeometry(storm)
|
||||
? t('Track and cone match this advisory')
|
||||
: storm.geometryStatus === 'pending'
|
||||
? t('Track/cone awaiting advisory {number}', {
|
||||
number: storm.advisoryNumber,
|
||||
})
|
||||
: t('Track/cone unavailable'));
|
||||
(isJtwc(storm)
|
||||
? coherentCycloneGeometry(storm)
|
||||
? t('Track and 34-knot wind danger area match this warning')
|
||||
: storm.geometryStatus === 'pending'
|
||||
? t('Track/danger area awaiting warning {number}', {
|
||||
number: storm.advisoryNumber,
|
||||
})
|
||||
: t('Track/danger area unavailable')
|
||||
: coherentCycloneGeometry(storm)
|
||||
? t('Track and cone match this advisory')
|
||||
: storm.geometryStatus === 'pending'
|
||||
? t('Track/cone awaiting advisory {number}', {
|
||||
number: storm.advisoryNumber,
|
||||
})
|
||||
: t('Track/cone unavailable'));
|
||||
// JTWC is not the regional warning centre for any basin.
|
||||
const note =
|
||||
storm && isJtwc(storm)
|
||||
? t(
|
||||
'JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.',
|
||||
)
|
||||
: '';
|
||||
const status =
|
||||
errorText(error) ||
|
||||
(snapshot?.stale
|
||||
@@ -388,14 +417,21 @@ export function createCyclonesLayer({
|
||||
: '';
|
||||
const intensity = storm ? intensityText(storm) : '';
|
||||
const detail = storm
|
||||
? t('{name} · {classification} · Advisory {number} · issued {time}', {
|
||||
name: storm.name,
|
||||
classification: classificationName(storm.classification),
|
||||
number: storm.advisoryNumber,
|
||||
time: utc(storm.issuedAt),
|
||||
})
|
||||
? isJtwc(storm)
|
||||
? t('{name} · {classification} · Warning {number} · issued {time}', {
|
||||
name: storm.name,
|
||||
classification: classificationName(storm.classification),
|
||||
number: storm.advisoryNumber,
|
||||
time: utc(storm.issuedAt),
|
||||
})
|
||||
: t('{name} · {classification} · Advisory {number} · issued {time}', {
|
||||
name: storm.name,
|
||||
classification: classificationName(storm.classification),
|
||||
number: storm.advisoryNumber,
|
||||
time: utc(storm.issuedAt),
|
||||
})
|
||||
: empty
|
||||
? t('No active NHC/CPHC systems')
|
||||
? t('No active tropical cyclone warnings')
|
||||
: stormCount
|
||||
? activeStorms
|
||||
: loading
|
||||
@@ -404,8 +440,8 @@ export function createCyclonesLayer({
|
||||
const controls = {
|
||||
readout: true,
|
||||
summary: {
|
||||
label: t('Cyclones · NHC / CPHC'),
|
||||
coverage: t('Atlantic · E/C Pacific'),
|
||||
label: t('Cyclones · NHC / CPHC · JTWC'),
|
||||
coverage: t('All tropical basins'),
|
||||
compact: stormCount
|
||||
? storm
|
||||
? t('{storms} · {name} selected', {
|
||||
@@ -418,7 +454,9 @@ export function createCyclonesLayer({
|
||||
? [
|
||||
{
|
||||
id: 'advisory',
|
||||
label: t('Official advisory ↗'),
|
||||
label: isJtwc(storm)
|
||||
? t('JTWC warning ↗')
|
||||
: t('Official advisory ↗'),
|
||||
href: storm.advisoryUrl,
|
||||
},
|
||||
]
|
||||
@@ -436,6 +474,7 @@ export function createCyclonesLayer({
|
||||
text: intensity,
|
||||
},
|
||||
{ id: 'geometry', text: geometry, muted: true },
|
||||
{ id: 'note', text: note, muted: true },
|
||||
].filter((line) => line.text)
|
||||
: [],
|
||||
detail,
|
||||
@@ -443,7 +482,7 @@ export function createCyclonesLayer({
|
||||
units: 'kt',
|
||||
},
|
||||
list: {
|
||||
ariaLabel: t('Active NHC and CPHC cyclone advisories'),
|
||||
ariaLabel: t('Active cyclone advisories and warnings'),
|
||||
items: (snapshot?.storms || []).map((item, index) => ({
|
||||
id: item.id,
|
||||
ordinal: index + 1,
|
||||
@@ -461,17 +500,19 @@ export function createCyclonesLayer({
|
||||
label: t('Advisory center / forecast track'),
|
||||
color: '#7fe6ed',
|
||||
},
|
||||
{
|
||||
label: t('Center-track uncertainty cone'),
|
||||
color: '#7fe6ed44',
|
||||
},
|
||||
isJtwc(storm)
|
||||
? { label: t(DANGER_AREA), color: '#ffb15c44' }
|
||||
: {
|
||||
label: t('Center-track uncertainty cone'),
|
||||
color: '#7fe6ed44',
|
||||
},
|
||||
]
|
||||
: [],
|
||||
info: storm
|
||||
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}\n${coverageText(snapshot.coverage)}`
|
||||
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}${note ? '\n' + note : ''}\n${coverageText(snapshot.coverage)}`
|
||||
: `${detail}${status ? '\n' + status : ''}\n${coverageText(snapshot?.coverage)}`,
|
||||
infoTitle: t(
|
||||
'Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.',
|
||||
'Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.',
|
||||
),
|
||||
};
|
||||
return controls;
|
||||
@@ -518,7 +559,7 @@ export function createCyclonesLayer({
|
||||
loading,
|
||||
error,
|
||||
stale: Boolean(snapshot?.stale),
|
||||
source: 'NOAA NHC / CPHC',
|
||||
source: storm ? sourceOf(storm) : SOURCE,
|
||||
advisoryAt: storm?.issuedAt || null,
|
||||
empty: Boolean(
|
||||
snapshot && !snapshot.unavailable && !snapshot.storms.length,
|
||||
|
||||
@@ -861,7 +861,7 @@ test('advisory selection uses accessible row descriptors and shared camera hando
|
||||
const controls = h.layer.getRowControls();
|
||||
assert.equal(controls.readout, true);
|
||||
assert.deepEqual(controls.chips, []);
|
||||
assert.equal(controls.summary.coverage, 'Atlantic · E/C Pacific');
|
||||
assert.equal(controls.summary.coverage, 'All tropical basins');
|
||||
assert.equal(controls.summary.actions[0].href, storm().advisoryUrl);
|
||||
assert.equal(controls.summary.lines.length, 3);
|
||||
assert.deepEqual(controls.summary.settings, []);
|
||||
@@ -870,7 +870,7 @@ test('advisory selection uses accessible row descriptors and shared camera hando
|
||||
]);
|
||||
assert.match(controls.summary.compact, /2 active storms · .* selected/);
|
||||
assert.equal(controls.summary.sections, undefined);
|
||||
assert.match(controls.list.ariaLabel, /NHC/);
|
||||
assert.match(controls.list.ariaLabel, /cyclone advisories and warnings/);
|
||||
assert.equal(controls.list.items.length, 2);
|
||||
assert.equal(controls.list.items[0].active, true);
|
||||
assert.match(controls.info, /awaiting advisory 10/);
|
||||
@@ -912,7 +912,10 @@ test('empty successful coverage, unavailable source and stale advisory are diffe
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
assert.equal(h.layer.getStats().empty, true);
|
||||
assert.match(h.layer.getRowControls().summary.detail, /No active NHC\/CPHC/);
|
||||
assert.match(
|
||||
h.layer.getRowControls().summary.detail,
|
||||
/No active tropical cyclone warnings/,
|
||||
);
|
||||
next = { ...snapshot(), stale: true };
|
||||
await h.layer.update();
|
||||
assert.match(h.layer.getRowControls().summary.status, /stale/);
|
||||
@@ -987,3 +990,63 @@ test('external cancellation and acquisition failure cannot install or retain unl
|
||||
assert.ok(h.cleared > 0);
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
test('a JTWC warning reads as a warning, notes the official regional centre and its danger area', async () => {
|
||||
const jtwc = {
|
||||
...storm('sh042027'),
|
||||
agency: 'jtwc',
|
||||
name: 'Xavier',
|
||||
classification: 'TC',
|
||||
basin: 'SH',
|
||||
advisoryNumber: '15',
|
||||
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
|
||||
dangerArea: null,
|
||||
};
|
||||
const h = harness({ getSnapshot: async () => snapshot([jtwc]) });
|
||||
try {
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
const controls = h.layer.getRowControls();
|
||||
assert.match(
|
||||
plain(controls.summary.detail),
|
||||
/^Xavier · Tropical cyclone · Warning 15 · issued/,
|
||||
);
|
||||
assert.deepEqual(controls.summary.actions, [
|
||||
{ id: 'advisory', label: 'JTWC warning ↗', href: jtwc.advisoryUrl },
|
||||
]);
|
||||
const note = controls.summary.lines.find((line) => line.id === 'note');
|
||||
assert.equal(
|
||||
note.text,
|
||||
'JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.',
|
||||
);
|
||||
assert.match(controls.info, /awaiting warning 15/);
|
||||
assert.match(controls.info, /regional centre’s warning is official/);
|
||||
assert.deepEqual(
|
||||
controls.legend.map((item) => item.label),
|
||||
['Advisory center / forecast track', '34-knot wind danger area'],
|
||||
);
|
||||
assert.equal(h.layer.getStats().source, 'JTWC');
|
||||
} finally {
|
||||
h.layer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('an NHC advisory carries no JTWC note and keeps its cone legend', async () => {
|
||||
const h = harness({ getSnapshot: async () => snapshot([storm()]) });
|
||||
try {
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
const controls = h.layer.getRowControls();
|
||||
assert.equal(
|
||||
controls.summary.lines.find((line) => line.id === 'note'),
|
||||
undefined,
|
||||
);
|
||||
assert.deepEqual(
|
||||
controls.legend.map((item) => item.label),
|
||||
['Advisory center / forecast track', 'Center-track uncertainty cone'],
|
||||
);
|
||||
assert.equal(h.layer.getStats().source, 'NOAA NHC / CPHC');
|
||||
} finally {
|
||||
h.layer.destroy();
|
||||
}
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
setOverlayEntries,
|
||||
setOverlaySourceVisible,
|
||||
} from '../../overlays/worldOverlay.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
/**
|
||||
* @module cyclones/labels
|
||||
@@ -19,6 +20,8 @@ export const CYCLONE_LEAD_LABEL_MAX_DISTANCE_M = 4_000_000;
|
||||
export const CYCLONE_OVERLAY_COHORT_LIMIT = 64;
|
||||
/** Advisory centre and forecast track; single source for points and cards. */
|
||||
export const CYCLONE_ACCENT = '#7fe6ed';
|
||||
/** JTWC's 34-knot wind danger area: its fill, dashed edge and label. */
|
||||
export const CYCLONE_DANGER_ACCENT = '#ffb15c';
|
||||
/** Selected advisory centre. */
|
||||
export const CYCLONE_SELECTED_ACCENT = '#ffe19a';
|
||||
/** Point sizes the cards keep clear of. */
|
||||
@@ -112,7 +115,32 @@ function cycloneLeadEntry(stormId, point) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Storm cards for every storm and lead-hour labels for the selected one.
|
||||
* The name of the selected storm's 34-knot wind danger area, on its edge.
|
||||
* @param {string} stormId
|
||||
* @param {object} position
|
||||
* @returns {object}
|
||||
*/
|
||||
function cycloneDangerAreaEntry(stormId, position) {
|
||||
return {
|
||||
...SHARED_CARD,
|
||||
...markerClearance(0),
|
||||
id: `area:${stormId}`,
|
||||
position,
|
||||
variant: 'card',
|
||||
title: t('34-knot wind danger area'),
|
||||
details: [],
|
||||
accent: CYCLONE_DANGER_ACCENT,
|
||||
selected: false,
|
||||
protected: false,
|
||||
// Below every lead-hour label.
|
||||
priority: LEAD_PRIORITY - 200,
|
||||
maxDistance: Number.POSITIVE_INFINITY,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Storm cards for every storm, and lead-hour labels and the danger area's
|
||||
* name for the selected one.
|
||||
* @param {Array<object>} storms Renderer anchors with `forecasts`.
|
||||
* @param {?string} selectedId
|
||||
* @returns {Array<object>}
|
||||
@@ -125,13 +153,17 @@ export function cycloneOverlayEntries(storms, selectedId) {
|
||||
if (!selected) continue;
|
||||
for (const point of storm.forecasts || [])
|
||||
entries.push(cycloneLeadEntry(storm.id, point));
|
||||
if (storm.dangerArea)
|
||||
entries.push(cycloneDangerAreaEntry(storm.id, storm.dangerArea));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** Storm id behind a published card or lead-hour label id, else null. */
|
||||
/** Storm id behind a published card, lead-hour or area label id, else null. */
|
||||
export function cycloneStormIdFromEntryId(entryId) {
|
||||
const match = /^(?:storm|lead):([^:]+)(?::|$)/.exec(String(entryId ?? ''));
|
||||
const match = /^(?:storm|lead|area):([^:]+)(?::|$)/.exec(
|
||||
String(entryId ?? ''),
|
||||
);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -198,3 +198,7 @@ test('storm identity resolves from card and lead-hour ids only', () => {
|
||||
for (const value of ['vessel:123', 'storm:', 'lead:', '', null, undefined])
|
||||
assert.equal(cycloneStormIdFromEntryId(value), null, String(value));
|
||||
});
|
||||
|
||||
test('a danger area label names its storm', () => {
|
||||
assert.equal(cycloneStormIdFromEntryId('area:sh042027'), 'sh042027');
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { sphereFromPoints } from '../../geo/sphere.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import {
|
||||
CYCLONE_ACCENT,
|
||||
CYCLONE_DANGER_ACCENT,
|
||||
CYCLONE_MARKER_PX,
|
||||
CYCLONE_SELECTED_ACCENT,
|
||||
createCycloneLabels,
|
||||
@@ -24,6 +25,29 @@ export function coherentCycloneGeometry(storm) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a danger area's label sits: the vertex of its outer ring nearest the
|
||||
* forecast point halfway along the track (ECEF).
|
||||
*/
|
||||
function dangerAreaAnchor(ring, forecastPoints, ecef, lonLat) {
|
||||
const middle = forecastPoints[Math.floor(forecastPoints.length / 2)];
|
||||
if (!middle) return ring[0];
|
||||
const target = ecef(lonLat(middle.position));
|
||||
let best = ring[0],
|
||||
bestDistance = Infinity;
|
||||
for (const vertex of ring) {
|
||||
const d =
|
||||
(vertex.x - target.x) ** 2 +
|
||||
(vertex.y - target.y) ** 2 +
|
||||
(vertex.z - target.z) ** 2;
|
||||
if (d < bestDistance) {
|
||||
best = vertex;
|
||||
bestDistance = d;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** A `#rrggbb` colour at `alpha`, as CSS. */
|
||||
function withAlpha(hex, alpha) {
|
||||
const n = Number.parseInt(hex.slice(1), 16);
|
||||
@@ -64,7 +88,14 @@ export function createCycloneRendering({ viewer, overlayHost }) {
|
||||
forecasts = [],
|
||||
spheres = new Map(),
|
||||
itemStorms = new Map();
|
||||
let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
|
||||
const emptyCounts = () => ({
|
||||
storms: 0,
|
||||
tracks: 0,
|
||||
cones: 0,
|
||||
dangerAreas: 0,
|
||||
forecastPoints: 0,
|
||||
});
|
||||
let counts = emptyCounts();
|
||||
let itemCount = 0;
|
||||
|
||||
function centerItem(storm) {
|
||||
@@ -104,7 +135,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
|
||||
nextLines = [],
|
||||
nextCones = [],
|
||||
nextLabels = [];
|
||||
const nextCounts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
|
||||
const nextCounts = emptyCounts();
|
||||
const lonLat = ({ longitude, latitude }) => ({
|
||||
lon: longitude,
|
||||
lat: latitude,
|
||||
@@ -130,6 +161,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
|
||||
windKt: storm.windKt,
|
||||
position: center,
|
||||
forecasts: [],
|
||||
dangerArea: null,
|
||||
};
|
||||
nextLabels.push(label);
|
||||
nextCounts.storms++;
|
||||
@@ -151,38 +183,66 @@ export function createCycloneRendering({ viewer, overlayHost }) {
|
||||
});
|
||||
nextCounts.tracks++;
|
||||
});
|
||||
const polygons =
|
||||
storm.cone?.type === 'Polygon'
|
||||
? [storm.cone.coordinates]
|
||||
: storm.cone?.coordinates || [];
|
||||
polygons.forEach((rings, index) => {
|
||||
// Each exterior retains its own interior holes. Native geographic
|
||||
// tessellation handles the antimeridian; never flatten rings.
|
||||
const all = rings.map((ring) => ring.map(pair));
|
||||
const ecefRings = all.map((ring) => ring.map(ecef));
|
||||
extent.push(...ecefRings[0]);
|
||||
nextCones.push({
|
||||
id: own(`cyclone:${storm.id}:cone:${index}`),
|
||||
geometry: { kind: 'polygon', rings: all },
|
||||
fill: withAlpha(CYCLONE_ACCENT, 0.16),
|
||||
height: 'clampGround',
|
||||
});
|
||||
ecefRings.forEach((ring, ringIndex) => {
|
||||
nextLines.push({
|
||||
id: own(
|
||||
`cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
|
||||
),
|
||||
positions: ring,
|
||||
widthPx: 1,
|
||||
mode: 'draped',
|
||||
style: {
|
||||
kind: 'solid',
|
||||
color: withAlpha(CYCLONE_ACCENT, 0.55),
|
||||
},
|
||||
// NHC's cone of centre-track uncertainty, or JTWC's 34-knot wind
|
||||
// danger area: drawn apart, never one as the other.
|
||||
const areas = [
|
||||
{ kind: 'cone', shape: storm.cone, color: CYCLONE_ACCENT },
|
||||
{
|
||||
kind: 'danger',
|
||||
shape: storm.dangerArea,
|
||||
color: CYCLONE_DANGER_ACCENT,
|
||||
},
|
||||
];
|
||||
for (const { kind, shape, color } of areas) {
|
||||
const polygons =
|
||||
shape?.type === 'Polygon'
|
||||
? [shape.coordinates]
|
||||
: shape?.coordinates || [];
|
||||
polygons.forEach((rings, index) => {
|
||||
// Each exterior retains its own interior holes. Native
|
||||
// geographic tessellation handles the antimeridian; never
|
||||
// flatten rings.
|
||||
const all = rings.map((ring) => ring.map(pair));
|
||||
const ecefRings = all.map((ring) => ring.map(ecef));
|
||||
extent.push(...ecefRings[0]);
|
||||
nextCones.push({
|
||||
id: own(`cyclone:${storm.id}:${kind}:${index}`),
|
||||
geometry: { kind: 'polygon', rings: all },
|
||||
fill: withAlpha(color, kind === 'cone' ? 0.16 : 0.12),
|
||||
height: 'clampGround',
|
||||
});
|
||||
ecefRings.forEach((ring, ringIndex) => {
|
||||
nextLines.push({
|
||||
id: own(
|
||||
`cyclone:${storm.id}:${kind}:${index}:outline:${ringIndex}`,
|
||||
),
|
||||
positions: ring,
|
||||
widthPx: kind === 'cone' ? 1 : 1.5,
|
||||
mode: 'draped',
|
||||
style:
|
||||
kind === 'cone'
|
||||
? { kind: 'solid', color: withAlpha(color, 0.55) }
|
||||
: {
|
||||
kind: 'dash',
|
||||
color: withAlpha(color, 0.8),
|
||||
length: 16,
|
||||
},
|
||||
});
|
||||
});
|
||||
if (kind === 'cone') nextCounts.cones++;
|
||||
else {
|
||||
nextCounts.dangerAreas++;
|
||||
// The area's name sits on its edge nearest the middle of
|
||||
// the forecast track.
|
||||
label.dangerArea ??= dangerAreaAnchor(
|
||||
ecefRings[0],
|
||||
storm.forecastPoints,
|
||||
ecef,
|
||||
lonLat,
|
||||
);
|
||||
}
|
||||
});
|
||||
nextCounts.cones++;
|
||||
});
|
||||
}
|
||||
for (const [index, point] of storm.forecastPoints.entries()) {
|
||||
if (point.tauHours === 0) continue;
|
||||
const pos = lonLat(point.position);
|
||||
@@ -252,7 +312,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
|
||||
itemStorms = new Map();
|
||||
itemCount = 0;
|
||||
selected = null;
|
||||
counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
|
||||
counts = emptyCounts();
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
|
||||
@@ -210,6 +210,7 @@ test('advisory geometry keeps polygon parts, holes and geographic seam coordinat
|
||||
storms: 1,
|
||||
tracks: 1,
|
||||
cones: 2,
|
||||
dangerAreas: 0,
|
||||
forecastPoints: 1,
|
||||
dataSources: 1,
|
||||
entities: 8,
|
||||
@@ -375,6 +376,7 @@ test('clear empties the sets and a later advisory draws again', async () => {
|
||||
storms: 0,
|
||||
tracks: 0,
|
||||
cones: 0,
|
||||
dangerAreas: 0,
|
||||
forecastPoints: 0,
|
||||
dataSources: 0,
|
||||
entities: 0,
|
||||
@@ -451,3 +453,50 @@ test('labels publish committed anchors to the shared overlay and follow selectio
|
||||
h.rendering.destroy();
|
||||
assert.equal(h.overlay.calls.at(-1), afterClear[1]);
|
||||
});
|
||||
|
||||
test('a JTWC danger area is drawn apart from any cone, with a dashed edge and its name for the selected storm', async () => {
|
||||
const h = harness();
|
||||
const jtwc = {
|
||||
...storm(),
|
||||
id: 'sh042027',
|
||||
cone: null,
|
||||
dangerArea: {
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[178, 10],
|
||||
[-178, 10],
|
||||
[-178, 20],
|
||||
[178, 10],
|
||||
],
|
||||
],
|
||||
},
|
||||
};
|
||||
assert.equal(await h.rendering.setSnapshot({ storms: [jtwc] }), true);
|
||||
const [area] = [...h.sets.cones.items.values()];
|
||||
assert.equal(area.id, 'cyclone:sh042027:danger:0');
|
||||
assert.equal(area.fill, 'rgba(255,177,92,0.12)');
|
||||
const outline = [...h.sets.lines.items.values()].find(
|
||||
(line) => line.id === 'cyclone:sh042027:danger:0:outline:0',
|
||||
);
|
||||
assert.deepEqual(outline.style, {
|
||||
kind: 'dash',
|
||||
color: 'rgba(255,177,92,0.8)',
|
||||
length: 16,
|
||||
});
|
||||
const diagnostics = h.rendering.getDiagnostics();
|
||||
assert.equal(diagnostics.cones, 0);
|
||||
assert.equal(diagnostics.dangerAreas, 1);
|
||||
// A click on the area names its storm.
|
||||
assert.equal(
|
||||
h.rendering.pickStorm(h.hit('cones', 'cyclone:sh042027:danger:0')),
|
||||
'sh042027',
|
||||
);
|
||||
assert.equal(h.overlay.entry('area:sh042027'), null, 'unselected: no name');
|
||||
h.rendering.setSelection('sh042027');
|
||||
const name = h.overlay.entry('area:sh042027');
|
||||
assert.equal(name.title, '34-knot wind danger area');
|
||||
// On the area's edge, at the vertex nearest the middle forecast point.
|
||||
assert.deepEqual(name.position, fromDegrees(-178, 20, 0));
|
||||
h.rendering.destroy();
|
||||
});
|
||||
@@ -45,22 +45,33 @@ const position = (value) => {
|
||||
};
|
||||
};
|
||||
|
||||
function officialLink(value, outlook = false) {
|
||||
/** The agencies whose advisories the snapshot carries. */
|
||||
export const CYCLONE_AGENCIES = Object.freeze(['nhc', 'jtwc']);
|
||||
// Each agency's storm ids, advisory links and outlook links.
|
||||
const AGENCY_RULES = Object.freeze({
|
||||
nhc: {
|
||||
id: /^(?:al|ep|cp)\d{6}$/,
|
||||
origin: 'https://www.nhc.noaa.gov',
|
||||
advisory: /^\/text\/[A-Z0-9]+\.shtml$/,
|
||||
outlook: /^\/gtwo\.php\?basin=(?:atlc|epac|cpac)&fdays=7$/,
|
||||
},
|
||||
jtwc: {
|
||||
id: /^(?:wp|io|sh|ep|cp)\d{6}$/,
|
||||
origin: 'https://www.metoc.navy.mil',
|
||||
advisory: /^\/jtwc\/products\/[a-z]{2}\d{4}web\.txt$/,
|
||||
outlook: /^\/jtwc\/products\/(?:abpw|abio)web\.txt$/,
|
||||
},
|
||||
});
|
||||
|
||||
function officialLink(value, rules, outlook = false) {
|
||||
if (value === null) return null;
|
||||
const url = new URL(text(value, 256));
|
||||
if (
|
||||
url.origin !== 'https://www.nhc.noaa.gov' ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.hash
|
||||
)
|
||||
if (url.origin !== rules.origin || url.username || url.password || url.hash)
|
||||
throw malformed();
|
||||
if (
|
||||
outlook
|
||||
? !/^\/gtwo\.php\?basin=(?:atlc|epac|cpac)&fdays=7$/.test(
|
||||
url.pathname + url.search,
|
||||
)
|
||||
: url.search || !/^\/text\/[A-Z0-9]+\.shtml$/.test(url.pathname)
|
||||
? !rules.outlook.test(url.pathname + url.search)
|
||||
: url.search || !rules.advisory.test(url.pathname)
|
||||
)
|
||||
throw malformed();
|
||||
return url.href;
|
||||
@@ -122,8 +133,14 @@ export function validateCycloneSnapshot(value) {
|
||||
const seen = new Set(),
|
||||
budget = { coordinates: 0, points: 0 };
|
||||
const storms = value.storms.map((raw) => {
|
||||
// A snapshot from before agencies carries NHC storms only.
|
||||
const agency = raw?.agency === undefined ? 'nhc' : raw.agency;
|
||||
const rules = Object.hasOwn(AGENCY_RULES, agency)
|
||||
? AGENCY_RULES[agency]
|
||||
: null;
|
||||
if (
|
||||
!/^(?:al|ep|cp)\d{6}$/.test(raw?.id) ||
|
||||
!rules ||
|
||||
!rules.id.test(raw?.id) ||
|
||||
seen.has(raw.id) ||
|
||||
!['current', 'pending', 'unavailable'].includes(raw.geometryStatus)
|
||||
)
|
||||
@@ -158,20 +175,27 @@ export function validateCycloneSnapshot(value) {
|
||||
};
|
||||
});
|
||||
const track = geometry(raw.track, 'track', budget),
|
||||
cone = geometry(raw.cone, 'cone', budget);
|
||||
cone = geometry(raw.cone, 'cone', budget),
|
||||
dangerArea = geometry(raw.dangerArea ?? null, 'cone', budget);
|
||||
// NHC draws a cone of centre-track uncertainty; JTWC publishes none, but
|
||||
// a 34-knot wind danger area, which is never a cone.
|
||||
const area = agency === 'nhc' ? cone : dangerArea;
|
||||
if ((agency === 'nhc' && dangerArea) || (agency === 'jtwc' && cone))
|
||||
throw malformed();
|
||||
if (
|
||||
raw.geometryStatus !== 'current' &&
|
||||
(track || cone || forecastPoints.length)
|
||||
(track || area || forecastPoints.length)
|
||||
)
|
||||
throw malformed();
|
||||
if (
|
||||
raw.geometryStatus === 'current' &&
|
||||
(!track || !cone || !forecastPoints.length)
|
||||
(!track || !area || !forecastPoints.length)
|
||||
)
|
||||
throw malformed();
|
||||
if (raw.basin !== raw.id.slice(0, 2).toUpperCase()) throw malformed();
|
||||
return {
|
||||
id: raw.id,
|
||||
agency,
|
||||
name: text(raw.name, 80),
|
||||
classification: text(raw.classification, 16),
|
||||
basin: raw.basin,
|
||||
@@ -185,13 +209,14 @@ export function validateCycloneSnapshot(value) {
|
||||
directionDegrees: number(raw.movement?.directionDegrees, 0, 360),
|
||||
speedKt: number(raw.movement?.speedKt, 0, 200),
|
||||
},
|
||||
advisoryUrl: officialLink(raw.advisoryUrl),
|
||||
outlookUrl: officialLink(raw.outlookUrl, true),
|
||||
advisoryUrl: officialLink(raw.advisoryUrl, rules),
|
||||
outlookUrl: officialLink(raw.outlookUrl, rules, true),
|
||||
geometryStatus: raw.geometryStatus,
|
||||
geometryAdvisoryNumber,
|
||||
forecastPoints,
|
||||
track,
|
||||
cone,
|
||||
dangerArea,
|
||||
};
|
||||
});
|
||||
if (value.unavailable && storms.length) throw malformed();
|
||||
|
||||
@@ -230,3 +230,69 @@ test('source deadline cancels request and removes timer on completion', async (t
|
||||
await rejected;
|
||||
assert.equal(signal.aborted, true);
|
||||
});
|
||||
|
||||
/** The current advisory as a JTWC warning with its 34-knot danger area. */
|
||||
function jtwc() {
|
||||
const value = current(),
|
||||
storm = value.storms[0];
|
||||
Object.assign(storm, {
|
||||
id: 'sh042027',
|
||||
agency: 'jtwc',
|
||||
basin: 'SH',
|
||||
classification: 'TC',
|
||||
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
|
||||
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
|
||||
dangerArea: storm.cone,
|
||||
cone: null,
|
||||
});
|
||||
return value;
|
||||
}
|
||||
|
||||
test('a JTWC warning is accepted with its danger area and its own links, never with a cone', () => {
|
||||
const [storm] = validateCycloneSnapshot(jtwc()).storms;
|
||||
assert.equal(storm.agency, 'jtwc');
|
||||
assert.equal(storm.cone, null);
|
||||
assert.equal(storm.dangerArea.type, 'MultiPolygon');
|
||||
assert.equal(
|
||||
storm.advisoryUrl,
|
||||
'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
|
||||
);
|
||||
// A snapshot from before agencies is NHC's.
|
||||
assert.equal(validateCycloneSnapshot(current()).storms[0].agency, 'nhc');
|
||||
for (const change of [
|
||||
(s) => (s.cone = s.dangerArea),
|
||||
(s) => (s.dangerArea = null),
|
||||
(s) => (s.agency = 'jma'),
|
||||
(s) => (s.id = 'al042027'),
|
||||
(s) => (s.basin = 'WP'),
|
||||
(s) => (s.advisoryUrl = 'https://www.nhc.noaa.gov/text/MIATCMEP5.shtml'),
|
||||
(s) => (s.advisoryUrl = 'https://www.metoc.navy.mil/jtwc/other.txt'),
|
||||
(s) =>
|
||||
(s.outlookUrl = 'https://www.nhc.noaa.gov/gtwo.php?basin=epac&fdays=7'),
|
||||
]) {
|
||||
const value = jtwc();
|
||||
change(value.storms[0]);
|
||||
assert.throws(() => validateCycloneSnapshot(value), /Malformed/);
|
||||
}
|
||||
// NHC keeps its cone and never carries a danger area; its ids stay its own.
|
||||
const nhc = current();
|
||||
nhc.storms[0].dangerArea = nhc.storms[0].cone;
|
||||
assert.throws(() => validateCycloneSnapshot(nhc), /Malformed/);
|
||||
const western = current();
|
||||
western.storms[0].id = 'wp012026';
|
||||
western.storms[0].basin = 'WP';
|
||||
assert.throws(() => validateCycloneSnapshot(western), /Malformed/);
|
||||
// A pending JTWC warning carries no geometry.
|
||||
const pending = jtwc();
|
||||
Object.assign(pending.storms[0], {
|
||||
geometryStatus: 'pending',
|
||||
geometryAdvisoryNumber: null,
|
||||
forecastPoints: [],
|
||||
track: null,
|
||||
dangerArea: null,
|
||||
});
|
||||
assert.equal(
|
||||
validateCycloneSnapshot(pending).storms[0].geometryStatus,
|
||||
'pending',
|
||||
);
|
||||
});
|
||||
@@ -21,6 +21,11 @@ import { ISS_NORAD, TRACKED_ORBIT_COLOR } from './policy.js';
|
||||
import { toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import {
|
||||
clearFocusTarget,
|
||||
getFocusTarget,
|
||||
publishFocusTargetAt,
|
||||
} from '../../data/focusDeemphasis.js';
|
||||
|
||||
const COMPANION = 25545;
|
||||
const GPS = 32711;
|
||||
@@ -70,7 +75,14 @@ function fakeFollowCamera() {
|
||||
camera.flightsCancelled += 1;
|
||||
},
|
||||
flyTo() {},
|
||||
pose: () => ({ lon: 0, lat: 0, height: 2e7, heading: 0, pitch: -1.57 }),
|
||||
pose: () => ({
|
||||
lon: 0,
|
||||
lat: 0,
|
||||
height: 2e7,
|
||||
heading: 0,
|
||||
pitch: -1.57,
|
||||
position: { x: 2.6378e7, y: 0, z: 0 },
|
||||
}),
|
||||
on(event, cb) {
|
||||
if (event !== 'followChanged') return () => {};
|
||||
listeners.add(cb);
|
||||
@@ -135,7 +147,13 @@ const SENSORS = indexImagingSensors({
|
||||
],
|
||||
});
|
||||
|
||||
async function fixture(t) {
|
||||
/**
|
||||
* @param {object} t The test context.
|
||||
* @param {{realFocus?: boolean}} [options] `realFocus` publishes through the
|
||||
* shared focus rectangle, with a query port that projects every point to
|
||||
* the screen centre.
|
||||
*/
|
||||
async function fixture(t, { realFocus = false } = {}) {
|
||||
const source = {
|
||||
async readGroup(group) {
|
||||
const text = GROUP_TEXT[group] || '';
|
||||
@@ -165,6 +183,9 @@ async function fixture(t) {
|
||||
getFocusTarget: () => null,
|
||||
focusNowMs: (now) => now,
|
||||
focusPassIsNeeded: () => false,
|
||||
...(realFocus
|
||||
? { clearFocusTarget, getFocusTarget, publishFocusTargetAt }
|
||||
: {}),
|
||||
},
|
||||
context: {
|
||||
clearTrackedSubjectContext: noop,
|
||||
@@ -203,7 +224,12 @@ async function fixture(t) {
|
||||
const viewer = { canvas: new EventTarget(), scene: {} };
|
||||
const camera = fakeFollowCamera();
|
||||
const frame = fakeFrame();
|
||||
const { draw, unbind } = bindFakeDraw(viewer, { camera, frame });
|
||||
const query = { project: () => ({ x: 720, y: 450 }) };
|
||||
const { draw, unbind } = bindFakeDraw(viewer, {
|
||||
camera,
|
||||
frame,
|
||||
...(realFocus ? { query } : {}),
|
||||
});
|
||||
const input = fakeInput(viewer);
|
||||
let frameNumber = 1;
|
||||
const { log, warn } = console;
|
||||
@@ -221,6 +247,7 @@ async function fixture(t) {
|
||||
console.log = log;
|
||||
input.destroy();
|
||||
unbind();
|
||||
if (realFocus) clearFocusTarget();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
@@ -412,6 +439,27 @@ test('holding the subject hides its dot, ring, docked companions and bracket', a
|
||||
assert.ok(f.detected().includes(ISS_NORAD));
|
||||
});
|
||||
|
||||
test('releasing a satellite leaves no focus rectangle, even when a follow listener reads it', async (t) => {
|
||||
const f = await fixture(t, { realFocus: true });
|
||||
// As the Cockpit entry button does: every follow change asks for the subject.
|
||||
let readsOnRelease = 0;
|
||||
f.camera.on('followChanged', (followed) => {
|
||||
if (followed) return;
|
||||
readsOnRelease += 1;
|
||||
f.methods.getCockpitSubject();
|
||||
});
|
||||
assert.equal(f.track(GPS), true);
|
||||
f.nextFrame();
|
||||
f.methods.getCockpitSubject();
|
||||
assert.equal(getFocusTarget()?.ownerLayer, 'satellites');
|
||||
assert.equal(getFocusTarget()?.id, GPS);
|
||||
|
||||
f.methods.stopTracking();
|
||||
assert.equal(readsOnRelease, 1, 'the listener ran during the release');
|
||||
assert.equal(f.methods.getCockpitSubject(), null);
|
||||
assert.equal(getFocusTarget(), null);
|
||||
});
|
||||
|
||||
test('a subject that is not tracked holds nothing', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(GPS);
|
||||
|
||||
@@ -90,18 +90,18 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
return;
|
||||
}
|
||||
const clearedNorad = layerState._trackedNorad;
|
||||
clearFocusTarget('satellites', layerState._trackedNorad);
|
||||
clearFocusTarget('satellites', clearedNorad);
|
||||
|
||||
// Re-show the dot (hidden while the tracked dot drew it) and
|
||||
// restore the original group palette from the shared style table (WS-D3)
|
||||
parts.rendering._restorePoint(
|
||||
layerState._trackedNorad,
|
||||
clearedNorad,
|
||||
parts.controls._pointStyleFor(
|
||||
layerState._trackedNorad,
|
||||
layerState._catalog.get(layerState._trackedNorad)?.group,
|
||||
clearedNorad,
|
||||
layerState._catalog.get(clearedNorad)?.group,
|
||||
),
|
||||
// Back to its class's visibility: a hidden class stays hidden.
|
||||
parts.controls._classVisible(layerState._trackedNorad),
|
||||
parts.controls._classVisible(clearedNorad),
|
||||
);
|
||||
|
||||
// Invalidate the per-frame tracked-position cache (WS-D2)
|
||||
@@ -109,9 +109,13 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
layerState._trackedFrameGeo = null;
|
||||
|
||||
// Remove the tracked dot and orbit path (unless ISS — keep its path)
|
||||
if (layerState._trackedNorad !== ISS_NORAD) {
|
||||
parts.rendering._hideOrbitPath(layerState._trackedNorad);
|
||||
if (clearedNorad !== ISS_NORAD) {
|
||||
parts.rendering._hideOrbitPath(clearedNorad);
|
||||
}
|
||||
// Released before the camera hears of it: a follow listener that reads
|
||||
// the tracked position mid-release must find nothing, or it would publish
|
||||
// the focus rectangle again after it was cleared above.
|
||||
layerState._trackedNorad = null;
|
||||
if (layerState._viewer && !skipViewerUntrack)
|
||||
stopFollowing(layerState._viewer);
|
||||
layerState._followTarget = null;
|
||||
@@ -119,7 +123,6 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
parts.rendering._removeTrackedEntity(layerState._trackedEntity);
|
||||
layerState._trackedEntity = null;
|
||||
}
|
||||
layerState._trackedNorad = null;
|
||||
layerState._trackedDockedToStation = null;
|
||||
layerState._trackedDockedToIss = false;
|
||||
parts.controls._syncIssOrbit?.();
|
||||
|
||||
@@ -9,7 +9,7 @@ import { poseSignature } from '../../render/camera/poseSignature.js';
|
||||
import { heightsOf } from '../../queries/heights.js';
|
||||
import { fromDegreesInto } from '../../geo/ellipsoid.js';
|
||||
import { Vec3 } from '../../geo/vector.js';
|
||||
import { frustumPlanes } from '../../geo/frustum.js';
|
||||
import { viewPlanes } from '../../geo/frustum.js';
|
||||
import { perspectiveCourseRotation } from '../../data/screenRotation.js';
|
||||
import {
|
||||
PLACED_WAKE_MS,
|
||||
@@ -1074,23 +1074,6 @@ export function createRendering({ state, services, parts }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The planes of the frustum the camera looks through, as the default
|
||||
* renderer culls with them, or null when the pose does not describe one.
|
||||
*/
|
||||
function viewPlanes(pose) {
|
||||
if (
|
||||
!pose?.position ||
|
||||
!pose.direction ||
|
||||
!pose.up ||
|
||||
!Number.isFinite(pose.fovy) ||
|
||||
!Number.isFinite(pose.aspectRatio) ||
|
||||
!Number.isFinite(pose.near)
|
||||
)
|
||||
return null;
|
||||
return frustumPlanes(pose);
|
||||
}
|
||||
|
||||
function refreshVisibility() {
|
||||
if (!state._enabled) return 0;
|
||||
const now = Date.now();
|
||||
|
||||
@@ -86,6 +86,62 @@ function sameMatrix(array, matrix) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const finiteVector = (v) =>
|
||||
!!v && Number.isFinite(v.x) && Number.isFinite(v.y) && Number.isFinite(v.z);
|
||||
|
||||
/** Conservative globe/frustum visibility; null means unknown. */
|
||||
export function createPointsVisibility(scene, camera) {
|
||||
const visibilitySphere = new Cesium.BoundingSphere();
|
||||
let visibilityMargin = null;
|
||||
let visibilityEllipsoid = null;
|
||||
let visibilityOccluder = null;
|
||||
return function visiblePoints(points, marginM) {
|
||||
const eye = camera.positionWC;
|
||||
const direction = camera.directionWC;
|
||||
const up = camera.upWC;
|
||||
if (
|
||||
scene.mode !== Cesium.SceneMode.SCENE3D ||
|
||||
!points?.length ||
|
||||
!finiteVector(eye) ||
|
||||
!finiteVector(direction) ||
|
||||
!finiteVector(up) ||
|
||||
!points.every(finiteVector)
|
||||
)
|
||||
return null;
|
||||
if (visibilityMargin !== marginM) {
|
||||
const radii = Cesium.Ellipsoid.WGS84.radii;
|
||||
visibilityMargin = marginM;
|
||||
visibilityEllipsoid = new Cesium.Ellipsoid(
|
||||
radii.x - marginM,
|
||||
radii.y - marginM,
|
||||
radii.z - marginM,
|
||||
);
|
||||
visibilityOccluder = new Cesium.EllipsoidalOccluder(visibilityEllipsoid);
|
||||
}
|
||||
const inverse = visibilityEllipsoid.oneOverRadii;
|
||||
// Inside the ellipsoid Cesium's occluder hides nearby points; judge by the frustum alone.
|
||||
const outside =
|
||||
Math.hypot(eye.x * inverse.x, eye.y * inverse.y, eye.z * inverse.z) >= 1;
|
||||
if (outside) {
|
||||
visibilityOccluder.cameraPosition = eye;
|
||||
let visible = false;
|
||||
for (const p of points) {
|
||||
if (visibilityOccluder.isPointVisible(p)) {
|
||||
visible = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!visible) return false;
|
||||
}
|
||||
const culling = camera.frustum.computeCullingVolume(eye, direction, up);
|
||||
return (
|
||||
culling.computeVisibility(
|
||||
Cesium.BoundingSphere.fromPoints(points, visibilitySphere),
|
||||
) !== Cesium.Intersect.OUTSIDE
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{scene: object, camera: object, report: (error: unknown) => void,
|
||||
* widget?: object, capabilities?: ReadonlySet<string>,
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
headlessCamera,
|
||||
withVirtualClock,
|
||||
} from './cameraGoldens.js';
|
||||
import { createCesiumCamera } from './camera.js';
|
||||
import { createCesiumCamera, createPointsVisibility } from './camera.js';
|
||||
import { createCesiumPorts } from './ports.js';
|
||||
import { bindRenderer, cameraOf } from '../rendererOf.js';
|
||||
|
||||
@@ -337,6 +337,147 @@ test('the camera port gives the clock its own tick back as it goes', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('visiblePoints is there only with its capability, and unknown outside 3D', (t) => {
|
||||
const { scene } = headlessCamera();
|
||||
for (const name of ['preUpdate', 'postUpdate', 'preRender', 'postRender'])
|
||||
scene[name] = new Cesium.Event();
|
||||
scene.primitives = { add() {}, remove() {} };
|
||||
scene.requestRender = () => {};
|
||||
const viewer = { scene, clock: { currentTime: Cesium.JulianDate.now() } };
|
||||
const without = createCesiumPorts(viewer, { capabilities: new Set() });
|
||||
assert.equal(without.camera.visiblePoints, undefined);
|
||||
without.dispose();
|
||||
const ports = createCesiumPorts(viewer, {
|
||||
capabilities: new Set(['pointVisibility']),
|
||||
});
|
||||
t.after(() => ports.dispose());
|
||||
const points = [Cesium.Cartesian3.fromDegrees(0, 0, 10)];
|
||||
for (const mode of [
|
||||
Cesium.SceneMode.SCENE2D,
|
||||
Cesium.SceneMode.COLUMBUS_VIEW,
|
||||
Cesium.SceneMode.MORPHING,
|
||||
undefined,
|
||||
]) {
|
||||
scene.mode = mode;
|
||||
assert.equal(ports.camera.visiblePoints(points, 200), null);
|
||||
}
|
||||
scene.mode = Cesium.SceneMode.SCENE3D;
|
||||
assert.equal(typeof ports.camera.visiblePoints(points, 200), 'boolean');
|
||||
});
|
||||
|
||||
const point = (lon, lat, altitude = 20) =>
|
||||
Cesium.Cartesian3.fromDegrees(lon, lat, altitude);
|
||||
const down = Cesium.Cartesian3.negate(
|
||||
Cesium.Cartesian3.UNIT_X,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const up = Cesium.Cartesian3.UNIT_Z;
|
||||
const frustum = new Cesium.PerspectiveFrustum({
|
||||
fov: Cesium.Math.toRadians(60),
|
||||
aspectRatio: 16 / 9,
|
||||
near: 1,
|
||||
// Cesium's default far plane, as the app uses.
|
||||
far: 5e8,
|
||||
});
|
||||
|
||||
function visibility(position, direction, up) {
|
||||
const visiblePoints = createPointsVisibility(
|
||||
{ mode: Cesium.SceneMode.SCENE3D },
|
||||
{ positionWC: position, directionWC: direction, upWC: up, frustum },
|
||||
);
|
||||
return (points) => visiblePoints(points, 200);
|
||||
}
|
||||
|
||||
function directionTo(position, target) {
|
||||
return Cesium.Cartesian3.normalize(
|
||||
Cesium.Cartesian3.subtract(target, position, new Cesium.Cartesian3()),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
}
|
||||
|
||||
function assertInFrustum(points, position, direction) {
|
||||
const culling = frustum.computeCullingVolume(position, direction, up);
|
||||
assert.notEqual(
|
||||
culling.computeVisibility(Cesium.BoundingSphere.fromPoints(points)),
|
||||
Cesium.Intersect.OUTSIDE,
|
||||
);
|
||||
}
|
||||
|
||||
test('a plane in front of the camera is visible', () => {
|
||||
assert.equal(visibility(point(0, 0, 30000), down, up)([point(0, 0)]), true);
|
||||
});
|
||||
|
||||
test('a plane behind the camera is outside the frustum', () => {
|
||||
assert.equal(
|
||||
visibility(point(0, 0, 30000), Cesium.Cartesian3.UNIT_X, up)([point(0, 0)]),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('a corner can be in view when the mount and centre are outside', () => {
|
||||
const visible = visibility(point(0, 0, 30000), down, up);
|
||||
const mount = point(0.3, 0);
|
||||
const points = [
|
||||
mount,
|
||||
point(0.1, 0.0001),
|
||||
point(0.3, 0.0001),
|
||||
point(0.3, -0.0001),
|
||||
point(0.1, -0.0001),
|
||||
];
|
||||
assert.equal(visible(points), true);
|
||||
assert.equal(visible([mount]), false);
|
||||
assert.equal(visible([point(0.2, 0)]), false);
|
||||
});
|
||||
|
||||
test('a nearby plane below the ellipsoid is visible to low and high viewers', () => {
|
||||
const cap = point(0.00054, 0, -18);
|
||||
const points = [point(0, 0, -18), cap];
|
||||
for (const altitude of [4, 1200]) {
|
||||
const position = point(0.00135, 0, altitude);
|
||||
const direction = directionTo(position, cap);
|
||||
assertInFrustum(points, position, direction);
|
||||
assert.equal(visibility(position, direction, up)(points), true);
|
||||
}
|
||||
});
|
||||
|
||||
test('the horizon rejects a negative-height plane on the far side', () => {
|
||||
const mount = point(0, 0, -18);
|
||||
const points = [mount, point(0.00054, 0, -18)];
|
||||
for (const altitude of [4, 30000, 2e7]) {
|
||||
const position = point(180, 0, altitude);
|
||||
const direction = directionTo(position, mount);
|
||||
assertInFrustum(points, position, direction);
|
||||
assert.equal(visibility(position, direction, up)(points), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('a low viewer can see a plane beyond the WGS84 horizon', () => {
|
||||
const mount = point(0, 0, 1);
|
||||
const position = point(0.2, 0, 4);
|
||||
assert.equal(
|
||||
visibility(position, directionTo(position, mount), up)([mount]),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('deep viewers do not lose nearby planes to the horizon test', () => {
|
||||
const mount = point(0, 0, -350);
|
||||
const position = point(0.00135, 0, -300);
|
||||
assert.equal(
|
||||
visibility(position, directionTo(position, mount), up)([mount]),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('a non-finite camera direction leaves visibility unknown', () => {
|
||||
const visible = visibility(
|
||||
point(0, 0, 30000),
|
||||
new Cesium.Cartesian3(NaN, 0, 0),
|
||||
up,
|
||||
);
|
||||
assert.equal(visible([point(0, 0)]), null);
|
||||
});
|
||||
|
||||
test('setFov holds the vertical angle across resizes, and waits for a first one', () => {
|
||||
const { scene, camera } = headlessCamera();
|
||||
scene.postUpdate = new Cesium.Event();
|
||||
|
||||
@@ -321,6 +321,8 @@ test('the application’s Cesium renderer runs the controller around its preUpda
|
||||
const renderer = await plugin.create({ container: {} });
|
||||
assert.equal(scene.screenSpaceCameraController.enableInputs, false);
|
||||
assert.equal(typeof renderer.camera.native.setPose, 'function');
|
||||
assert.equal(renderer.capabilities.has('pointVisibility'), true);
|
||||
assert.equal(renderer.camera.visiblePoints([], 200), null);
|
||||
renderer.frame.on('preUpdate', () => order.push('preUpdate'));
|
||||
scene.preUpdate.raise(scene, Cesium.JulianDate.fromDate(new Date(5000)));
|
||||
assert.deepEqual(order, [['before', 5000], 'preUpdate', 'after']);
|
||||
|
||||
+672
-69
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,416 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import test, { after } from 'node:test';
|
||||
import { createCesiumDraw, lineAgeData } from './draw.js';
|
||||
|
||||
// Node has no WebGL context to report line-width limits.
|
||||
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
|
||||
Cesium.ContextLimits._maximumAliasedLineWidth = 10;
|
||||
|
||||
// A material's texture uniform is told from the browser's image classes, which
|
||||
// Node lacks.
|
||||
const IMAGE_CLASSES = [
|
||||
'HTMLCanvasElement',
|
||||
'HTMLImageElement',
|
||||
'ImageBitmap',
|
||||
'OffscreenCanvas',
|
||||
];
|
||||
const realClasses = IMAGE_CLASSES.map((name) => globalThis[name]);
|
||||
for (const name of IMAGE_CLASSES) globalThis[name] ??= class {};
|
||||
after(() =>
|
||||
IMAGE_CLASSES.forEach((name, i) => (globalThis[name] = realClasses[i])),
|
||||
);
|
||||
|
||||
/** A scene with what a line set touches: primitives, its events and its time. */
|
||||
function fakeScene(ms = Date.UTC(2026, 0, 1)) {
|
||||
const added = [];
|
||||
return {
|
||||
added,
|
||||
postRender: new Cesium.Event(),
|
||||
preRender: new Cesium.Event(),
|
||||
camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) },
|
||||
frameState: {
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
time: Cesium.JulianDate.fromDate(new Date(ms)),
|
||||
},
|
||||
updateHeight: () => () => {},
|
||||
getHeight: () => undefined,
|
||||
primitives: {
|
||||
add: (primitive) => (added.push(primitive), primitive),
|
||||
remove: (primitive) => {
|
||||
const at = added.indexOf(primitive);
|
||||
if (at >= 0) added.splice(at, 1);
|
||||
return at >= 0;
|
||||
},
|
||||
length: 0,
|
||||
},
|
||||
requestRender() {},
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
}
|
||||
|
||||
const T0 = Date.UTC(2026, 0, 1);
|
||||
|
||||
/** A port that fades lines with age, over `scene`, and its frames at a scene time. */
|
||||
function agedDraw(scene = fakeScene(), capabilities = ['lineAgeFade']) {
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: (error) => assert.fail(error),
|
||||
capabilities: new Set(capabilities),
|
||||
});
|
||||
return {
|
||||
part,
|
||||
scene,
|
||||
frameAt(ms) {
|
||||
scene.frameState.time = Cesium.JulianDate.fromDate(new Date(ms));
|
||||
part.beforeRender();
|
||||
part.afterRender();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const along = (n, lat = 10) =>
|
||||
Array.from({ length: n }, (_, i) =>
|
||||
Cesium.Cartesian3.fromDegrees(i * 0.01, lat, 100),
|
||||
);
|
||||
|
||||
const trail = (positions, times, extra = {}) => ({
|
||||
id: 'trail',
|
||||
positions,
|
||||
widthPx: 3,
|
||||
mode: '3d',
|
||||
style: { kind: 'solid', color: [0.2, 0.8, 1, 0.9] },
|
||||
ageFade: { times, windowMs: 60_000, alphaFloor: 0.06, ...extra },
|
||||
pickable: false,
|
||||
});
|
||||
|
||||
/** The polylines a line set's host draws in its collection. */
|
||||
function collectionOf(scene) {
|
||||
const host = scene.added.at(-1);
|
||||
if (host instanceof Cesium.PolylineCollection) return host;
|
||||
for (let i = 0; i < host.length; i++)
|
||||
if (host.get(i) instanceof Cesium.PolylineCollection) return host.get(i);
|
||||
return null;
|
||||
}
|
||||
|
||||
test('a polyline’s age texels: a point at the place of the one before it is dropped, the rest even along it, times in seconds before the newest', () => {
|
||||
const [a, b, c] = along(3);
|
||||
const age = lineAgeData([a, a, b, c], [T0, T0 + 1000, T0 + 2000, T0 + 4000], {
|
||||
times: [],
|
||||
windowMs: 30_000,
|
||||
alphaFloor: 0.06,
|
||||
squaredAlphaFloor: 0.14,
|
||||
});
|
||||
assert.equal(age.count, 3);
|
||||
assert.equal(age.base, T0 + 4000);
|
||||
const texel = (i) => [age.data[i * 4], age.data[i * 4 + 1]];
|
||||
assert.deepEqual(texel(0), [0, -4]);
|
||||
assert.deepEqual(texel(1), [0.5, -2]);
|
||||
assert.deepEqual(texel(2), [1, 0]);
|
||||
assert.deepEqual(age.uniforms, {
|
||||
ageCount: 3,
|
||||
ageWidth: 3,
|
||||
ageRows: 1,
|
||||
ageByLength: 0,
|
||||
ageWindow: 30,
|
||||
ageAlphaFloor: 0.06,
|
||||
ageSquaredFloor: 0.14,
|
||||
ageWidthFloor: 1,
|
||||
ageShow: 0,
|
||||
});
|
||||
});
|
||||
|
||||
test('a windowed line’s age texels carry its span, in seconds; an endless one cuts at now alone', () => {
|
||||
const points = along(2);
|
||||
const fade = (showMs) => ({
|
||||
times: [],
|
||||
windowMs: 30_000,
|
||||
alphaFloor: 0.06,
|
||||
showMs,
|
||||
});
|
||||
const at = (showMs, windowed = true) =>
|
||||
lineAgeData(points, [T0, T0 + 1000], fade(showMs), false, windowed).uniforms
|
||||
.ageShow;
|
||||
assert.equal(at(45_000), 45);
|
||||
assert.equal(at(Infinity), -1);
|
||||
assert.equal(at(undefined), 0, 'no span, no cut');
|
||||
assert.equal(at(45_000, false), 0, 'not cut where the port does not');
|
||||
});
|
||||
|
||||
test('a draped line’s age texels lie along it by distance, and a long line takes more rows', () => {
|
||||
const points = [
|
||||
Cesium.Cartesian3.fromDegrees(0, 0),
|
||||
Cesium.Cartesian3.fromDegrees(1, 0),
|
||||
Cesium.Cartesian3.fromDegrees(4, 0),
|
||||
];
|
||||
const age = lineAgeData(
|
||||
points,
|
||||
[0, 1000, 2000],
|
||||
{ times: [], windowMs: 1, alphaFloor: 0 },
|
||||
true,
|
||||
);
|
||||
assert.equal(age.uniforms.ageByLength, 1);
|
||||
assert.equal(age.data[0], 0);
|
||||
assert.ok(
|
||||
Math.abs(age.data[4] - 0.25) < 1e-6,
|
||||
`a quarter along (${age.data[4]})`,
|
||||
);
|
||||
assert.equal(age.data[8], 1);
|
||||
const long = along(2500);
|
||||
const many = lineAgeData(
|
||||
long,
|
||||
long.map((_, i) => i),
|
||||
{ times: [], windowMs: 1, alphaFloor: 0 },
|
||||
);
|
||||
assert.equal(many.width, 1024);
|
||||
assert.equal(many.rows, 3);
|
||||
assert.equal(many.data.length, 1024 * 3 * 4);
|
||||
});
|
||||
|
||||
test('an aged line fades on the scene clock: time passing changes its material, never its line', () => {
|
||||
const { part, scene, frameAt } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const positions = along(4);
|
||||
const times = [T0 - 30_000, T0 - 20_000, T0 - 10_000, T0];
|
||||
set.set([
|
||||
trail(positions, times, { squaredAlphaFloor: 0.14, widthFloor: 0.3 }),
|
||||
]);
|
||||
const polylines = collectionOf(scene);
|
||||
const polyline = polylines.get(0);
|
||||
const material = polyline.material;
|
||||
assert.equal(material.type, 'DrawAgedLine_solid');
|
||||
assert.ok(material.isTranslucent(), 'drawn in the translucent pass');
|
||||
assert.equal(material.uniforms.ageWindow, 60);
|
||||
assert.equal(material.uniforms.ageAlphaFloor, 0.06);
|
||||
assert.equal(material.uniforms.ageSquaredFloor, 0.14);
|
||||
assert.equal(material.uniforms.ageWidthFloor, 0.3);
|
||||
assert.equal(material.uniforms.ageCount, 4);
|
||||
assert.ok(
|
||||
Cesium.Color.equals(
|
||||
material.materials.aged.uniforms.color,
|
||||
new Cesium.Color(0.2, 0.8, 1, 0.9),
|
||||
),
|
||||
'its style’s colour inside',
|
||||
);
|
||||
for (let k = 1; k <= 120; k++) {
|
||||
frameAt(T0 + k * 1000);
|
||||
assert.equal(
|
||||
material.uniforms.ageNow,
|
||||
k,
|
||||
`seconds after its newest point, frame ${k}`,
|
||||
);
|
||||
}
|
||||
assert.equal(collectionOf(scene), polylines, 'the same collection');
|
||||
assert.equal(polylines.length, 1);
|
||||
assert.equal(polylines.get(0), polyline, 'the same line');
|
||||
assert.equal(polyline.material, material, 'the same material');
|
||||
});
|
||||
|
||||
test('an aged line given new points and times moves in place and takes the new times', () => {
|
||||
const { part, scene, frameAt } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const positions = along(5);
|
||||
const times = [0, 1, 2, 3, 4].map((i) => T0 + i * 10_000);
|
||||
set.set([trail(positions.slice(0, 4), times.slice(0, 4))]);
|
||||
const polyline = collectionOf(scene).get(0);
|
||||
const material = polyline.material;
|
||||
frameAt(T0 + 40_000);
|
||||
assert.equal(material.uniforms.ageNow, 10);
|
||||
set.upsert([trail(positions.slice(1), times.slice(1))]);
|
||||
assert.equal(collectionOf(scene).get(0), polyline, 'moved in place');
|
||||
assert.equal(polyline.material, material);
|
||||
frameAt(T0 + 45_000);
|
||||
assert.equal(material.uniforms.ageNow, 5, 'from its new newest point');
|
||||
assert.ok(Cesium.Cartesian3.equals(polyline.positions[0], positions[1]));
|
||||
// A new colour is taken in place too, inside the fade.
|
||||
set.upsert([
|
||||
{
|
||||
...trail(positions.slice(1), times.slice(1)),
|
||||
style: { kind: 'solid', color: '#ff0000' },
|
||||
},
|
||||
]);
|
||||
assert.equal(collectionOf(scene).get(0), polyline, 'recoloured in place');
|
||||
assert.ok(
|
||||
Cesium.Color.equals(
|
||||
material.materials.aged.uniforms.color,
|
||||
Cesium.Color.RED,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('segment colours fade with age too, each segment with its own two times', () => {
|
||||
const { part, scene, frameAt } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const times = [T0, T0 + 1000, T0 + 2000];
|
||||
set.set([
|
||||
{
|
||||
...trail(along(3), times),
|
||||
segmentColors: ['#ff0000', '#00ff00'],
|
||||
},
|
||||
]);
|
||||
const pieces = [];
|
||||
const visit = (primitive) => {
|
||||
if (primitive instanceof Cesium.Primitive) pieces.push(primitive);
|
||||
else if (primitive?.length !== undefined && primitive.get)
|
||||
for (let i = 0; i < primitive.length; i++) visit(primitive.get(i));
|
||||
};
|
||||
visit(scene.added.at(-1));
|
||||
assert.equal(pieces.length, 2);
|
||||
frameAt(T0 + 3000);
|
||||
const [first, second] = pieces.map((piece) => piece.appearance.material);
|
||||
assert.equal(first.type, 'DrawAgedLine_solid');
|
||||
assert.equal(
|
||||
first.uniforms.ageNow,
|
||||
2,
|
||||
'its newer point a second after the first',
|
||||
);
|
||||
assert.equal(second.uniforms.ageNow, 1);
|
||||
assert.ok(
|
||||
Cesium.Color.equals(first.materials.aged.uniforms.color, Cesium.Color.RED),
|
||||
);
|
||||
assert.ok(
|
||||
Cesium.Color.equals(
|
||||
second.materials.aged.uniforms.color,
|
||||
Cesium.Color.LIME,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('a draped aged line draws by a ground primitive of its own, its times along its length', () => {
|
||||
const { part, scene } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const ground = [0, 1, 2].map((i) =>
|
||||
Cesium.Cartesian3.fromDegrees(i * 0.01, 10),
|
||||
);
|
||||
set.set([{ ...trail(ground, [T0, T0 + 1, T0 + 2]), mode: 'draped' }]);
|
||||
const host = scene.added.at(-1);
|
||||
const primitives = [];
|
||||
const visit = (primitive) => {
|
||||
if (primitive instanceof Cesium.GroundPolylinePrimitive)
|
||||
primitives.push(primitive);
|
||||
else if (primitive?.length !== undefined && primitive.get)
|
||||
for (let i = 0; i < primitive.length; i++) visit(primitive.get(i));
|
||||
};
|
||||
visit(host);
|
||||
assert.equal(primitives.length, 1);
|
||||
const material = primitives[0].appearance.material;
|
||||
assert.equal(material.type, 'DrawAgedLine_solid');
|
||||
assert.equal(material.uniforms.ageByLength, 1);
|
||||
});
|
||||
|
||||
test('an aged line built anew lets its old material go once its primitive is gone', () => {
|
||||
const { part, scene, frameAt } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
const deep = (times) => ({
|
||||
...trail(along(3), times),
|
||||
depthFail: { kind: 'solid', color: '#ffffff' },
|
||||
});
|
||||
set.set([deep([T0, T0 + 1, T0 + 2])]);
|
||||
const record = part.sets.get('trails');
|
||||
assert.equal(record.ages.size, 2, 'its line and the part behind the surface');
|
||||
const [old] = record.ages.keys();
|
||||
set.upsert([deep([T0 + 1, T0 + 2, T0 + 3])]);
|
||||
frameAt(T0 + 10);
|
||||
assert.ok(old.isDestroyed(), 'the old material went with its primitive');
|
||||
assert.equal(record.ages.size, 2);
|
||||
void scene;
|
||||
});
|
||||
|
||||
test('a windowed line is cut on the scene clock: time passing changes its material, never its line', () => {
|
||||
const { part, scene, frameAt } = agedDraw(fakeScene(), [
|
||||
'lineAgeFade',
|
||||
'lineTimeWindow',
|
||||
]);
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
// A whole track, an hour of it, shown over its last minute.
|
||||
const positions = along(61);
|
||||
const times = positions.map((_, i) => T0 + i * 60_000);
|
||||
set.set([trail(positions, times, { alphaFloor: 1, showMs: 60_000 })]);
|
||||
const polylines = collectionOf(scene);
|
||||
const polyline = polylines.get(0);
|
||||
const material = polyline.material;
|
||||
assert.equal(material.type, 'DrawAgedLine_solid');
|
||||
assert.equal(material.uniforms.ageShow, 60);
|
||||
assert.equal(material.uniforms.ageCount, 61);
|
||||
const before = polyline.positions;
|
||||
for (let k = 1; k <= 120; k++) {
|
||||
frameAt(T0 + k * 30_000);
|
||||
assert.equal(
|
||||
material.uniforms.ageNow,
|
||||
(k * 30_000 - 3_600_000) / 1000,
|
||||
`seconds after its newest point, frame ${k}`,
|
||||
);
|
||||
}
|
||||
assert.equal(collectionOf(scene), polylines, 'the same collection');
|
||||
assert.equal(polylines.get(0), polyline, 'the same line');
|
||||
assert.equal(polyline.material, material, 'the same material');
|
||||
assert.equal(polyline.positions, before, 'its points untouched');
|
||||
// A new span is a new look: drawn anew, with it.
|
||||
set.upsert([trail(positions, times, { alphaFloor: 1, showMs: 120_000 })]);
|
||||
assert.equal(collectionOf(scene).get(0).material.uniforms.ageShow, 120);
|
||||
});
|
||||
|
||||
test('without the window’s capability a line ignores its span and draws whole', () => {
|
||||
const { part, scene } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
set.set([trail(along(3), [T0, T0 + 1, T0 + 2], { showMs: 60_000 })]);
|
||||
const material = collectionOf(scene).get(0).material;
|
||||
assert.equal(material.type, 'DrawAgedLine_solid', 'still faded');
|
||||
assert.equal(material.uniforms.ageShow, 0, 'never cut');
|
||||
});
|
||||
|
||||
test('without the capability a line ignores its age fade; with it a bad fade is refused', () => {
|
||||
const plain = agedDraw(fakeScene(), []);
|
||||
const lines = plain.part.port.lines({ id: 'trails' });
|
||||
lines.set([trail(along(3), [T0])]);
|
||||
const material = collectionOf(plain.scene).get(0).material;
|
||||
assert.equal(material.type, 'Color', 'drawn as its style alone');
|
||||
|
||||
const { part } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
assert.throws(
|
||||
() => set.set([trail(along(3), [T0, T0])]),
|
||||
TypeError,
|
||||
'one time a position',
|
||||
);
|
||||
assert.throws(
|
||||
() => set.set([trail(along(2), [T0, T0], { windowMs: 0 })]),
|
||||
TypeError,
|
||||
'a positive window',
|
||||
);
|
||||
assert.throws(
|
||||
() => set.set([trail(along(2), [T0, T0], { widthFloor: 2 })]),
|
||||
TypeError,
|
||||
'floors from 0 to 1',
|
||||
);
|
||||
for (const showMs of [0, -1, Number.NaN])
|
||||
assert.throws(
|
||||
() => set.set([trail(along(2), [T0, T0], { showMs })]),
|
||||
TypeError,
|
||||
'a positive span',
|
||||
);
|
||||
assert.equal(set.size(), 0, 'nothing changed');
|
||||
});
|
||||
|
||||
test('an aged line made first leaves its style’s type named as a plain material of it is', () => {
|
||||
const lists = Cesium.Material._uniformList;
|
||||
const was = lists.Color;
|
||||
delete lists.Color;
|
||||
try {
|
||||
const { part, scene } = agedDraw();
|
||||
const set = part.port.lines({ id: 'trails' });
|
||||
set.set([trail(along(2), [T0, T0 + 1])]);
|
||||
assert.deepEqual(lists.Color, ['color_0'], 'as a plain Color material');
|
||||
// A plain line beside it then draws with it in its collection.
|
||||
set.upsert([
|
||||
{ ...trail(along(2), [T0, T0 + 1]), id: 'plain', ageFade: undefined },
|
||||
]);
|
||||
const plain = collectionOf(scene).get(1).material;
|
||||
assert.equal(plain.type, 'Color');
|
||||
assert.ok(
|
||||
lists.Color.every((name) => typeof plain._uniforms[name] === 'function'),
|
||||
);
|
||||
} finally {
|
||||
if (was) lists.Color = was;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,375 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import test, { after } from 'node:test';
|
||||
import { createCesiumDraw } from './draw.js';
|
||||
|
||||
// Node has no WebGL context to report line-width limits.
|
||||
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
|
||||
Cesium.ContextLimits._maximumAliasedLineWidth = 10;
|
||||
|
||||
// A material's texture uniform is told from the browser's image classes, which
|
||||
// Node lacks.
|
||||
const IMAGE_CLASSES = [
|
||||
'HTMLCanvasElement',
|
||||
'HTMLImageElement',
|
||||
'ImageBitmap',
|
||||
'OffscreenCanvas',
|
||||
];
|
||||
const realClasses = IMAGE_CLASSES.map((name) => globalThis[name]);
|
||||
for (const name of IMAGE_CLASSES) globalThis[name] ??= class {};
|
||||
after(() =>
|
||||
IMAGE_CLASSES.forEach((name, i) => (globalThis[name] = realClasses[i])),
|
||||
);
|
||||
|
||||
/** A scene with what a line set touches: primitives, its events and its time. */
|
||||
function fakeScene(ms = Date.UTC(2026, 0, 1)) {
|
||||
const added = [];
|
||||
return {
|
||||
added,
|
||||
postRender: new Cesium.Event(),
|
||||
preRender: new Cesium.Event(),
|
||||
camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) },
|
||||
frameState: {
|
||||
mode: Cesium.SceneMode.SCENE3D,
|
||||
time: Cesium.JulianDate.fromDate(new Date(ms)),
|
||||
},
|
||||
updateHeight: () => () => {},
|
||||
getHeight: () => undefined,
|
||||
primitives: {
|
||||
add: (primitive) => (added.push(primitive), primitive),
|
||||
remove: (primitive) => {
|
||||
const at = added.indexOf(primitive);
|
||||
if (at >= 0) added.splice(at, 1);
|
||||
return at >= 0;
|
||||
},
|
||||
length: 0,
|
||||
},
|
||||
requestRender() {},
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
}
|
||||
|
||||
const T0 = Date.UTC(2026, 0, 1);
|
||||
|
||||
/** A port over a fake scene that draws lines in runs (and with `more`). */
|
||||
function brokenDraw(capabilities = ['lineBreaks'], scene = fakeScene()) {
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: (error) => assert.fail(error),
|
||||
capabilities: new Set(capabilities),
|
||||
});
|
||||
return { part, scene, set: part.port.lines({ id: 'trails' }) };
|
||||
}
|
||||
|
||||
/** Six positions west to east, `height` up. */
|
||||
const along = (n = 6, height = 100) =>
|
||||
Array.from({ length: n }, (_, i) =>
|
||||
Cesium.Cartesian3.fromDegrees(i * 0.01, 10, height),
|
||||
);
|
||||
|
||||
/** Three runs: positions 0-1, 2-4 and 5 alone (which draws nothing). */
|
||||
const trails = (extra = {}) => ({
|
||||
id: 'trails',
|
||||
positions: along(),
|
||||
breaks: [2, 5],
|
||||
widthPx: 3,
|
||||
mode: '3d',
|
||||
style: { kind: 'solid', color: [0.2, 0.8, 1, 0.9] },
|
||||
...extra,
|
||||
});
|
||||
|
||||
/** Everything a set's host holds, collections opened. */
|
||||
function everything(scene) {
|
||||
const all = [];
|
||||
const walk = (p) => {
|
||||
all.push(p);
|
||||
if (p instanceof Cesium.PrimitiveCollection)
|
||||
for (let i = 0; i < p.length; i++) walk(p.get(i));
|
||||
};
|
||||
for (const p of scene.added) walk(p);
|
||||
return all;
|
||||
}
|
||||
|
||||
/** The polylines a set's collection draws. */
|
||||
function polylinesOf(scene) {
|
||||
const collection = everything(scene).find(
|
||||
(p) => p instanceof Cesium.PolylineCollection,
|
||||
);
|
||||
const lines = [];
|
||||
for (let i = 0; i < collection.length; i++) lines.push(collection.get(i));
|
||||
return lines;
|
||||
}
|
||||
|
||||
const lonOf = (p) =>
|
||||
Number(
|
||||
Cesium.Math.toDegrees(
|
||||
Cesium.Cartographic.fromCartesian(p).longitude,
|
||||
).toFixed(6),
|
||||
);
|
||||
|
||||
test('an undraped line in runs is a polyline a run in its collection, each picked as the line', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
set.set([trails()]);
|
||||
const lines = polylinesOf(scene);
|
||||
assert.equal(lines.length, 2, 'a polyline a run with length');
|
||||
assert.deepEqual(
|
||||
lines.map((line) => line.positions.map(lonOf)),
|
||||
[
|
||||
[0, 0.01],
|
||||
[0.02, 0.03, 0.04],
|
||||
],
|
||||
'nothing from position 1 to 2, nor 4 to 5',
|
||||
);
|
||||
assert.deepEqual(
|
||||
lines.map((line) => line.id.id),
|
||||
['trails', 'trails'],
|
||||
'each run picks as its line',
|
||||
);
|
||||
assert.notEqual(lines[0].id, lines[1].id, 'under a pick id of its own');
|
||||
assert.equal(set.size(), 1, 'one item');
|
||||
});
|
||||
|
||||
test('a line in runs takes packed positions and breaks', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
const flat = new Float64Array(along().flatMap((p) => [p.x, p.y, p.z]));
|
||||
set.set([trails({ positions: flat, breaks: new Uint32Array([3]) })]);
|
||||
assert.deepEqual(
|
||||
polylinesOf(scene).map((line) => line.positions.length),
|
||||
[3, 3],
|
||||
);
|
||||
});
|
||||
|
||||
test('an arrow in runs has a head at the end of each run', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
set.set([trails({ style: { kind: 'arrow', color: '#ffffff' } })]);
|
||||
assert.deepEqual(
|
||||
polylinesOf(scene).map((line) => line.material.type),
|
||||
['PolylineArrow', 'PolylineArrow'],
|
||||
);
|
||||
});
|
||||
|
||||
test('segment colours and shows stay a pair of positions; the pairs across a break draw nothing', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
const red = [1, 0, 0, 1];
|
||||
const green = [0, 1, 0, 1];
|
||||
const blue = [0, 0, 1, 1];
|
||||
const line = (colors, shows) =>
|
||||
trails({
|
||||
style: { kind: 'glow', color: '#ffffff', power: 0.2 },
|
||||
segmentColors: colors,
|
||||
segmentShow: shows,
|
||||
});
|
||||
set.set([
|
||||
line([red, blue, green, green, blue], [true, true, true, false, true]),
|
||||
]);
|
||||
const host = scene.added[0];
|
||||
// In the set's collection, a polyline a segment.
|
||||
const pieces = polylinesOf(scene);
|
||||
assert.equal(pieces.length, 3, 'segments 0, 2 and 3; not 1 nor 4');
|
||||
assert.equal(pieces[0].material.type, 'PolylineGlow');
|
||||
const color = (p) => p.material.uniforms.color;
|
||||
assert.deepEqual(
|
||||
pieces.map((p) => [color(p).red, color(p).green, color(p).blue, p.show]),
|
||||
[
|
||||
[1, 0, 0, true],
|
||||
[0, 1, 0, true],
|
||||
[0, 1, 0, false],
|
||||
],
|
||||
);
|
||||
set.upsert([
|
||||
line([green, red, red, blue, red], [true, false, true, true, true]),
|
||||
]);
|
||||
assert.equal(scene.added[0], host, 'recoloured and shown in place');
|
||||
assert.deepEqual(
|
||||
pieces.map((p) => [color(p).red, color(p).green, color(p).blue, p.show]),
|
||||
[
|
||||
[0, 1, 0, true],
|
||||
[1, 0, 0, true],
|
||||
[0, 0, 1, true],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('a run of a line that fades with age takes its own points’ times', () => {
|
||||
const { scene, set } = brokenDraw(['lineAgeFade', 'lineBreaks']);
|
||||
const times = along().map((_, i) => T0 + i * 1000);
|
||||
set.set([trails({ ageFade: { times, windowMs: 60_000, alphaFloor: 0.1 } })]);
|
||||
const lines = polylinesOf(scene);
|
||||
assert.deepEqual(
|
||||
lines.map((line) => [line.material.type, line.material.uniforms.ageCount]),
|
||||
[
|
||||
['DrawAgedLine_solid', 2],
|
||||
['DrawAgedLine_solid', 3],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('a revealed line in runs reveals them in order, along their own length', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
// Runs of one leg and of two, all of one length, the gap between them
|
||||
// (positions 1 to 2) none: half their length is all of the first run
|
||||
// and a quarter of the second.
|
||||
set.set([trails({ positions: along(5), breaks: [2], revealFraction: 0.5 })]);
|
||||
let lines = polylinesOf(scene);
|
||||
const revealOf = (line) => line.material.materials?.revealed;
|
||||
assert.equal(revealOf(lines[0]), undefined, 'the first run all shown');
|
||||
assert.equal(lines[0].show, true);
|
||||
const second = lines[1];
|
||||
assert.ok(revealOf(second), 'the second run revealed');
|
||||
// Half its first leg, of two.
|
||||
assert.ok(
|
||||
Math.abs(second.material.uniforms.reveal - 0.25) < 1e-9,
|
||||
`revealed a quarter along (${second.material.uniforms.reveal})`,
|
||||
);
|
||||
set.set([trails({ positions: along(5), breaks: [2], revealFraction: 0.25 })]);
|
||||
lines = polylinesOf(scene);
|
||||
assert.equal(lines[1].show, false, 'a run not yet reached is hidden');
|
||||
});
|
||||
|
||||
test('a draped line in runs drapes a ground piece a run; a solid segmented one a ground instance a segment, none across a break', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
set.set([trails({ mode: 'draped', positions: along(6, 0) })]);
|
||||
const ground = everything(scene).filter(
|
||||
(p) => p instanceof Cesium.GroundPolylinePrimitive,
|
||||
);
|
||||
assert.equal(ground.length, 2, 'a ground piece a run with length');
|
||||
assert.deepEqual(
|
||||
ground.map((p) => p.geometryInstances[0].geometry._positions.length),
|
||||
[2, 3],
|
||||
);
|
||||
set.set([
|
||||
trails({
|
||||
mode: 'draped',
|
||||
positions: along(6, 0),
|
||||
segmentColors: along()
|
||||
.slice(1)
|
||||
.map(() => [0, 1, 0, 1]),
|
||||
}),
|
||||
]);
|
||||
const batch = everything(scene).filter(
|
||||
(p) => p instanceof Cesium.GroundPolylinePrimitive,
|
||||
);
|
||||
assert.equal(batch.length, 1, 'one batch');
|
||||
assert.equal(
|
||||
batch[0].geometryInstances.length,
|
||||
3,
|
||||
'segments 0, 2 and 3: not 1 nor 4',
|
||||
);
|
||||
});
|
||||
|
||||
test('changed breaks draw the line anew; the same ones change it in place', () => {
|
||||
const { scene, set } = brokenDraw();
|
||||
set.set([trails()]);
|
||||
const host = scene.added[0];
|
||||
set.upsert([trails({ show: false })]);
|
||||
assert.equal(scene.added[0], host, 'shown in place');
|
||||
assert.deepEqual(
|
||||
polylinesOf(scene).map((line) => line.show),
|
||||
[false, false],
|
||||
);
|
||||
set.upsert([trails({ breaks: [3] })]);
|
||||
assert.notEqual(scene.added[0], host, 'built anew');
|
||||
assert.deepEqual(
|
||||
polylinesOf(scene).map((line) => line.positions.length),
|
||||
[3, 3],
|
||||
);
|
||||
});
|
||||
|
||||
test('without the capability a line ignores its breaks; with it bad breaks are refused', () => {
|
||||
const plain = brokenDraw([]);
|
||||
plain.set.set([trails()]);
|
||||
assert.equal(polylinesOf(plain.scene).length, 1, 'one line, joined');
|
||||
|
||||
const { set } = brokenDraw();
|
||||
for (const breaks of [[0], [6], [3, 2], [2, 2], [1.5], ['2']])
|
||||
assert.throws(
|
||||
() => set.set([trails({ breaks })]),
|
||||
TypeError,
|
||||
`refused: ${JSON.stringify(breaks)}`,
|
||||
);
|
||||
assert.equal(set.size(), 0, 'nothing changed');
|
||||
set.set([trails({ breaks: [] })]);
|
||||
assert.equal(set.size(), 1, 'no breaks: one run');
|
||||
});
|
||||
|
||||
test('where the scene cannot drape, a draped line in runs draws a run over the surface each, hidden past the horizon', () => {
|
||||
const scene = fakeScene();
|
||||
scene.frameState.context = { depthTexture: false };
|
||||
const { part, set } = brokenDraw(['lineBreaks'], scene);
|
||||
const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 0);
|
||||
set.set([
|
||||
trails({
|
||||
mode: 'draped',
|
||||
positions: [at(0), at(0.01), at(0.02), at(0.03)],
|
||||
breaks: [2],
|
||||
// The overlay draws its shown segments only, from first to last.
|
||||
segmentShow: [false, true, true],
|
||||
}),
|
||||
trails({
|
||||
id: 'two',
|
||||
mode: 'draped',
|
||||
positions: [at(0), at(0.01), at(0.02), at(0.03)],
|
||||
breaks: [2],
|
||||
}),
|
||||
]);
|
||||
const frame = () => {
|
||||
part.beforeRender();
|
||||
part.afterRender();
|
||||
};
|
||||
const runs = everything(scene).filter(
|
||||
(p) => p instanceof Cesium.Primitive && p.depthFailAppearance,
|
||||
);
|
||||
// The first line kept positions 1 to 3, its break at 1 of them: a run of
|
||||
// one position and one of two; the second two runs of two.
|
||||
assert.equal(runs.length, 3, 'a primitive a run with length');
|
||||
scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0);
|
||||
frame();
|
||||
assert.deepEqual(
|
||||
runs.map((p) => p.show),
|
||||
[true, true, true],
|
||||
);
|
||||
scene.camera.positionWC = new Cesium.Cartesian3(-2e7, 0, 0);
|
||||
frame();
|
||||
assert.deepEqual(
|
||||
runs.map((p) => p.show),
|
||||
[false, false, false],
|
||||
'past the horizon',
|
||||
);
|
||||
});
|
||||
|
||||
test('a draped line in runs whose first run is later than its second times each run by its own points', () => {
|
||||
const { scene, set } = brokenDraw([
|
||||
'lineAgeFade',
|
||||
'lineTimeWindow',
|
||||
'lineBreaks',
|
||||
]);
|
||||
set.set([
|
||||
trails({
|
||||
mode: 'draped',
|
||||
positions: along(4, 0),
|
||||
breaks: [2],
|
||||
ageFade: {
|
||||
times: [T0 + 110_000, T0 + 120_000, T0, T0 + 10_000],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 1,
|
||||
showMs: 30_000,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const ground = everything(scene).filter(
|
||||
(p) => p instanceof Cesium.GroundPolylinePrimitive,
|
||||
);
|
||||
assert.equal(ground.length, 2, 'a ground piece a run');
|
||||
const ages = ground.map((p) => p.appearance.material.uniforms);
|
||||
assert.deepEqual(
|
||||
ages.map((u) => [u.ageCount, u.ageByLength, u.ageShow]),
|
||||
[
|
||||
[2, 1, 30],
|
||||
[2, 1, 30],
|
||||
],
|
||||
'its own two points each, along its length, cut to the span',
|
||||
);
|
||||
// Each run's clock reads from its own newest point: the first's is
|
||||
// 110 s later than the second's.
|
||||
assert.equal(ages[1].ageNow - ages[0].ageNow, 110);
|
||||
});
|
||||
@@ -72,6 +72,10 @@ export const CESIUM_CHECKS = new Set([
|
||||
'draw.lines.drape',
|
||||
'draw.lines.split',
|
||||
'draw.lines.outlineDraped',
|
||||
'draw.lines.ageFade',
|
||||
'draw.lines.timeWindow',
|
||||
'draw.lines.breaks',
|
||||
'draw.lines.breaks.timeWindow',
|
||||
'draw.lines.segments',
|
||||
'draw.lines.segmentStyles',
|
||||
'draw.sets.blend',
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
* absent, never stubbed.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { createCesiumCamera } from './camera.js';
|
||||
import { createCesiumCamera, createPointsVisibility } from './camera.js';
|
||||
import { createControlledCamera } from './controlledCamera.js';
|
||||
import { listenerList, toCartesian, uncaught } from './common.js';
|
||||
import { createCesiumCredits } from './credits.js';
|
||||
@@ -83,7 +83,16 @@ export function cesiumCapabilities(scene, only) {
|
||||
'meshes',
|
||||
// Raster shells; other field kinds are refused.
|
||||
'fields',
|
||||
// Lines faded with age in their material, from a floating-point
|
||||
// texture of their points' times (`draw.js`).
|
||||
// And cut by time there, within a span of the scene clock.
|
||||
...(scene?.context?.floatingPointTexture
|
||||
? ['lineAgeFade', 'lineTimeWindow']
|
||||
: []),
|
||||
// Lines in runs, a piece a run (`draw.js`).
|
||||
'lineBreaks',
|
||||
'followFrame',
|
||||
'pointVisibility',
|
||||
// Cesium's AUTODETECT tracking frame (`follow.js`).
|
||||
'followAutodetect',
|
||||
'cameraChangeThreshold',
|
||||
@@ -488,6 +497,8 @@ export function createCesiumPorts(
|
||||
: {}),
|
||||
});
|
||||
const cameraPort = cameraPart.port;
|
||||
if (capabilities.has('pointVisibility'))
|
||||
cameraPort.visiblePoints = createPointsVisibility(scene, camera);
|
||||
measureCameraChanged = cameraPart.measureChanged ?? null;
|
||||
const effectsPart = createCesiumEffects(scene, {
|
||||
capabilities,
|
||||
|
||||
@@ -12,6 +12,7 @@ import { createNativeClick } from './nativeClick.js';
|
||||
test('capabilities follow what the scene supports', () => {
|
||||
const effects = [
|
||||
'followFrame',
|
||||
'pointVisibility',
|
||||
'followAutodetect',
|
||||
'cameraChangeThreshold',
|
||||
'columns',
|
||||
@@ -42,6 +43,7 @@ test('capabilities follow what the scene supports', () => {
|
||||
'quads',
|
||||
'meshes',
|
||||
'fields',
|
||||
'lineBreaks',
|
||||
];
|
||||
assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]);
|
||||
// A scene with a globe reads its visibility back.
|
||||
|
||||
@@ -3453,6 +3453,379 @@ export function portChecks() {
|
||||
}
|
||||
},
|
||||
),
|
||||
check(
|
||||
'draw.lines.ageFade',
|
||||
'a line, draped or not, fades with the age of its points as scene time moves on, without being sent again',
|
||||
async (h, r) => {
|
||||
if (h.pixels === false)
|
||||
return { skip: 'this harness reads no drawn pixels' };
|
||||
await overAustin(h, r);
|
||||
const t0 = Date.UTC(2026, 0, 1, 18);
|
||||
r.frame.setTime(t0);
|
||||
// Off the row under the camera, where a ground line can leave a gap.
|
||||
const at = (dLon, dLat, height) =>
|
||||
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
|
||||
const lines = r.draw.lines({ id: 'conf:line-age-fade' });
|
||||
const line = (id, dLat, mode) => ({
|
||||
id,
|
||||
positions: [
|
||||
at(-0.004, dLat, mode === 'draped' ? 0 : 20),
|
||||
at(0.004, dLat, mode === 'draped' ? 0 : 20),
|
||||
],
|
||||
widthPx: 16,
|
||||
mode,
|
||||
style: { kind: 'solid', color: [0, 1, 0, 1] },
|
||||
// Its west end a minute old at t0, its east end new.
|
||||
ageFade: {
|
||||
times: [t0 - 60_000, t0],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 0,
|
||||
},
|
||||
});
|
||||
// Unfaded but narrowed to a quarter of its width where it is old.
|
||||
const narrowed = {
|
||||
...line('narrowed', 0.0035, '3d'),
|
||||
ageFade: {
|
||||
times: [t0 - 60_000, t0],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 1,
|
||||
widthFloor: 0.25,
|
||||
},
|
||||
};
|
||||
lines.set([
|
||||
line('air', 0.002, '3d'),
|
||||
line('ground', -0.002, 'draped'),
|
||||
narrowed,
|
||||
]);
|
||||
// Whether the line at `dLon` is drawn green there, strongly, `dy`
|
||||
// pixels off its middle.
|
||||
const green = (dLon, dLat, dy = 0) => {
|
||||
r.frame.renderNow();
|
||||
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
|
||||
const image = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(s.x),
|
||||
y: Math.round(s.y) + dy,
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
const [red, g, blue] = image.data;
|
||||
return g > red + 80 && g > blue + 80;
|
||||
};
|
||||
try {
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
ok(green(0.0035, dLat), `${what}: its new end drawn`);
|
||||
ok(!green(-0.0035, dLat), `${what}: its old end faded`);
|
||||
}
|
||||
ok(green(-0.0035, 0.0035), 'narrowed: its old end drawn, unfaded');
|
||||
ok(green(0.0035, 0.0035, 6), 'narrowed: its new end full width');
|
||||
ok(
|
||||
!green(-0.0035, 0.0035, 6),
|
||||
'narrowed: its old end a quarter as wide',
|
||||
);
|
||||
// Two minutes on, all of it is old; back at t0 its new end is new.
|
||||
r.frame.setTime(t0 + 120_000);
|
||||
await drawn(h, r);
|
||||
ok(!green(0.0035, 0.002), '3d: faded as time moved on');
|
||||
ok(!green(0.0035, -0.002), 'draped: faded as time moved on');
|
||||
r.frame.setTime(t0);
|
||||
await drawn(h, r);
|
||||
ok(green(0.0035, 0.002), '3d: new again back at t0');
|
||||
ok(green(0.0035, -0.002), 'draped: new again back at t0');
|
||||
equal(lines.size(), 3, 'never sent again');
|
||||
} finally {
|
||||
lines.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'lineAgeFade' },
|
||||
),
|
||||
check(
|
||||
'draw.lines.timeWindow',
|
||||
'a line, draped or not, draws only its part within a span of scene time, cut as the time moves on, without being sent again',
|
||||
async (h, r) => {
|
||||
if (h.pixels === false)
|
||||
return { skip: 'this harness reads no drawn pixels' };
|
||||
await overAustin(h, r);
|
||||
const t0 = Date.UTC(2026, 0, 1, 18);
|
||||
r.frame.setTime(t0);
|
||||
// Off the row under the camera, where a ground line can leave a gap.
|
||||
const at = (dLon, dLat, height) =>
|
||||
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
|
||||
const lines = r.draw.lines({ id: 'conf:line-time-window' });
|
||||
// West to east over two minutes, t0 at its middle; shown over the
|
||||
// last 30 s, unfaded.
|
||||
const line = (id, dLat, mode) => ({
|
||||
id,
|
||||
positions: [
|
||||
at(-0.004, dLat, mode === 'draped' ? 0 : 20),
|
||||
at(0.004, dLat, mode === 'draped' ? 0 : 20),
|
||||
],
|
||||
widthPx: 16,
|
||||
mode,
|
||||
style: { kind: 'solid', color: [0, 1, 0, 1] },
|
||||
ageFade: {
|
||||
times: [t0 - 60_000, t0 + 60_000],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 1,
|
||||
showMs: 30_000,
|
||||
},
|
||||
});
|
||||
lines.set([line('air', 0.002, '3d'), line('ground', -0.002, 'draped')]);
|
||||
// Whether the line at `dLon` is drawn green there, strongly.
|
||||
const green = (dLon, dLat) => {
|
||||
r.frame.renderNow();
|
||||
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
|
||||
const image = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(s.x),
|
||||
y: Math.round(s.y),
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
const [red, g, blue] = image.data;
|
||||
return g > red + 80 && g > blue + 80;
|
||||
};
|
||||
try {
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
// At t0 it shows from 30 s ago (a quarter along) to now (half).
|
||||
ok(green(-0.001, dLat), `${what}: drawn within the span`);
|
||||
ok(!green(0.002, dLat), `${what}: not drawn after now`);
|
||||
ok(!green(-0.0035, dLat), `${what}: not drawn before the span`);
|
||||
}
|
||||
// 40 s on, it shows from 10 s to 40 s after t0.
|
||||
r.frame.setTime(t0 + 40_000);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
ok(green(0.002, dLat), `${what}: drawn where now reached`);
|
||||
ok(!green(-0.001, dLat), `${what}: cut as it grew old`);
|
||||
}
|
||||
r.frame.setTime(t0);
|
||||
await drawn(h, r);
|
||||
ok(green(-0.001, 0.002), '3d: drawn again back at t0');
|
||||
ok(!green(0.002, -0.002), 'draped: cut again back at t0');
|
||||
equal(lines.size(), 2, 'never sent again');
|
||||
} finally {
|
||||
lines.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'lineTimeWindow' },
|
||||
),
|
||||
check(
|
||||
'draw.lines.breaks',
|
||||
'a line in runs, draped or not, draws and picks each run, in its segment colours, and nothing between them',
|
||||
async (h, r) => {
|
||||
await overAustin(h, r);
|
||||
// Off the row under the camera, where a ground line can leave a gap.
|
||||
const at = (dLon, dLat, height) =>
|
||||
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
|
||||
const lines = r.draw.lines({ id: 'conf:line-breaks' });
|
||||
// Two runs, west and east, the second starting at position 2: the
|
||||
// pair from position 1 to 2, across the break, is not drawn.
|
||||
const lons = [-0.004, -0.002, 0.001, 0.004];
|
||||
const line = (id, dLat, mode, segmentColors) => ({
|
||||
id,
|
||||
positions: lons.map((dLon) =>
|
||||
at(dLon, dLat, mode === 'draped' ? 0 : 20),
|
||||
),
|
||||
breaks: [2],
|
||||
widthPx: 16,
|
||||
mode,
|
||||
style: { kind: 'solid', color: [0, 1, 0, 1] },
|
||||
...(segmentColors
|
||||
? {
|
||||
// The pair across the break has a colour, ignored.
|
||||
segmentColors: [
|
||||
[1, 0, 0, 1],
|
||||
[0, 1, 0, 1],
|
||||
[0, 0, 1, 1],
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
const kinds = [
|
||||
['3d', 0.003, false],
|
||||
['draped', 0.001, false],
|
||||
['3d coloured', -0.001, true],
|
||||
['draped coloured', -0.003, true],
|
||||
];
|
||||
const lat = new Map(kinds.map(([what, dLat]) => [what, dLat]));
|
||||
lines.set(
|
||||
kinds.map(([what, dLat, coloured]) =>
|
||||
line(
|
||||
what,
|
||||
dLat,
|
||||
what.startsWith('draped') ? 'draped' : '3d',
|
||||
coloured,
|
||||
),
|
||||
),
|
||||
);
|
||||
const where = (what, dLon) =>
|
||||
at(dLon, lat.get(what), what.startsWith('draped') ? 0 : 20);
|
||||
// The colour drawn there, strongly: 'r', 'g', 'b', or null.
|
||||
const colour = (what, dLon) => {
|
||||
r.frame.renderNow();
|
||||
const s = r.query.project(where(what, dLon));
|
||||
const image = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(s.x),
|
||||
y: Math.round(s.y),
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
const [red, green, blue] = image.data;
|
||||
if (red > green + 80 && red > blue + 80) return 'r';
|
||||
if (green > red + 80 && green > blue + 80) return 'g';
|
||||
if (blue > red + 80 && blue > green + 80) return 'b';
|
||||
return null;
|
||||
};
|
||||
const picked = (what, dLon) => {
|
||||
const s = r.query.project(where(what, dLon));
|
||||
ok(s, `${what} projects`);
|
||||
return r.query
|
||||
.drillPick(s.x, s.y)
|
||||
.filter((hit) => hit.set === 'conf:line-breaks')
|
||||
.map((hit) => hit.id);
|
||||
};
|
||||
try {
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
await drawn(h, r);
|
||||
for (const [what, , coloured] of kinds) {
|
||||
deepEqual(
|
||||
picked(what, -0.003),
|
||||
[what],
|
||||
`${what}: its first run picks`,
|
||||
);
|
||||
deepEqual(
|
||||
picked(what, -0.0005),
|
||||
[],
|
||||
`${what}: nothing between its runs`,
|
||||
);
|
||||
deepEqual(
|
||||
picked(what, 0.0025),
|
||||
[what],
|
||||
`${what}: its second run picks`,
|
||||
);
|
||||
if (h.pixels === false) continue;
|
||||
equal(
|
||||
colour(what, -0.003),
|
||||
coloured ? 'r' : 'g',
|
||||
`${what}: its first run drawn`,
|
||||
);
|
||||
equal(
|
||||
colour(what, -0.0005),
|
||||
null,
|
||||
`${what}: nothing drawn between its runs`,
|
||||
);
|
||||
equal(
|
||||
colour(what, 0.0025),
|
||||
coloured ? 'b' : 'g',
|
||||
`${what}: its second run drawn`,
|
||||
);
|
||||
}
|
||||
equal(lines.size(), kinds.length, 'one item a line');
|
||||
} finally {
|
||||
lines.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'lineBreaks' },
|
||||
),
|
||||
check(
|
||||
'draw.lines.breaks.timeWindow',
|
||||
'a line in runs, draped or not, whose first run is later than its second, cuts each run by its own times',
|
||||
async (h, r) => {
|
||||
if (!r.capabilities.has('lineBreaks'))
|
||||
return { skip: 'the renderer draws no lines in runs' };
|
||||
if (h.pixels === false)
|
||||
return { skip: 'this harness reads no drawn pixels' };
|
||||
await overAustin(h, r);
|
||||
const t0 = Date.UTC(2026, 0, 1, 18);
|
||||
r.frame.setTime(t0);
|
||||
const at = (dLon, dLat, height) =>
|
||||
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
|
||||
const lines = r.draw.lines({ id: 'conf:line-breaks-window' });
|
||||
// Its first run, west, the last ten seconds to t0; its second, east,
|
||||
// two minutes before.
|
||||
const line = (id, dLat, mode) => ({
|
||||
id,
|
||||
positions: [-0.004, -0.001, 0.001, 0.004].map((dLon) =>
|
||||
at(dLon, dLat, mode === 'draped' ? 0 : 20),
|
||||
),
|
||||
breaks: [2],
|
||||
widthPx: 16,
|
||||
mode,
|
||||
style: { kind: 'solid', color: [0, 1, 0, 1] },
|
||||
ageFade: {
|
||||
times: [t0 - 10_000, t0, t0 - 120_000, t0 - 110_000],
|
||||
windowMs: 60_000,
|
||||
alphaFloor: 1,
|
||||
showMs: 30_000,
|
||||
},
|
||||
});
|
||||
lines.set([line('air', 0.002, '3d'), line('ground', -0.002, 'draped')]);
|
||||
const green = (dLon, dLat) => {
|
||||
r.frame.renderNow();
|
||||
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
|
||||
const image = r.readPixels({
|
||||
crop: {
|
||||
x: Math.round(s.x),
|
||||
y: Math.round(s.y),
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
const [red, g, blue] = image.data;
|
||||
return g > red + 80 && g > blue + 80;
|
||||
};
|
||||
try {
|
||||
await drawn(h, r);
|
||||
await settled(r);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
ok(green(-0.0025, dLat), `${what}: its later run drawn at t0`);
|
||||
ok(!green(0.0025, dLat), `${what}: its earlier run too old at t0`);
|
||||
ok(!green(0, dLat), `${what}: nothing between its runs`);
|
||||
}
|
||||
// 105 s before t0 the second run is within the span, the first
|
||||
// not yet begun.
|
||||
r.frame.setTime(t0 - 105_000);
|
||||
await drawn(h, r);
|
||||
for (const [what, dLat] of [
|
||||
['3d', 0.002],
|
||||
['draped', -0.002],
|
||||
]) {
|
||||
ok(green(0.0025, dLat), `${what}: its earlier run drawn then`);
|
||||
ok(!green(-0.0025, dLat), `${what}: its later run not yet drawn`);
|
||||
ok(!green(0, dLat), `${what}: still nothing between its runs`);
|
||||
}
|
||||
equal(lines.size(), 2, 'never sent again');
|
||||
} finally {
|
||||
lines.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'lineTimeWindow' },
|
||||
),
|
||||
check(
|
||||
'draw.lines.segments',
|
||||
'a draped line takes segment colours and shows, changed every frame in place, without stopping the frame or picks',
|
||||
|
||||
Vendored
+9
@@ -234,6 +234,15 @@ export type CameraEvent =
|
||||
'changed' | 'moveStart' | 'moveEnd' | 'followChanged' | 'flightEnd';
|
||||
|
||||
export interface CameraPort {
|
||||
/**
|
||||
* Whether any of the ECEF points may be on screen: false only when their
|
||||
* bounding sphere is outside the view or all of them are below the horizon
|
||||
* of WGS84 shrunk by `horizonMarginM` metres; null when it cannot tell
|
||||
* (not a 3D scene, an empty point set, or a non-finite point or camera
|
||||
* vector), which callers treat as visible. Supply a finite, nonnegative
|
||||
* margin smaller than the shortest WGS84 radius.
|
||||
*/
|
||||
visiblePoints?(points: Ecef[], horizonMarginM: number): boolean | null;
|
||||
pose(): CameraPose;
|
||||
/**
|
||||
* Place the eye. A position with a `{direction, up}` orientation is placed
|
||||
|
||||
Vendored
+8
@@ -183,6 +183,8 @@ export type Capability =
|
||||
| 'pickPosition'
|
||||
/** Points tested against the frame's depth (`query.occlusionTest`). */
|
||||
| 'occlusionTest'
|
||||
/** Conservative camera visibility of a point set (`camera.visiblePoints`). */
|
||||
| 'pointVisibility'
|
||||
/** Outward user zooms that keep the Earth framed (`controls.keepEarthFramed`). */
|
||||
| 'keepEarthFramed'
|
||||
/** Height sampling against tiles and terrain. */
|
||||
@@ -205,6 +207,12 @@ export type Capability =
|
||||
| 'fields'
|
||||
/** Rate-limited course easing (`IconItem.courseGlide`). */
|
||||
| 'courseGlide'
|
||||
/** Lines that fade with the age of their points (`LineItem.ageFade`). */
|
||||
| 'lineAgeFade'
|
||||
/** Lines drawn only within a span of the scene clock (`LineAgeFade.showMs`). */
|
||||
| 'lineTimeWindow'
|
||||
/** Lines drawn as several runs, not joined across their breaks (`LineItem.breaks`). */
|
||||
| 'lineBreaks'
|
||||
/** Screen-space clustering of icons. */
|
||||
| 'cluster'
|
||||
/** Post-processing styles. */
|
||||
|
||||
Vendored
+66
@@ -295,10 +295,74 @@ export type LineStyle =
|
||||
rim?: { shade: number; widthFraction: number };
|
||||
};
|
||||
|
||||
/**
|
||||
* `lineAgeFade`: a line that fades with the age of its points, drawn by the
|
||||
* renderer on the scene clock (`frame.setTime`), so a line whose points stay
|
||||
* where they are is not sent again as time passes. A point's recency is
|
||||
* `1 - clamp((now - time) / windowMs, 0, 1)`, its time running evenly
|
||||
* between neighbouring positions, so the fade is smooth along the line, not
|
||||
* stepped at its points. The line's colour (its style's, or a segment's from
|
||||
* `segmentColors`) draws at its alpha times
|
||||
* `mix(alphaFloor, 1, smoothstep(0, 1, recency))`, and with
|
||||
* `squaredAlphaFloor` times `mix(squaredAlphaFloor, 1, recency²)` as well;
|
||||
* with `widthFloor` it draws `widthPx` times `mix(widthFloor, 1, recency)`
|
||||
* wide, about its path. A point at or past the window draws at the floors, a
|
||||
* point at or after now at full strength. New `times` with new positions are
|
||||
* an ordinary update.
|
||||
*
|
||||
* `lineTimeWindow`: with `showMs`, only the part of the line within `showMs`
|
||||
* of now is drawn, cut along it where its interpolated time crosses: parts
|
||||
* whose time is after now, or before `now - showMs`, are not drawn (nor
|
||||
* picked). The cut follows the scene clock as the fade does, so a moving
|
||||
* object's trail can be its whole track, sent once: drawn from `showMs` ago
|
||||
* up to where the object is now. A renderer without the capability ignores
|
||||
* `showMs` and draws the whole line.
|
||||
*/
|
||||
export interface LineAgeFade {
|
||||
/** Each position's time, epoch ms on the scene clock: one per position. */
|
||||
times: number[] | Float64Array;
|
||||
/** The age a point fades over, ms; positive. */
|
||||
windowMs: number;
|
||||
/** A fully aged point's alpha multiplier, 0..1. */
|
||||
alphaFloor: number;
|
||||
/** A second alpha multiplier's floor, eased by recency squared, 0..1. */
|
||||
squaredAlphaFloor?: number;
|
||||
/** A fully aged point's width multiplier, 0..1 [1, no narrowing]. */
|
||||
widthFloor?: number;
|
||||
/**
|
||||
* `lineTimeWindow`: draw only the part of the line from `showMs` before
|
||||
* now up to now, ms; positive (`Infinity`: up to now, however old).
|
||||
* [absent: the whole line]
|
||||
*/
|
||||
showMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* `lineBreaks`: a line drawn as several runs, so many lines in one style can
|
||||
* be one item (thousands of moving objects' trails sent as one line, say),
|
||||
* and the renderer handles one item instead of thousands. Each break is the
|
||||
* index `i` of a position that starts a new run (`0 < i < positions.length`,
|
||||
* strictly increasing): the segment from position `i - 1` to `i` is not
|
||||
* drawn (nor picked), and the line does not join across it, each run having
|
||||
* two ends of its own, capped and joined as a line of its own would be.
|
||||
* `segmentColors` and `segmentShow` stay one a pair of neighbouring
|
||||
* positions (`j`: from position `j` to `j + 1`), so a pair across a break
|
||||
* has an entry that is ignored; `ageFade.times` stays one a position; and
|
||||
* `revealFraction` runs along the runs, in order, as one length (the gaps
|
||||
* between them have none). A renderer without the capability is never sent
|
||||
* `breaks`: its lines are sent one item a run instead.
|
||||
*/
|
||||
export type LineBreaks = number[] | Uint32Array;
|
||||
|
||||
export interface LineItem {
|
||||
id: string;
|
||||
/** ECEF positions, or packed `x, y, z` triples. */
|
||||
positions: Ecef[] | Float64Array;
|
||||
/**
|
||||
* `lineBreaks`: the positions that start a new run of the line
|
||||
* (`LineBreaks`). [absent or empty: one run]
|
||||
*/
|
||||
breaks?: LineBreaks;
|
||||
widthPx: number;
|
||||
/**
|
||||
* `3d`: straight in space; `geodesic`: along the ellipsoid; `draped`: on
|
||||
@@ -321,6 +385,8 @@ export interface LineItem {
|
||||
segmentShow?: boolean[];
|
||||
/** Draw only the first fraction of the line, 0..1. */
|
||||
revealFraction?: number;
|
||||
/** `lineAgeFade`: fade the line with the age of its points (`LineAgeFade`). */
|
||||
ageFade?: LineAgeFade;
|
||||
/** Positions are in a frame rotating with the sky (orbits). */
|
||||
frame?: 'fixed' | 'inertial';
|
||||
meta?: Meta;
|
||||
|
||||
@@ -41,6 +41,9 @@ export const CAPABILITIES = Object.freeze([
|
||||
'meshes',
|
||||
'fields',
|
||||
'courseGlide',
|
||||
'lineAgeFade',
|
||||
'lineTimeWindow',
|
||||
'lineBreaks',
|
||||
'cluster',
|
||||
'styles',
|
||||
'bloom',
|
||||
@@ -50,6 +53,7 @@ export const CAPABILITIES = Object.freeze([
|
||||
'followFrame',
|
||||
'cameraChangeThreshold',
|
||||
'occlusionTest',
|
||||
'pointVisibility',
|
||||
'keepEarthFramed',
|
||||
]);
|
||||
|
||||
@@ -209,6 +213,7 @@ export const PORTS = deepFreeze({
|
||||
'matrices',
|
||||
),
|
||||
['followFrame', 'followFrame'],
|
||||
['visiblePoints', 'pointVisibility'],
|
||||
['controls.keepEarthFramed', 'keepEarthFramed'],
|
||||
]),
|
||||
query: Object.fromEntries([
|
||||
|
||||
@@ -262,6 +262,8 @@ export function createStubRenderer(options = {}) {
|
||||
camera.setViewRectangle(viewRectangle);
|
||||
if (capabilities.has('followFrame'))
|
||||
camera.port.followFrame = camera.eyeFrame;
|
||||
if (capabilities.has('pointVisibility'))
|
||||
camera.port.visiblePoints = () => null;
|
||||
camera.port.setView({
|
||||
destination: { lon: -97.7431, lat: 30.2672, height: 15000000 },
|
||||
});
|
||||
@@ -1328,9 +1330,19 @@ export function createStubRenderer(options = {}) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The positions that start a run of a line in runs (`lineBreaks`), or
|
||||
* null: nothing is drawn between two runs.
|
||||
*/
|
||||
const runStarts = (item) =>
|
||||
capabilities.has('lineBreaks') && item.breaks?.length
|
||||
? new Set(item.breaks)
|
||||
: null;
|
||||
|
||||
/**
|
||||
* A line's positions as ECEF, cut at its `revealFraction` of length (as
|
||||
* drawn straight between its positions).
|
||||
* drawn straight between its positions, along its runs, the gaps between
|
||||
* them having none).
|
||||
*/
|
||||
function revealedLine(item) {
|
||||
const flat = item.positions instanceof Float64Array;
|
||||
@@ -1348,7 +1360,10 @@ export function createStubRenderer(options = {}) {
|
||||
);
|
||||
const fraction = item.revealFraction;
|
||||
if (fraction === undefined || fraction >= 1) return points;
|
||||
const at = alongLength(points, fraction);
|
||||
const starts = runStarts(item);
|
||||
const at = starts
|
||||
? alongRuns(points, starts, fraction)
|
||||
: alongLength(points, fraction);
|
||||
if (!at) return [];
|
||||
const { index, t } = at;
|
||||
return [
|
||||
@@ -1357,17 +1372,43 @@ export function createStubRenderer(options = {}) {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* `alongLength` for a line in runs: the segment a fraction of its runs'
|
||||
* length ends on, and how far along it, the segments between runs
|
||||
* measuring nothing.
|
||||
*/
|
||||
function alongRuns(points, starts, fraction) {
|
||||
if (!(fraction > 0) || points.length < 2) return null;
|
||||
const lengths = [];
|
||||
for (let i = 0; i + 1 < points.length; i++)
|
||||
lengths.push(
|
||||
starts.has(i + 1) ? 0 : magnitude(sub(points[i + 1], points[i])),
|
||||
);
|
||||
const total = lengths.reduce((sum, length) => sum + length, 0);
|
||||
if (!(total > 0)) return null;
|
||||
let left = fraction * total;
|
||||
for (let i = 0; i < lengths.length; i++) {
|
||||
if (lengths[i] > 0 && left <= lengths[i])
|
||||
return { index: i, t: left / lengths[i] };
|
||||
left -= lengths[i];
|
||||
}
|
||||
return { index: lengths.length - 1, t: 1 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a line is under the pixel `(x, y)`: the nearest point of a
|
||||
* drawn segment within half its width (and `slack`) of it, or null.
|
||||
*/
|
||||
function lineHit(item, x, y, slack) {
|
||||
const points = revealedLine(item);
|
||||
const starts = runStarts(item);
|
||||
const reach = (item.widthPx ?? 1) / 2 + slack;
|
||||
let best = null;
|
||||
let bestDistance = Infinity;
|
||||
for (let i = 0; i + 1 < points.length; i++) {
|
||||
if (item.segmentShow?.[i] === false) continue;
|
||||
// Nothing is drawn between two runs.
|
||||
if (starts?.has(i + 1)) continue;
|
||||
const a = points[i];
|
||||
const b = points[i + 1];
|
||||
if (isOccluded(a) && isOccluded(b)) continue;
|
||||
|
||||
@@ -20,7 +20,7 @@ test('the stub passes the conformance suite', async () => {
|
||||
.filter((r) => r.status === 'skip')
|
||||
.map((r) => r.id);
|
||||
// It draws only models into pixels, so the sweep's, a lit shape's, a line outline's, a
|
||||
// split line's, a draped outlined line's and the blends' (over a drawn shape), video tiles', the weather's pixels (drawn, and by scene time) and an encoded capture go unread; its camera takes no user gestures: the drag and wheel scripts are for a
|
||||
// split line's, a draped outlined line's, an aged line's, a time-windowed line's (in runs too) and the blends' (over a drawn shape), video tiles', the weather's pixels (drawn, and by scene time) and an encoded capture go unread; its camera takes no user gestures: the drag and wheel scripts are for a
|
||||
// camera that does (a controller over it, say).
|
||||
assert.deepEqual(skipped, [
|
||||
'effects.screenModulation.pixels',
|
||||
@@ -29,6 +29,9 @@ test('the stub passes the conformance suite', async () => {
|
||||
'draw.sets.blend',
|
||||
'draw.lines.split',
|
||||
'draw.lines.outlineDraped',
|
||||
'draw.lines.ageFade',
|
||||
'draw.lines.timeWindow',
|
||||
'draw.lines.breaks.timeWindow',
|
||||
'draw.models.blend',
|
||||
'draw.models.paint',
|
||||
'globe.imagery.video',
|
||||
@@ -40,6 +43,15 @@ test('the stub passes the conformance suite', async () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test('point visibility capability is optional and the stub reports unknown', () => {
|
||||
const without = createStubRenderer({ capabilities: [] });
|
||||
const withVisibility = createStubRenderer({
|
||||
capabilities: ['pointVisibility'],
|
||||
});
|
||||
assert.equal(without.camera.visiblePoints, undefined);
|
||||
assert.equal(withVisibility.camera.visiblePoints([], 200), null);
|
||||
});
|
||||
|
||||
test('a frame runs the contract’s steps in order', () => {
|
||||
const r = createStubRenderer();
|
||||
r.frame.requestRender('test');
|
||||
|
||||
@@ -2150,50 +2150,6 @@ test('a hold resumed partway waits for a clip that starts again, else only its r
|
||||
assert.deepEqual(await hold(0), [2000]);
|
||||
});
|
||||
|
||||
/** Drive frame-by-frame camera motion headlessly for one test. */
|
||||
function installAnimationFrames() {
|
||||
const original = globalThis.requestAnimationFrame;
|
||||
const originalCancel = globalThis.cancelAnimationFrame;
|
||||
globalThis.requestAnimationFrame = (callback) => setTimeout(callback, 16);
|
||||
globalThis.cancelAnimationFrame = (handle) => clearTimeout(handle);
|
||||
return () => {
|
||||
globalThis.requestAnimationFrame = original;
|
||||
globalThis.cancelAnimationFrame = originalCancel;
|
||||
};
|
||||
}
|
||||
|
||||
test('a run resumed inside a flight goes on from that point of the path and clock', async () => {
|
||||
const { director, viewer, restore } = makeDirector();
|
||||
const restoreFrames = installAnimationFrames();
|
||||
const clock = [];
|
||||
director.subscribeSceneClock((snap) => clock.push(snap));
|
||||
const poses = [];
|
||||
const setView = director._setCameraView.bind(director);
|
||||
director._setCameraView = (pose) => {
|
||||
poses.push(pose);
|
||||
return setView(pose);
|
||||
};
|
||||
try {
|
||||
// 0.75 of a 0.4 s scene: halfway along shot B's 0.2 s flight.
|
||||
const run = director.startScene('scene-1', {
|
||||
single: true,
|
||||
fromProgress: 0.75,
|
||||
preview: false,
|
||||
});
|
||||
await settle(40);
|
||||
const first = clock.find((snap) => snap.running);
|
||||
assert.equal(first.shotId, 'shot-b', 'starts in the shot that moment is in');
|
||||
assert.ok(Math.abs(first.sceneElapsedSec - 0.3) < 1e-9, 'the clock starts at the moment');
|
||||
// The first frame is the seek's own framing, halfway from A to B.
|
||||
assert.ok(poses.length, 'the camera is driven from where it is');
|
||||
assert.ok(Math.abs(poses[0].lat - -10) < 0.5, 'halfway from A to B');
|
||||
assert.deepEqual(await run, { started: true, shots: 1 });
|
||||
assert.equal(poses.at(-1).lat, -30, 'and ends on shot B');
|
||||
assert.equal(viewer.flights.length, 0, 'no fresh flight from the shot start');
|
||||
assert.equal(director._lastRun.wasCancelled, false);
|
||||
} finally { await director.destroy(); restoreFrames(); restore(); }
|
||||
});
|
||||
|
||||
test('a run resumed inside a hold plays its layers on from the seek’s state and waits only the rest of it', async () => {
|
||||
const project = structuredClone(PROJECT_FIXTURE);
|
||||
project.scenes[0].shots[0].holdSec = 0.6;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { cctvProxy } from '../../server/providers/cctv.js';
|
||||
|
||||
/** Collects what a handler wrote, the way a Node ServerResponse would. */
|
||||
export function recordingResponse() {
|
||||
const chunks = [];
|
||||
let finished;
|
||||
const done = new Promise((resolve) => {
|
||||
finished = resolve;
|
||||
});
|
||||
const res = {
|
||||
statusCode: 0,
|
||||
headers: {},
|
||||
writableEnded: false,
|
||||
body: '',
|
||||
writeHead(status, headers) {
|
||||
res.statusCode = status;
|
||||
res.headers = { ...res.headers, ...headers };
|
||||
},
|
||||
setHeader(name, value) {
|
||||
res.headers[name] = value;
|
||||
},
|
||||
write(chunk) {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
return true;
|
||||
},
|
||||
end(chunk) {
|
||||
if (chunk) chunks.push(Buffer.from(chunk));
|
||||
res.writableEnded = true;
|
||||
res.body = Buffer.concat(chunks).toString('utf8');
|
||||
finished();
|
||||
},
|
||||
on() {},
|
||||
once() {},
|
||||
emit() {},
|
||||
destroy() {},
|
||||
};
|
||||
return { res, done };
|
||||
}
|
||||
|
||||
export function mountCctvProvider(t, { cameras, fetch }) {
|
||||
const saved = {};
|
||||
for (const name of [
|
||||
'CCTV_SOURCES_JSON',
|
||||
'CCTV_SOURCES_FILE',
|
||||
'CCTV_FORCE_AUSTIN',
|
||||
'GOOGLE_MAPS_SERVER_API_KEY',
|
||||
'GOOGLE_MAPS_API_KEY',
|
||||
'GEV_RATELIMIT_GOOGLE_PER_MIN',
|
||||
])
|
||||
saved[name] = process.env[name];
|
||||
|
||||
const nativeFetch = globalThis.fetch;
|
||||
const closers = [];
|
||||
t.after(() => {
|
||||
for (const close of closers) close();
|
||||
globalThis.fetch = nativeFetch;
|
||||
for (const [name, value] of Object.entries(saved)) {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
});
|
||||
|
||||
process.env.CCTV_SOURCES_JSON = JSON.stringify(cameras);
|
||||
process.env.CCTV_SOURCES_FILE = 'absent-source-file.json';
|
||||
process.env.CCTV_FORCE_AUSTIN = '0';
|
||||
// No Street View key: a /frame miss lands on the synthetic billboard.
|
||||
delete process.env.GOOGLE_MAPS_SERVER_API_KEY;
|
||||
delete process.env.GOOGLE_MAPS_API_KEY;
|
||||
// The default Google budget, whatever the shell sets.
|
||||
delete process.env.GEV_RATELIMIT_GOOGLE_PER_MIN;
|
||||
// The HLS puller binds fetch when cctvProxy() creates it, so mock first.
|
||||
globalThis.fetch = fetch;
|
||||
let handler;
|
||||
cctvProxy().configureServer({
|
||||
httpServer: { on: (_event, fn) => closers.push(fn) },
|
||||
middlewares: { use: (_route, fn) => (handler = fn) },
|
||||
});
|
||||
if (!handler) throw new Error('the CCTV provider must mount a middleware');
|
||||
|
||||
const call = async (path, headers = {}, method = 'GET', remoteAddress) => {
|
||||
const { res, done } = recordingResponse();
|
||||
await handler(
|
||||
{ url: path, headers, method, socket: { remoteAddress }, on() {} },
|
||||
res,
|
||||
);
|
||||
await done;
|
||||
return res;
|
||||
};
|
||||
const health = async (id) => {
|
||||
const res = await call('/health');
|
||||
return JSON.parse(res.body).cameras.find((entry) => entry.id === id);
|
||||
};
|
||||
return { call, health, handler };
|
||||
}
|
||||
@@ -234,7 +234,7 @@ export function bindFakeCesiumScene(
|
||||
direction: c?.directionWC
|
||||
? plain(c.directionWC)
|
||||
: { x: 0, y: 0, z: -1 },
|
||||
up: { x: 0, y: 1, z: 0 },
|
||||
up: c?.upWC ? plain(c.upWC) : { x: 0, y: 1, z: 0 },
|
||||
right: { x: 1, y: 0, z: 0 },
|
||||
// An orthographic frustum has none, as the Cesium port reports it.
|
||||
fovy:
|
||||
|
||||
@@ -173,7 +173,8 @@ export const getCyclones = defineTool({
|
||||
title: 'Tropical cyclones',
|
||||
description:
|
||||
'Active tropical cyclones from the NOAA National Hurricane Center and ' +
|
||||
'Central Pacific Hurricane Center, optionally limited to an area.',
|
||||
'Central Pacific Hurricane Center, and from the Joint Typhoon Warning ' +
|
||||
'Center elsewhere, optionally limited to an area.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { area: AREA_SCHEMA },
|
||||
@@ -204,6 +205,7 @@ export const getCyclones = defineTool({
|
||||
name: storm.name,
|
||||
classification: storm.classification,
|
||||
basin: storm.basin,
|
||||
agency: storm.agency ?? 'nhc',
|
||||
lat: storm.position.latitude,
|
||||
lon: storm.position.longitude,
|
||||
position_at: storm.positionAt,
|
||||
|
||||
@@ -908,9 +908,6 @@ export class StyleManager extends ShellFacade {
|
||||
this._panelChrome.setPanelCollapsed(panelId, collapsed, options),
|
||||
readPanel: (panel) => this._panelChrome._shownPanel(panel),
|
||||
onSheetsClosed: () => this._syncShareState(),
|
||||
onTabOpened: (sheet) => {
|
||||
void this._onMobileTabOpened(sheet);
|
||||
},
|
||||
publish: (view) =>
|
||||
useDisplayStore(applicationPinia()).publishPhoneShell(view),
|
||||
afterPublish: (callback) => {
|
||||
@@ -919,32 +916,6 @@ export class StyleManager extends ShellFacade {
|
||||
});
|
||||
}
|
||||
|
||||
/** Reveal a tracked aircraft through Contacts when its phone tab is opened. */
|
||||
async _onMobileTabOpened(sheet) {
|
||||
const context = this.getContextModeState();
|
||||
if (
|
||||
sheet !== 'context' ||
|
||||
this._disposed ||
|
||||
!context ||
|
||||
context.mode ||
|
||||
context.changing ||
|
||||
context.entering ||
|
||||
!this.getAircraftTrackingTarget()
|
||||
)
|
||||
return false;
|
||||
try {
|
||||
const result = await this.setContextMode('contacts');
|
||||
if (result?.ok) return true;
|
||||
if (result?.cancelled || this._disposed) return false;
|
||||
} catch {
|
||||
if (this._disposed) return false;
|
||||
}
|
||||
this._showToast(
|
||||
t('Contacts could not complete the requested transition; try again'),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the owner-approved map stack chip row from the matching controller
|
||||
* entries. Cesium ion/Bing chips remain keyboard-focusable but unavailable,
|
||||
|
||||
+16
-1
@@ -1,3 +1,5 @@
|
||||
import { watch } from 'vue';
|
||||
import { MOBILE_SHEET_ATTR } from './mobileSheets.js';
|
||||
import {
|
||||
EMPTY_CCTV_FRAME,
|
||||
_clearCctvFrame,
|
||||
@@ -73,7 +75,10 @@ export class CctvControls {
|
||||
if (state) this._renderCctvState(state);
|
||||
if (this._cctvChip) this._publishCctvChip({});
|
||||
});
|
||||
if (this._cctvVideo && typeof MutationObserver !== 'undefined') {
|
||||
if (
|
||||
(this._cctvVideo || this._cctvFrame) &&
|
||||
typeof MutationObserver !== 'undefined'
|
||||
) {
|
||||
this._videoVisibilityObserver = new MutationObserver(() =>
|
||||
this._renderCctvState(this._cctvState),
|
||||
);
|
||||
@@ -82,6 +87,15 @@ export class CctvControls {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', 'hidden'],
|
||||
});
|
||||
// On phones the panel is on screen only while the Cameras sheet is open.
|
||||
this._videoVisibilityObserver.observe(document.body, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class', MOBILE_SHEET_ATTR],
|
||||
});
|
||||
this._offPreviewCards = watch(
|
||||
() => this.store.previewCards,
|
||||
() => this._renderCctvState(this._cctvState),
|
||||
);
|
||||
this.listen(document, 'visibilitychange', () =>
|
||||
this._renderCctvState(this._cctvState),
|
||||
);
|
||||
@@ -154,6 +168,7 @@ export class CctvControls {
|
||||
this._quebecCctvOverlay?.dispose();
|
||||
this._cctvVideoSurface?.stop();
|
||||
this._videoVisibilityObserver?.disconnect();
|
||||
this._offPreviewCards?.();
|
||||
this._actionGeneration++;
|
||||
this.listeners.abort();
|
||||
this._cctvUnsubscribe?.();
|
||||
|
||||
@@ -186,6 +186,14 @@ export function _settleCctvFrame(token, src, ok) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Shared live health describes the stream even when this viewer shows a frame. */
|
||||
export function isCctvLiveFrameFallback(activeCamera) {
|
||||
return (
|
||||
activeCamera?.isVideo === false &&
|
||||
String(activeCamera.sourceKind || '').toLowerCase() === 'live'
|
||||
);
|
||||
}
|
||||
|
||||
/** The source badge's label and frame state for the camera and preview. */
|
||||
export function presentCctvSourceBadge(activeCamera, enabled, frame) {
|
||||
if (!enabled || !activeCamera)
|
||||
@@ -194,6 +202,11 @@ export function presentCctvSourceBadge(activeCamera, enabled, frame) {
|
||||
return { label: t('FRAME · LOADING'), state: 'loading' };
|
||||
if (frame.error && !frame.hasFrame)
|
||||
return { label: t('FRAME · UNAVAILABLE'), state: 'error' };
|
||||
if (isCctvLiveFrameFallback(activeCamera))
|
||||
return {
|
||||
label: `${cctvSourceKindLabel('fallback')} · ${cctvSourceStatusLabel('degraded')}`,
|
||||
state: 'ready',
|
||||
};
|
||||
const kind = cctvSourceKindLabel(
|
||||
activeCamera.sourceKind || activeCamera.feedType || 'unknown',
|
||||
);
|
||||
|
||||
+152
-11
@@ -20,7 +20,7 @@ const BUTTONS = {
|
||||
_cctvProjectionBtn: 'cctv-projection-btn',
|
||||
};
|
||||
|
||||
function panel(t) {
|
||||
function panel(t, { video = false } = {}) {
|
||||
document.body.replaceChildren();
|
||||
const host = document.body.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
@@ -32,6 +32,7 @@ function panel(t) {
|
||||
document.getElementById(id),
|
||||
]),
|
||||
);
|
||||
if (video) elements._cctvVideo = document.getElementById('cctv-video');
|
||||
const controls = new CctvControls({
|
||||
elements: {
|
||||
...elements,
|
||||
@@ -377,17 +378,10 @@ test('a second edit of the same chip gets a fresh input', async (t) => {
|
||||
});
|
||||
|
||||
test('the frame preview renders each step of a camera frame request', async (t) => {
|
||||
const prior = globalThis.Image;
|
||||
const requests = [];
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
requests.push(this);
|
||||
}
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.Image = prior;
|
||||
});
|
||||
const requests = mockImages(t);
|
||||
const { controls, byId } = panel(t);
|
||||
// The preview loads while the panel is open; the panel starts collapsed.
|
||||
byId('cctv-panel').classList.remove('collapsed');
|
||||
const frame = byId('cctv-frame');
|
||||
const wrap = byId('cctv-frame-wrap');
|
||||
const badge = byId('cctv-source-badge');
|
||||
@@ -606,3 +600,150 @@ test('the meta line of a disabled layer does not describe its last camera', () =
|
||||
);
|
||||
assert.match(presentCctvPanel(activeState, true).meta, /^Austin · HDG /);
|
||||
});
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
function mockImages(t) {
|
||||
const prior = globalThis.Image;
|
||||
const requests = [];
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
requests.push(this);
|
||||
}
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.Image = prior;
|
||||
});
|
||||
return requests;
|
||||
}
|
||||
|
||||
const stillState = (frameUrl, id = 'a') => ({
|
||||
enabled: true,
|
||||
count: 2,
|
||||
cameraIndex: [camera, { ...camera, id: 'b' }],
|
||||
activeCameraId: id,
|
||||
activeCamera: { ...camera, id, frameUrl, sourceKind: 'snapshot' },
|
||||
});
|
||||
|
||||
test('the still preview is fetched only while the tab and the panel are shown', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const hidden = Object.getOwnPropertyDescriptor(document, 'hidden');
|
||||
let tabHidden = false;
|
||||
Object.defineProperty(document, 'hidden', {
|
||||
configurable: true,
|
||||
get: () => tabHidden,
|
||||
});
|
||||
t.after(() => {
|
||||
if (hidden) Object.defineProperty(document, 'hidden', hidden);
|
||||
else delete document.hidden;
|
||||
});
|
||||
const { controls, byId } = panel(t);
|
||||
assert.equal(controls._cctvVideo, undefined);
|
||||
const panelElement = byId('cctv-panel');
|
||||
const state = stillState;
|
||||
|
||||
// Collapsed panel: nothing is requested, however often the state arrives.
|
||||
assert.equal(panelElement.classList.contains('collapsed'), true);
|
||||
controls._renderCctvState(state('a1.jpg'));
|
||||
controls._renderCctvState(state('a2.jpg'));
|
||||
assert.equal(requests.length, 0, 'collapsed panel');
|
||||
|
||||
// Opening it resumes through the class observer, with no manual render.
|
||||
panelElement.classList.remove('collapsed');
|
||||
await settle();
|
||||
assert.equal(requests.length, 1, 'expanded panel');
|
||||
assert.equal(requests[0].src, 'a2.jpg');
|
||||
requests[0].onload();
|
||||
|
||||
// A background tab: refreshed URLs are not requested.
|
||||
tabHidden = true;
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
controls._renderCctvState(state('a3.jpg'));
|
||||
assert.equal(requests.length, 1, 'hidden tab');
|
||||
|
||||
// Back in the tab: visibilitychange alone fetches the current URL.
|
||||
tabHidden = false;
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
assert.equal(requests.length, 2, 'visible tab');
|
||||
assert.equal(requests[1].src, 'a3.jpg');
|
||||
});
|
||||
|
||||
test('the still preview waits for the Cameras sheet on phones', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
const { controls, byId } = panel(t);
|
||||
byId('cctv-panel').classList.remove('collapsed');
|
||||
document.body.classList.add('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'layers');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 0, 'another sheet is open');
|
||||
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 0, 'no sheet is open');
|
||||
|
||||
document.body.setAttribute('data-mobile-sheet', 'cameras');
|
||||
await settle();
|
||||
assert.equal(requests.length, 1, 'Cameras sheet opened');
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
|
||||
// Off a phone the sheet attribute means nothing.
|
||||
requests[0].onload();
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'layers');
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
assert.equal(requests.length, 2, 'desktop ignores the sheet');
|
||||
});
|
||||
|
||||
test('a camera picked while the panel is collapsed shows its own still on expanding', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, byId } = panel(t);
|
||||
const panelElement = byId('cctv-panel');
|
||||
panelElement.classList.remove('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
panelElement.classList.add('collapsed');
|
||||
await settle();
|
||||
controls._renderCctvState(stillState('b1.jpg', 'b'));
|
||||
assert.equal(requests.length, 1);
|
||||
requests[0].onload();
|
||||
panelElement.classList.remove('collapsed');
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(requests.length, 2);
|
||||
assert.equal(requests[1].src, 'b1.jpg');
|
||||
assert.equal(byId('cctv-frame').dataset.cameraId, 'b');
|
||||
assert.notEqual(byId('cctv-frame').getAttribute('src'), 'a1.jpg');
|
||||
});
|
||||
|
||||
test('leaving the Cameras sheet stops the live video and coming back starts it again', async (t) => {
|
||||
const { controls, byId } = panel(t, { video: true });
|
||||
byId('cctv-panel').classList.remove('collapsed');
|
||||
document.body.classList.add('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'cameras');
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
controls._renderCctvState({
|
||||
enabled: true,
|
||||
count: 1,
|
||||
cameraIndex: [camera],
|
||||
activeCameraId: 'a',
|
||||
activeCamera: { ...camera, isVideo: true },
|
||||
});
|
||||
const first = controls._cctvVideoSurface;
|
||||
assert.ok(first);
|
||||
const stop = t.mock.method(first, 'stop');
|
||||
document.body.setAttribute('data-mobile-sheet', 'layers');
|
||||
await settle();
|
||||
assert.equal(stop.mock.callCount(), 1);
|
||||
assert.equal(controls._cctvVideoSurface, null);
|
||||
document.body.setAttribute('data-mobile-sheet', 'cameras');
|
||||
await settle();
|
||||
assert.ok(controls._cctvVideoSurface);
|
||||
assert.notEqual(controls._cctvVideoSurface, first);
|
||||
});
|
||||
@@ -1,9 +1,22 @@
|
||||
import { getLocale, keepCodesWithValues, msg, t, tn } from '../i18n/index.js';
|
||||
import { cctvSourceLabelText, cctvSourceMessageText } from './cctvFrames.js';
|
||||
import {
|
||||
cctvSourceLabelText,
|
||||
cctvSourceMessageText,
|
||||
isCctvLiveFrameFallback,
|
||||
} from './cctvFrames.js';
|
||||
|
||||
import { createCctvVideoSurface } from './cctvVideo.js';
|
||||
import { presentCctvCalibration } from './cctvCalibration.js';
|
||||
import { roundHeadingDegrees } from '../data/headingDegrees.js';
|
||||
import {
|
||||
MOBILE_SHELL_CLASS,
|
||||
MOBILE_SHEET_ATTR,
|
||||
sheetForPanelId,
|
||||
} from './mobileSheets.js';
|
||||
|
||||
const CAMERAS_SHEET = sheetForPanelId('cctv-panel');
|
||||
const CONTEXT_SHEET = sheetForPanelId('global-context-panel');
|
||||
|
||||
export function _calBadgeLabel(badge) {
|
||||
switch (badge) {
|
||||
case 'calibrated':
|
||||
@@ -96,9 +109,10 @@ function metaText(state, enabled, activeCamera, catalogCount) {
|
||||
const provider = cctvSourceLabelText(
|
||||
activeCamera.sourceLabel || activeCamera.provider || 'Configured Source',
|
||||
);
|
||||
const statusMsg = activeCamera.sourceMessage
|
||||
? ` · ${cctvSourceMessageText(activeCamera.sourceMessage)}`
|
||||
: '';
|
||||
const statusMsg =
|
||||
activeCamera.sourceMessage && !isCctvLiveFrameFallback(activeCamera)
|
||||
? ` · ${cctvSourceMessageText(activeCamera.sourceMessage)}`
|
||||
: '';
|
||||
// A partner-supplied feed inside a pack names its owner here.
|
||||
const credit = activeCamera.credit ? ` · ${activeCamera.credit}` : '';
|
||||
const calBadge = activeCamera.calBadge
|
||||
@@ -274,11 +288,25 @@ export function _renderCctvState(state) {
|
||||
const liveIntent =
|
||||
enabled && !!activeCamera?.isVideo && !activeCamera?.browserMediaUrl;
|
||||
this.store.setLive(liveIntent);
|
||||
// A background tab, a collapsed panel or a closed phone sheet shows no
|
||||
// picture; the observers and visibilitychange render again on showing.
|
||||
const body = globalThis.document?.body;
|
||||
const phone = body?.classList.contains(MOBILE_SHELL_CLASS);
|
||||
const sheet = body?.getAttribute(MOBILE_SHEET_ATTR);
|
||||
const tabShown = !!body && !document.hidden;
|
||||
const panelShown =
|
||||
tabShown &&
|
||||
!this._cctvPanel?.classList.contains('collapsed') &&
|
||||
(!phone || sheet === CAMERAS_SHEET);
|
||||
// Context's camera card shows the same still.
|
||||
const cardShown =
|
||||
tabShown &&
|
||||
this.store.previewCards > 0 &&
|
||||
(!phone || sheet === CONTEXT_SHEET);
|
||||
// Its bigger view is a popup over the map, shown on any phone sheet.
|
||||
const popupShown = tabShown && this.store.previewPopups > 0;
|
||||
if (this._cctvVideo) {
|
||||
const visible =
|
||||
liveIntent &&
|
||||
!document.hidden &&
|
||||
!this._cctvPanel?.classList.contains('collapsed');
|
||||
const visible = liveIntent && panelShown;
|
||||
if (!visible || this._cctvVideoCameraId !== activeId) {
|
||||
this._cctvVideoSurface?.stop();
|
||||
this._cctvVideoSurface = null;
|
||||
@@ -303,6 +331,7 @@ export function _renderCctvState(state) {
|
||||
// immediate so navigation never waits on the prior camera's request.
|
||||
if (
|
||||
nextSrc &&
|
||||
(panelShown || cardShown || popupShown) &&
|
||||
(cameraChanged || (!frameLoading && this._frame.currentSrc !== nextSrc))
|
||||
) {
|
||||
this._queueCctvFrame(nextSrc, nextCameraId, cameraChanged);
|
||||
|
||||
@@ -9,7 +9,13 @@ import {
|
||||
subjectEntryAllowed,
|
||||
} from '../contextModePolicy.js';
|
||||
import { cockpitSubjectProviders } from '../cockpitSubjectProviders.js';
|
||||
import { formatAwarenessLabel } from '../data/militaryAwarenessEngine.js';
|
||||
import {
|
||||
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
|
||||
aircraftClassMatches,
|
||||
formatAwarenessLabel,
|
||||
} from '../data/militaryAwarenessEngine.js';
|
||||
import { fromDegreesInto } from '../geo/ellipsoid.js';
|
||||
import { findCamera } from '../render/rendererOf.js';
|
||||
import { enterCockpitWithTracking } from '../cockpitTracking.js';
|
||||
import { cockpitVisionModeForStyle } from '../cockpitVisionPolicy.js';
|
||||
import { readEntityRecord } from '../data/entityRecords.js';
|
||||
@@ -352,13 +358,41 @@ export class CockpitCoordinator {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a requested-layer entry searches from: the aircraft the camera
|
||||
* follows, else the ground under the camera.
|
||||
* @param {{layerId: string}|null} currentTarget The tracked aircraft.
|
||||
* @returns {{x: number, y: number, z: number}|null}
|
||||
*/
|
||||
_cockpitEntrySearchOrigin(currentTarget) {
|
||||
const { flightsLayer, militaryFlightsLayer } = this.services;
|
||||
const layer =
|
||||
currentTarget?.layerId === 'military'
|
||||
? militaryFlightsLayer
|
||||
: currentTarget?.layerId === 'flights'
|
||||
? flightsLayer
|
||||
: null;
|
||||
const subject = layer?.getTrackedSubject?.();
|
||||
if (subject?.position) return subject.position;
|
||||
const pose = findCamera(this.viewer)?.pose?.();
|
||||
if (!Number.isFinite(pose?.lat) || !Number.isFinite(pose?.lon)) return null;
|
||||
return fromDegreesInto(pose.lon, pose.lat, 0, { x: 0, y: 0, z: 0 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Retarget a voice entry to the requested layer and class before entering.
|
||||
* It searches the aircraft that layer shows, under the person's own
|
||||
* filters, nearest first, from the followed aircraft or the camera, and
|
||||
* follows the nearest match; the aircraft already followed counts when it
|
||||
* matches. It needs nothing from Contacts.
|
||||
*/
|
||||
_retargetCockpitEntryLayer({
|
||||
targetLayer,
|
||||
aircraftClass,
|
||||
currentTarget,
|
||||
selectedTarget,
|
||||
}) {
|
||||
const { militaryAwarenessLayer } = this.services;
|
||||
const { flightsLayer, militaryFlightsLayer } = this.services;
|
||||
if (!['flights', 'military'].includes(targetLayer)) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -370,12 +404,27 @@ export class CockpitCoordinator {
|
||||
const alreadyOnLayer = activeLayer === targetLayer;
|
||||
if (alreadyOnLayer && !aircraftClass)
|
||||
return { ok: true, retargeted: false };
|
||||
const moved = militaryAwarenessLayer?.navigateNext
|
||||
? !!militaryAwarenessLayer.navigateNext({
|
||||
targetLayer,
|
||||
aircraftClass,
|
||||
origin: 'voice',
|
||||
})
|
||||
const layer =
|
||||
targetLayer === 'military' ? militaryFlightsLayer : flightsLayer;
|
||||
const origin = this._cockpitEntrySearchOrigin(currentTarget);
|
||||
const nearby =
|
||||
origin && typeof layer?.getNearby === 'function'
|
||||
? layer.getNearby(
|
||||
origin,
|
||||
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
|
||||
targetLayer === 'military' ? 5000 : 25000,
|
||||
)
|
||||
: [];
|
||||
const match = nearby.find(
|
||||
(item) => item?.icao24 && aircraftClassMatches(item, aircraftClass),
|
||||
);
|
||||
const followed =
|
||||
match &&
|
||||
currentTarget?.layerId === targetLayer &&
|
||||
String(currentTarget.id) === String(match.icao24);
|
||||
if (followed) return { ok: true, retargeted: false };
|
||||
const moved = match
|
||||
? !!layer.trackById?.(match.icao24, { origin: 'voice' })
|
||||
: false;
|
||||
if (moved) return { ok: true, retargeted: true };
|
||||
// A filter that matched nothing still enters, as long as the layer is
|
||||
|
||||
@@ -869,3 +869,79 @@ test('a malformed provider is left out and the built-in kinds are unchanged', as
|
||||
assert.equal(cockpit.enter(), true);
|
||||
assert.equal(cockpit.subjectKind, 'aircraft');
|
||||
});
|
||||
|
||||
// A requested-layer entry finds its aircraft in that layer, from the
|
||||
// aircraft the camera follows; it never asks Contacts.
|
||||
function retargetFixture(t, nearby) {
|
||||
const { coordinator } = fixture(t, {
|
||||
enabled: ['flights', 'military'],
|
||||
tracked: { layerId: 'flights', info: CIVIL },
|
||||
});
|
||||
const tracked = [];
|
||||
const searches = [];
|
||||
coordinator.services.militaryAwarenessLayer.navigateNext = () =>
|
||||
assert.fail('entry must not navigate through Contacts');
|
||||
coordinator.services.flightsLayer.getTrackedSubject = () => ({
|
||||
layerId: 'flights',
|
||||
id: CIVIL.icao24,
|
||||
position: { x: 1, y: 2, z: 3 },
|
||||
});
|
||||
coordinator.services.militaryFlightsLayer.getNearby = (...args) => {
|
||||
searches.push(args);
|
||||
return nearby;
|
||||
};
|
||||
coordinator.services.militaryFlightsLayer.trackById = (id, options) => {
|
||||
tracked.push([id, options.origin]);
|
||||
return true;
|
||||
};
|
||||
return { coordinator, tracked, searches };
|
||||
}
|
||||
|
||||
test('a voice entry asking for a military class follows the nearest match without Contacts', (t) => {
|
||||
const { coordinator, tracked, searches } = retargetFixture(t, [
|
||||
{ icao24: 'jet1', aircraftClass: 'fighter', distance: 10 },
|
||||
{ icao24: 'helo1', aircraftClass: 'helicopter', distance: 20 },
|
||||
{ icao24: 'helo2', aircraftClass: 'helicopter', distance: 30 },
|
||||
]);
|
||||
const result = coordinator._retargetCockpitEntryLayer({
|
||||
targetLayer: 'military',
|
||||
aircraftClass: 'helicopter',
|
||||
currentTarget: { layerId: 'flights', id: CIVIL.icao24 },
|
||||
selectedTarget: null,
|
||||
});
|
||||
assert.deepEqual(result, { ok: true, retargeted: true });
|
||||
assert.deepEqual(tracked, [['helo1', 'voice']]);
|
||||
// Searched from the followed aircraft, among the aircraft the person's
|
||||
// filters show: never the hidden ones.
|
||||
assert.deepEqual(searches[0][0], { x: 1, y: 2, z: 3 });
|
||||
assert.equal(searches[0][3], undefined);
|
||||
});
|
||||
|
||||
test('a voice entry whose followed aircraft already matches stays on it', (t) => {
|
||||
const { coordinator, tracked } = retargetFixture(t, [
|
||||
{ icao24: 'helo1', aircraftClass: 'helicopter', distance: 0 },
|
||||
]);
|
||||
const result = coordinator._retargetCockpitEntryLayer({
|
||||
targetLayer: 'military',
|
||||
aircraftClass: 'helicopter',
|
||||
currentTarget: { layerId: 'military', id: 'helo1' },
|
||||
selectedTarget: null,
|
||||
});
|
||||
assert.deepEqual(result, { ok: true, retargeted: false });
|
||||
assert.deepEqual(tracked, []);
|
||||
});
|
||||
|
||||
test('a voice entry with no matching aircraft says so and follows nothing', (t) => {
|
||||
const { coordinator, tracked } = retargetFixture(t, [
|
||||
{ icao24: 'jet1', aircraftClass: 'fighter', distance: 10 },
|
||||
]);
|
||||
const result = coordinator._retargetCockpitEntryLayer({
|
||||
targetLayer: 'military',
|
||||
aircraftClass: 'helicopter',
|
||||
currentTarget: { layerId: 'flights', id: CIVIL.icao24 },
|
||||
selectedTarget: null,
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.error, /No helicopter military contact is available/);
|
||||
assert.deepEqual(tracked, []);
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, nextTick } from 'vue';
|
||||
import { CctvControls } from './cctvControls.js';
|
||||
import { useCctvStore } from './stores/cctv.js';
|
||||
import CctvPanel from './views/panels/CctvPanel.vue';
|
||||
import CctvPreview from './views/panels/CctvPreview.vue';
|
||||
|
||||
const settle = () => new Promise((r) => setTimeout(r, 0));
|
||||
const camera = {
|
||||
id: 'a',
|
||||
city: 'Austin',
|
||||
name: 'Congress Ave',
|
||||
headingDeg: 91.6,
|
||||
fovDeg: 60,
|
||||
rangeM: 120.4,
|
||||
sourceLabel: 'Configured Source',
|
||||
calBadge: 'curated',
|
||||
};
|
||||
const stillState = (frameUrl, id = 'a') => ({
|
||||
enabled: true,
|
||||
count: 2,
|
||||
cameraIndex: [camera, { ...camera, id: 'b' }],
|
||||
activeCameraId: id,
|
||||
activeCamera: { ...camera, id, frameUrl, sourceKind: 'snapshot' },
|
||||
});
|
||||
|
||||
function fixture(t, { card = true } = {}) {
|
||||
document.body.replaceChildren();
|
||||
const host = document.body.appendChild(document.createElement('div'));
|
||||
const cardHost = document.body.appendChild(document.createElement('div'));
|
||||
const pinia = createPinia();
|
||||
const app = createApp(CctvPanel).use(pinia);
|
||||
app.mount(host);
|
||||
let preview;
|
||||
function mountCard() {
|
||||
preview = createApp(CctvPreview, { cameraId: 'a' }).use(pinia);
|
||||
preview.mount(cardHost);
|
||||
}
|
||||
function unmountCard() {
|
||||
preview?.unmount();
|
||||
preview = null;
|
||||
}
|
||||
if (card) mountCard();
|
||||
const store = useCctvStore(pinia);
|
||||
const controls = new CctvControls({
|
||||
elements: {
|
||||
_cctvPanel: document.getElementById('cctv-panel'),
|
||||
_cctvFrame: document.getElementById('cctv-frame'),
|
||||
_cctvFrameWrap: document.getElementById('cctv-frame-wrap'),
|
||||
},
|
||||
cctv: {},
|
||||
actions: {
|
||||
isEnabled: () => true,
|
||||
setPanelCollapsed() {},
|
||||
syncViewport() {},
|
||||
},
|
||||
store,
|
||||
});
|
||||
t.after(() => {
|
||||
controls.destroy();
|
||||
app.unmount();
|
||||
preview?.unmount();
|
||||
});
|
||||
return {
|
||||
controls,
|
||||
cardHost,
|
||||
mountCard,
|
||||
unmountCard,
|
||||
store,
|
||||
panelEl: document.getElementById('cctv-panel'),
|
||||
};
|
||||
}
|
||||
|
||||
function mockImages(t) {
|
||||
const prior = globalThis.Image;
|
||||
const requests = [];
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
requests.push(this);
|
||||
}
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.Image = prior;
|
||||
});
|
||||
return requests;
|
||||
}
|
||||
|
||||
test('desktop: the Context card keeps refreshing while the accordion folds CCTV', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, cardHost, panelEl } = fixture(t);
|
||||
panelEl.classList.remove('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 1);
|
||||
requests[0].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(cardHost.querySelector('img')?.getAttribute('src'), 'a1.jpg');
|
||||
// Context opens: the desktop accordion folds CCTV (class collapsed).
|
||||
panelEl.classList.add('collapsed');
|
||||
await settle();
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
assert.equal(requests.length, 2);
|
||||
assert.equal(requests[1].src, 'a2.jpg');
|
||||
requests[1].onload();
|
||||
controls._renderCctvState(stillState('a3.jpg'));
|
||||
assert.equal(requests.length, 3);
|
||||
assert.equal(requests[2].src, 'a3.jpg');
|
||||
requests[2].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(cardHost.querySelector('img')?.getAttribute('src'), 'a3.jpg');
|
||||
});
|
||||
|
||||
test('phone: a camera picked with the Context sheet open gets its still', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
const { controls, cardHost, panelEl } = fixture(t);
|
||||
document.body.classList.add('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'context');
|
||||
panelEl.classList.remove('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
requests.length,
|
||||
1,
|
||||
'the Context card on the Context sheet requests the still',
|
||||
);
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
requests.at(-1).onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.ok(
|
||||
cardHost.querySelector('.cctv-preview__expand'),
|
||||
'the card shows a frame, not Acquiring frame…',
|
||||
);
|
||||
});
|
||||
|
||||
test('phone: the card on a closed Context sheet waits', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, panelEl } = fixture(t);
|
||||
panelEl.classList.add('collapsed');
|
||||
document.body.classList.add('mobile-shell');
|
||||
document.body.setAttribute('data-mobile-sheet', 'layers');
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 0);
|
||||
document.body.setAttribute('data-mobile-sheet', 'context');
|
||||
await settle();
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
});
|
||||
|
||||
test('phone: the bigger view keeps refreshing after the layout turns phone, and stops once closed', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
t.after(() => {
|
||||
document.body.classList.remove('mobile-shell');
|
||||
document.body.removeAttribute('data-mobile-sheet');
|
||||
});
|
||||
const { controls, cardHost, panelEl } = fixture(t);
|
||||
panelEl.classList.add('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 1);
|
||||
requests[0].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
cardHost.querySelector('.cctv-preview__expand').click();
|
||||
await settle();
|
||||
await nextTick();
|
||||
const popup = document.body.querySelector('.cctv-popup');
|
||||
assert.ok(popup);
|
||||
assert.equal(popup.querySelector('img').getAttribute('src'), 'a1.jpg');
|
||||
|
||||
document.body.classList.add('mobile-shell');
|
||||
await settle();
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.ok(document.body.contains(popup));
|
||||
assert.equal(requests.length, 2);
|
||||
assert.equal(requests[1].src, 'a2.jpg');
|
||||
requests[1].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(popup.querySelector('img').getAttribute('src'), 'a2.jpg');
|
||||
|
||||
popup.querySelector('.cctv-popup__close').click();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(document.body.querySelector('.cctv-popup'), null);
|
||||
controls._renderCctvState(stillState('a3.jpg'));
|
||||
await settle();
|
||||
assert.equal(requests.length, 2);
|
||||
});
|
||||
|
||||
test('desktop: a card that mounts asks for the still', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, panelEl, mountCard } = fixture(t, { card: false });
|
||||
panelEl.classList.add('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
await settle();
|
||||
assert.equal(requests.length, 0);
|
||||
mountCard();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].src, 'a1.jpg');
|
||||
});
|
||||
|
||||
test('desktop: a card that unmounts stops the still, and a remount resumes it', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, panelEl, mountCard, unmountCard, store } = fixture(t);
|
||||
panelEl.classList.add('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
assert.equal(requests.length, 1);
|
||||
requests[0].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
|
||||
unmountCard();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(store.previewCards, 0);
|
||||
controls._renderCctvState(stillState('a2.jpg'));
|
||||
await settle();
|
||||
assert.equal(requests.length, 1);
|
||||
|
||||
mountCard();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(requests.length, 2);
|
||||
assert.equal(requests[1].src, 'a2.jpg');
|
||||
});
|
||||
|
||||
test('desktop: the bigger view is released when the card unmounts, also in the tick it closes', async (t) => {
|
||||
const requests = mockImages(t);
|
||||
const { controls, cardHost, panelEl, mountCard, unmountCard, store } =
|
||||
fixture(t);
|
||||
panelEl.classList.add('collapsed');
|
||||
controls._renderCctvState(stillState('a1.jpg'));
|
||||
requests[0].onload();
|
||||
await settle();
|
||||
await nextTick();
|
||||
const openPopup = async () => {
|
||||
cardHost.querySelector('.cctv-preview__expand').click();
|
||||
await nextTick();
|
||||
assert.equal(store.previewPopups, 1);
|
||||
};
|
||||
|
||||
await openPopup();
|
||||
unmountCard();
|
||||
await nextTick();
|
||||
assert.equal(document.body.querySelector('.cctv-popup'), null);
|
||||
assert.equal(store.previewPopups, 0);
|
||||
|
||||
mountCard();
|
||||
await nextTick();
|
||||
await openPopup();
|
||||
// Closed and unmounted before the watcher runs, as when one Escape closes
|
||||
// the phone's Context sheet and the popup.
|
||||
document.body.querySelector('.cctv-popup__close').click();
|
||||
unmountCard();
|
||||
await settle();
|
||||
await nextTick();
|
||||
assert.equal(store.previewPopups, 0);
|
||||
assert.equal(store.previewCards, 0);
|
||||
const before = requests.length;
|
||||
controls._renderCctvState(stillState('a3.jpg'));
|
||||
await settle();
|
||||
assert.equal(requests.length, before);
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
export const MOBILE_SHELL_CLASS = 'mobile-shell';
|
||||
export const MOBILE_SHEET_ATTR = 'data-mobile-sheet';
|
||||
|
||||
/**
|
||||
* Panels each sheet expands. A sheet also shows its rail's other panels
|
||||
* collapsed (Scenes under Layers), per styles/mobile-shell.css.
|
||||
*/
|
||||
export const MOBILE_SHEET_PANELS = Object.freeze({
|
||||
layers: Object.freeze(['data-panel']),
|
||||
cameras: Object.freeze(['cctv-panel', 'street-level-panel']),
|
||||
context: Object.freeze(['global-context-panel']),
|
||||
missions: Object.freeze(['space-missions-panel']),
|
||||
search: Object.freeze(['location-bar']),
|
||||
more: Object.freeze(['control-panel', 'pp-toggles']),
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {string} panelId
|
||||
* @returns {string|null} The sheet that presents `panelId`.
|
||||
*/
|
||||
export function sheetForPanelId(panelId) {
|
||||
for (const [sheet, ids] of Object.entries(MOBILE_SHEET_PANELS)) {
|
||||
if (ids.includes(panelId)) return sheet;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
+13
-31
@@ -18,23 +18,20 @@ import {
|
||||
readPanelState,
|
||||
} from './rail/panelState.js';
|
||||
|
||||
import {
|
||||
MOBILE_SHELL_CLASS,
|
||||
MOBILE_SHEET_ATTR,
|
||||
MOBILE_SHEET_PANELS,
|
||||
} from './mobileSheets.js';
|
||||
|
||||
export {
|
||||
MOBILE_SHELL_CLASS,
|
||||
MOBILE_SHEET_ATTR,
|
||||
MOBILE_SHEET_PANELS,
|
||||
sheetForPanelId,
|
||||
} from './mobileSheets.js';
|
||||
|
||||
export const MOBILE_SHELL_MEDIA_QUERY = '(max-width: 720px)';
|
||||
export const MOBILE_SHELL_CLASS = 'mobile-shell';
|
||||
export const MOBILE_SHEET_ATTR = 'data-mobile-sheet';
|
||||
|
||||
/**
|
||||
* Panels each sheet expands. A sheet also shows its rail's other panels
|
||||
* collapsed (Scenes under Layers), per styles/mobile-shell.css.
|
||||
*/
|
||||
export const MOBILE_SHEET_PANELS = Object.freeze({
|
||||
layers: Object.freeze(['data-panel']),
|
||||
cameras: Object.freeze(['cctv-panel', 'street-level-panel']),
|
||||
context: Object.freeze(['global-context-panel']),
|
||||
missions: Object.freeze(['space-missions-panel']),
|
||||
search: Object.freeze(['location-bar']),
|
||||
more: Object.freeze(['control-panel', 'pp-toggles']),
|
||||
});
|
||||
|
||||
export const MOBILE_TABS = Object.freeze([
|
||||
Object.freeze({ sheet: 'layers', label: msg('Layers'), icon: 'layers' }),
|
||||
Object.freeze({ sheet: 'cameras', label: msg('Cameras'), icon: 'videocam' }),
|
||||
@@ -64,17 +61,6 @@ const BORROWED_PANELS = Object.freeze([
|
||||
|
||||
const BORROW_OPTIONS = Object.freeze({ persist: false, syncShare: false });
|
||||
|
||||
/**
|
||||
* @param {string} panelId
|
||||
* @returns {string|null} The sheet that presents `panelId`.
|
||||
*/
|
||||
export function sheetForPanelId(panelId) {
|
||||
for (const [sheet, ids] of Object.entries(MOBILE_SHEET_PANELS)) {
|
||||
if (ids.includes(panelId)) return sheet;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sheet after a tab press: the same tab closes its sheet, another opens.
|
||||
* @param {string|null} current
|
||||
@@ -112,8 +98,6 @@ function currentSheetOf(body) {
|
||||
* @param {(callback: () => void) => number} [input.requestFrame]
|
||||
* @param {() => void} [input.onSheetsClosed] Runs after the last sheet closes
|
||||
* and its panels are put back (e.g. to refresh the share link).
|
||||
* @param {(sheet: string) => void} [input.onTabOpened] Runs only when the user
|
||||
* opens a sheet from its tab, never on close or programmatic presentation.
|
||||
* @param {(view: ?{enabled: boolean, sheet: string|null, tabs: typeof MOBILE_TABS}) => void} [input.publish]
|
||||
* Receives the tab bar: whether the shell is on, the open sheet and the
|
||||
* tabs; null once the shell is destroyed.
|
||||
@@ -131,7 +115,6 @@ export function initMobileShell({
|
||||
ResizeObserverImpl = globalThis.ResizeObserver,
|
||||
requestFrame = globalThis.requestAnimationFrame?.bind(globalThis),
|
||||
onSheetsClosed = () => {},
|
||||
onTabOpened = () => {},
|
||||
publish = () => {},
|
||||
afterPublish = (callback) => callback(),
|
||||
} = {}) {
|
||||
@@ -365,7 +348,6 @@ export function initMobileShell({
|
||||
// Closing from the tab bar returns focus to the tab that was pressed.
|
||||
if (!sheet) returnFocus = button;
|
||||
setSheet(sheet);
|
||||
if (sheet && currentSheetOf(body) === sheet) onTabOpened(sheet);
|
||||
});
|
||||
// Touch events let native scrolling continue until a downward pull at the
|
||||
// top is intentional. Pointer capture/touch-action:none would also seize
|
||||
|
||||
+11
-155
@@ -2,7 +2,6 @@ import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import { StyleManager } from './applicationShell.js';
|
||||
import { ContextControls } from './contextControls.js';
|
||||
import {
|
||||
MOBILE_SHEET_PANELS,
|
||||
MOBILE_TABS,
|
||||
@@ -10,7 +9,6 @@ import {
|
||||
nextSheet,
|
||||
sheetForPanelId,
|
||||
} from './mobileShell.js';
|
||||
import { withEntityRecord } from '../data/entityRecords.js';
|
||||
|
||||
function element(tag, document) {
|
||||
const node = new EventTarget();
|
||||
@@ -111,12 +109,7 @@ function element(tag, document) {
|
||||
|
||||
const PANEL_IDS = [...new Set(Object.values(MOBILE_SHEET_PANELS).flat())];
|
||||
|
||||
function fixture({
|
||||
mobile = true,
|
||||
expanded = [],
|
||||
onTabOpened = () => {},
|
||||
afterPublish,
|
||||
} = {}) {
|
||||
function fixture({ mobile = true, expanded = [], afterPublish } = {}) {
|
||||
const document = new EventTarget();
|
||||
document.ids = new Map();
|
||||
document.createElement = (tag) => element(tag, document);
|
||||
@@ -208,7 +201,6 @@ function fixture({
|
||||
}
|
||||
const shell = initMobileShell({
|
||||
documentRef: document,
|
||||
onTabOpened,
|
||||
publish,
|
||||
afterPublish,
|
||||
matchMedia: () => media,
|
||||
@@ -587,7 +579,9 @@ test('the phone shell keeps the required attribution visible', () => {
|
||||
};
|
||||
const lift = (block) =>
|
||||
Number(
|
||||
/bottom: calc\(var\(--mobile-tab-space\) \+ (\d+)px \+ var\(--world-timeline-lift, 0px\)\)/.exec(block)?.[1],
|
||||
/bottom: calc\(var\(--mobile-tab-space\) \+ (\d+)px \+ var\(--world-timeline-lift, 0px\)\)/.exec(
|
||||
block,
|
||||
)?.[1],
|
||||
);
|
||||
const z = (block) => Number(/z-index: (\d+);/.exec(block)?.[1]);
|
||||
const idleCredit = rule(
|
||||
@@ -803,157 +797,19 @@ test('touches outside the active sheet and destroyed listeners cannot dismiss or
|
||||
assert.equal(shell.getSheet(), null);
|
||||
});
|
||||
|
||||
test('the tab-open callback reports only a successful manual opening', () => {
|
||||
const opened = [];
|
||||
const phone = fixture({ onTabOpened: (sheet) => opened.push(sheet) });
|
||||
phone.shell.setSheet('context');
|
||||
assert.deepEqual(opened, []);
|
||||
phone.press('context');
|
||||
assert.deepEqual(opened, [], 'closing is not a new context request');
|
||||
phone.press('context');
|
||||
assert.deepEqual(opened, ['context']);
|
||||
phone.setBodyClass('cockpit-mode');
|
||||
test('opening the Context tab only presents its panel and starts no Context mode', () => {
|
||||
const phone = fixture();
|
||||
phone.press('context');
|
||||
assert.equal(phone.shell.getSheet(), 'context');
|
||||
assert.deepEqual(
|
||||
opened,
|
||||
['context'],
|
||||
'blocked sheets cannot activate a mode',
|
||||
phone.calls.map(({ panelId, collapsed }) => ({ panelId, collapsed })),
|
||||
[{ panelId: 'global-context-panel', collapsed: false }],
|
||||
);
|
||||
// The application shell no longer starts Contacts when the tab opens.
|
||||
assert.equal(StyleManager.prototype._onMobileTabOpened, undefined);
|
||||
phone.shell.destroy();
|
||||
});
|
||||
|
||||
test('manual Context opens the existing transaction without disabling the tracked aircraft', async () => {
|
||||
const calls = [];
|
||||
const tracked = { layerId: 'flights', icao24: 'abc123', callsign: 'EJA225' };
|
||||
const viewer = { trackedEntity: withEntityRecord({}, { trackedId: 'flights:abc123' }) };
|
||||
const entity = viewer.trackedEntity;
|
||||
const enabled = new Set(['flights', 'weather']);
|
||||
const controls = new ContextControls({
|
||||
elements: {},
|
||||
installations: {},
|
||||
actions: {
|
||||
getCockpit: () => null,
|
||||
claimVisualAuthority: () => calls.push('claim'),
|
||||
syncDetection() {},
|
||||
scheduleLayout() {},
|
||||
showToast() {},
|
||||
},
|
||||
});
|
||||
controls.connect({
|
||||
layers: new Map(
|
||||
['flights', 'weather', 'military-awareness'].map((id) => [id, {}]),
|
||||
),
|
||||
getEnabledLayerIds: () => [...enabled],
|
||||
getLayerParams: () => ({}),
|
||||
isEffectivelyEnabled: (id) => enabled.has(id),
|
||||
isEnabled: (id) => enabled.has(id),
|
||||
setLayerParams: (id, params) => calls.push({ id, params }),
|
||||
setEnabled: async (id, value) => {
|
||||
calls.push({ id, value });
|
||||
if (!value) enabled.delete(id);
|
||||
if (id === 'flights' && !value) viewer.trackedEntity = null;
|
||||
return true;
|
||||
},
|
||||
_setEnabledWithIntent: (id, value) => {
|
||||
calls.push({ id, value });
|
||||
enabled.add(id);
|
||||
return { intentEpoch: 1, promise: Promise.resolve(true) };
|
||||
},
|
||||
});
|
||||
const shell = {
|
||||
cockpitView: {
|
||||
readAircraftInfo: () => (viewer.trackedEntity ? tracked : null),
|
||||
},
|
||||
getAircraftTrackingTarget: StyleManager.prototype.getAircraftTrackingTarget,
|
||||
getContextModeState: () => controls.getContextModeState(),
|
||||
setContextMode: (mode) => controls.setContextMode(mode),
|
||||
_showToast: () => assert.fail('successful entry must not report a failure'),
|
||||
};
|
||||
try {
|
||||
assert.equal(
|
||||
await StyleManager.prototype._onMobileTabOpened.call(shell, 'context'),
|
||||
true,
|
||||
);
|
||||
assert.equal(controls.getContextModeState().mode, 'flights');
|
||||
assert.equal(viewer.trackedEntity, entity);
|
||||
assert.deepEqual(shell.getAircraftTrackingTarget(), {
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
});
|
||||
assert.ok(enabled.has('flights'));
|
||||
assert.ok(
|
||||
calls.some(
|
||||
(call) => call.id === 'military-awareness' && call.value === true,
|
||||
),
|
||||
);
|
||||
assert.ok(!calls.some((call) => call.id === 'flights'));
|
||||
const count = calls.length;
|
||||
assert.equal(
|
||||
await StyleManager.prototype._onMobileTabOpened.call(shell, 'context'),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
calls.length,
|
||||
count,
|
||||
'an already active Contacts session is not restarted',
|
||||
);
|
||||
} finally {
|
||||
controls.stop();
|
||||
controls.disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('manual Context respects an active mode, busy transitions, missing tracks and disposal', async () => {
|
||||
for (const state of [
|
||||
{ mode: 'flights' },
|
||||
{ changing: true },
|
||||
{ entering: 'flights' },
|
||||
{ noTrack: true },
|
||||
{ disposed: true },
|
||||
{ sheet: 'layers' },
|
||||
]) {
|
||||
const shell = {
|
||||
_disposed: state.disposed,
|
||||
getContextModeState: () => state,
|
||||
getAircraftTrackingTarget: () =>
|
||||
state.noTrack ? null : { layerId: 'flights', id: 'abc123' },
|
||||
setContextMode: () =>
|
||||
assert.fail('guarded tab must not mutate Context or tracking'),
|
||||
};
|
||||
assert.equal(
|
||||
await StyleManager.prototype._onMobileTabOpened.call(
|
||||
shell,
|
||||
state.sheet || 'context',
|
||||
),
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('failed mobile Contacts entry uses the existing notice and cancelled/disposed entries stay quiet', async () => {
|
||||
for (const outcome of ['failure', 'throw', 'cancelled', 'disposed']) {
|
||||
const notices = [];
|
||||
const shell = {
|
||||
getContextModeState: () => ({ mode: null }),
|
||||
getAircraftTrackingTarget: () => ({ layerId: 'flights', id: 'abc123' }),
|
||||
setContextMode: async () => {
|
||||
if (outcome === 'throw') throw new Error('source unavailable');
|
||||
if (outcome === 'disposed') shell._disposed = true;
|
||||
return { ok: false, cancelled: outcome === 'cancelled' };
|
||||
},
|
||||
_showToast: (message) => notices.push(message),
|
||||
};
|
||||
assert.equal(
|
||||
await StyleManager.prototype._onMobileTabOpened.call(shell, 'context'),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
notices.length,
|
||||
['failure', 'throw'].includes(outcome) ? 1 : 0,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a slow downward pull is claimed before Android native scroll takes ownership', () => {
|
||||
const { document, shell, press } = fixture();
|
||||
press('layers');
|
||||
|
||||
@@ -20,6 +20,10 @@ export const useCctvStore = defineStore('gev-cctv', () => {
|
||||
|
||||
/** The preview: requested and shown frame, loading and error state. */
|
||||
const frame = shallowRef(null);
|
||||
/** Number of camera cards outside the panel showing its preview, including Context's card. */
|
||||
const previewCards = shallowRef(0);
|
||||
/** Number of open bigger views of a camera card (popups over the map). */
|
||||
const previewPopups = shallowRef(0);
|
||||
/** Whether the live video surface replaces the still frame. */
|
||||
const live = shallowRef(false);
|
||||
/** `{label, state}` for the source badge; null until first synced. */
|
||||
@@ -49,6 +53,16 @@ export const useCctvStore = defineStore('gev-cctv', () => {
|
||||
frame.value = markRaw(next);
|
||||
}
|
||||
|
||||
/** @param {boolean} shown */
|
||||
function showPreviewCard(shown) {
|
||||
previewCards.value = Math.max(0, previewCards.value + (shown ? 1 : -1));
|
||||
}
|
||||
|
||||
/** @param {boolean} shown */
|
||||
function showPreviewPopup(shown) {
|
||||
previewPopups.value = Math.max(0, previewPopups.value + (shown ? 1 : -1));
|
||||
}
|
||||
|
||||
/** @param {boolean} on */
|
||||
function setLive(on) {
|
||||
live.value = Boolean(on);
|
||||
@@ -73,6 +87,8 @@ export const useCctvStore = defineStore('gev-cctv', () => {
|
||||
view,
|
||||
calEdit,
|
||||
frame,
|
||||
previewCards,
|
||||
previewPopups,
|
||||
live,
|
||||
sourceBadge,
|
||||
summary,
|
||||
@@ -80,6 +96,8 @@ export const useCctvStore = defineStore('gev-cctv', () => {
|
||||
publish,
|
||||
setCalEdit,
|
||||
setFrame,
|
||||
showPreviewCard,
|
||||
showPreviewPopup,
|
||||
setLive,
|
||||
setSourceBadge,
|
||||
setSummary,
|
||||
|
||||
@@ -357,6 +357,13 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
|
||||
* @param {boolean} [options.fly] Also fly the camera to it.
|
||||
* @returns {boolean} Whether a card could be made.
|
||||
*/
|
||||
/**
|
||||
* Counts card selections and clears, so a selection that was asked for
|
||||
* before a newer one can tell it came too late.
|
||||
*/
|
||||
let generation = 0;
|
||||
const selectionGeneration = () => generation;
|
||||
|
||||
/** Things that move are followed as soon as they are picked. */
|
||||
const AUTO_FOLLOW = new Set(['flights', 'military', 'satellites']);
|
||||
/**
|
||||
@@ -374,6 +381,7 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
|
||||
*/
|
||||
function select(identity, { fly = false, follow: autoFollow = true } = {}) {
|
||||
if (!read(identity)) return false;
|
||||
generation++;
|
||||
stopLocating();
|
||||
away.value = false;
|
||||
reference =
|
||||
@@ -403,6 +411,7 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
|
||||
}
|
||||
|
||||
function clear() {
|
||||
generation++;
|
||||
if (following.value) shell.value?.letGo?.(card.value);
|
||||
following.value = null;
|
||||
asked = null;
|
||||
@@ -451,6 +460,7 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
|
||||
locate,
|
||||
connect,
|
||||
select,
|
||||
selectionGeneration,
|
||||
clear,
|
||||
refresh,
|
||||
flyTo,
|
||||
@@ -477,3 +487,33 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
|
||||
askAboutView,
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Opens what a voice or chat action selected in the Context panel, as a click
|
||||
* on it does (`src/ui/entityContextBridge.js` selects the same way): its card
|
||||
* opens, and the panel with it. The app hands it to voice, which reads
|
||||
* `generation()` when a selection is asked and passes it back as `since`.
|
||||
* The action has already selected or followed the item in its own layer, so
|
||||
* the card does not follow it again (a click on a flight does not either). A
|
||||
* card picked or cleared since the action was asked stays, and nothing opens
|
||||
* in Cockpit, where Context is hidden.
|
||||
* @param {import('pinia').Pinia} pinia
|
||||
* @returns {{generation: () => number, show: (identity: {layerId: string, id: string|number, label?: string, lat?: number, lon?: number}, options?: {since?: number|null, cockpitActive?: boolean}) => boolean}}
|
||||
*/
|
||||
export function createContextCardOpener(pinia) {
|
||||
const store = () => useEntityCardStore(pinia);
|
||||
return {
|
||||
generation: () => store().selectionGeneration(),
|
||||
show(identity, { since = null, cockpitActive = false } = {}) {
|
||||
if (!identity?.layerId || identity.id == null || identity.id === '')
|
||||
return false;
|
||||
if (cockpitActive) return false;
|
||||
if (since !== null && store().selectionGeneration() !== since)
|
||||
return false;
|
||||
return store().select(
|
||||
{ ...identity, id: String(identity.id) },
|
||||
{ follow: false },
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -28,8 +28,20 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(
|
||||
.hud-readout:has(> #hud-mode) {
|
||||
display: none;
|
||||
}
|
||||
/* The globe actions sit on the title row, level with the title, with the
|
||||
loading line under them (status.css). Narrower, where the row would reach
|
||||
the title, they drop to the HUD's top rows and the loading line drops
|
||||
with them, so it never covers the actions. */
|
||||
#top-center-actions {
|
||||
top: clamp(86px, 9.55vh, 108px);
|
||||
top: 32px;
|
||||
}
|
||||
@media (max-width: 1179px) {
|
||||
#top-center-actions {
|
||||
top: clamp(86px, 9.55vh, 108px);
|
||||
}
|
||||
#global-loading-status {
|
||||
top: calc(clamp(86px, 9.55vh, 108px) + 42px);
|
||||
}
|
||||
}
|
||||
#left-panel-stack.layout-focus {
|
||||
bottom: var(--left-stack-safe-bottom, 4vh);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { t } from '../../../i18n/index.js';
|
||||
import { useCctvStore } from '../../stores/cctv.js';
|
||||
@@ -16,7 +16,8 @@ const props = defineProps({
|
||||
cameraId: { type: String, default: '' },
|
||||
});
|
||||
|
||||
const { view, frame, sourceBadge } = storeToRefs(useCctvStore());
|
||||
const cctv = useCctvStore();
|
||||
const { view, frame, sourceBadge } = storeToRefs(cctv);
|
||||
const chrome = usePanelChromeStore();
|
||||
const { panels } = storeToRefs(chrome);
|
||||
|
||||
@@ -53,11 +54,19 @@ const big = ref(false);
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape') big.value = false;
|
||||
};
|
||||
watch(big, (open) => {
|
||||
if (open) document.addEventListener('keydown', onKey);
|
||||
else document.removeEventListener('keydown', onKey);
|
||||
// The cleanup also runs when the card unmounts, even if `big` turned false in
|
||||
// the same tick and the watcher never saw it.
|
||||
watch(big, (open, _, onCleanup) => {
|
||||
if (!open) return;
|
||||
cctv.showPreviewPopup(true);
|
||||
document.addEventListener('keydown', onKey);
|
||||
onCleanup(() => {
|
||||
cctv.showPreviewPopup(false);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
});
|
||||
});
|
||||
onBeforeUnmount(() => document.removeEventListener('keydown', onKey));
|
||||
onMounted(() => cctv.showPreviewCard(true));
|
||||
onBeforeUnmount(() => cctv.showPreviewCard(false));
|
||||
|
||||
function openPanel() {
|
||||
if (panels.value['cctv-panel']?.collapsed !== false) chrome.act('toggle', 'cctv-panel');
|
||||
|
||||
+113
-73
@@ -1210,13 +1210,28 @@ export function createGevActionRunner({
|
||||
args.type ||
|
||||
args.filterType,
|
||||
);
|
||||
let contextChangedForEntry = false;
|
||||
let priorContextMode = null;
|
||||
let rollbackTarget = null;
|
||||
if (
|
||||
action === 'enter' &&
|
||||
typeof styleManager.setContextMode === 'function'
|
||||
) {
|
||||
// Entry changes no Context mode, layer or detection setting, as the
|
||||
// COCKPIT button does not. The one exception is a military entry while
|
||||
// Military Flights is off: that layer is switched on as a plain layer
|
||||
// the person can switch off, and switched off again if entry fails.
|
||||
// Contacts stays as it is.
|
||||
let rollbackTarget;
|
||||
let switchedOn = null;
|
||||
// A switch-off undoing this action's own switch-on; it runs even for a
|
||||
// turn that went stale, so a failed entry leaves no layer behind.
|
||||
const switchBackOff = async () => {
|
||||
if (!switchedOn) return null;
|
||||
return runGevAction(
|
||||
'set_layer_visibility',
|
||||
{ layerId: switchedOn, enabled: false },
|
||||
{},
|
||||
);
|
||||
};
|
||||
const failed = async (result) => {
|
||||
const layerRollback = await switchBackOff();
|
||||
return layerRollback ? { ...result, layerRollback } : result;
|
||||
};
|
||||
if (action === 'enter') {
|
||||
if (!current()) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -1227,51 +1242,37 @@ export function createGevActionRunner({
|
||||
};
|
||||
}
|
||||
rollbackTarget = styleManager.getAircraftTrackingTarget?.() || null;
|
||||
const contextState =
|
||||
typeof styleManager.getContextModeState === 'function'
|
||||
? styleManager.getContextModeState()
|
||||
: {};
|
||||
priorContextMode = contextState?.mode || null;
|
||||
const contactsReady =
|
||||
contextState?.mode === 'flights' &&
|
||||
contextState?.active !== false &&
|
||||
contextState?.changing !== true;
|
||||
if (!contactsReady) {
|
||||
const contextResult = await styleManager.setContextMode('flights', {
|
||||
signal: runOptions.signal,
|
||||
isCurrent: runOptions.isCurrent,
|
||||
// Cockpit entry establishes Contacts as its own precondition. That
|
||||
// is internal choreography, not an operator Context request, so it
|
||||
// must stay inert: claiming here would cancel a pending shared
|
||||
// style/detection restore the operator never overrode.
|
||||
claimVisualAuthority: false,
|
||||
});
|
||||
contextChangedForEntry = contextResult?.ok === true;
|
||||
if (contextResult?.ok !== true || !current()) {
|
||||
const contextRollback = contextChangedForEntry
|
||||
? await styleManager.setContextMode(priorContextMode, {
|
||||
claimVisualAuthority: false,
|
||||
})
|
||||
: null;
|
||||
return {
|
||||
if (
|
||||
targetLayer === 'military' &&
|
||||
dataManager.layers?.has?.('military') &&
|
||||
!dataManager.isEnabled?.('military')
|
||||
) {
|
||||
const layer = await runGevAction(
|
||||
'set_layer_visibility',
|
||||
{ layerId: 'military', enabled: true },
|
||||
runOptions,
|
||||
);
|
||||
if (layer?.ok === true) switchedOn = 'military';
|
||||
// The search needs the layer's aircraft, which arrive with its
|
||||
// first data, not with the switch.
|
||||
if (layer?.ok === true && current())
|
||||
await waitForLayerFirstData(dataManager, 'military', runOptions);
|
||||
if (layer?.ok !== true || !current()) {
|
||||
return failed({
|
||||
ok: false,
|
||||
action: 'control_cockpit',
|
||||
cancelled: !current() || Boolean(contextResult?.cancelled),
|
||||
cancelled: !current() || Boolean(layer?.cancelled),
|
||||
error:
|
||||
contextResult?.error ||
|
||||
'Contacts context could not be established for Cockpit entry',
|
||||
context: contextResult
|
||||
? withContextModeVocabulary(contextResult)
|
||||
: null,
|
||||
contextRollback: withContextModeVocabulary(contextRollback),
|
||||
layer?.error ||
|
||||
(layer?.ok === true
|
||||
? 'Cockpit entry was cancelled before it could run'
|
||||
: 'Military Flights could not be switched on'),
|
||||
layer,
|
||||
state: styleManager.getCockpitState?.() || null,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Contacts activation can adopt a newer explicit aircraft selection.
|
||||
// Sample only after that transaction settles so an older voice snapshot
|
||||
// cannot overwrite the operator's newer choice.
|
||||
const selectedTarget =
|
||||
action === 'enter' ? selectedCockpitTarget(dataManager) : null;
|
||||
let cockpitResult;
|
||||
@@ -1291,30 +1292,7 @@ export function createGevActionRunner({
|
||||
state: styleManager.getCockpitState?.() || null,
|
||||
};
|
||||
}
|
||||
if (
|
||||
action === 'enter' &&
|
||||
cockpitResult?.ok !== true &&
|
||||
contextChangedForEntry
|
||||
) {
|
||||
const contextRollback = await styleManager.setContextMode(
|
||||
priorContextMode,
|
||||
{
|
||||
// Undoing this action's own precondition — still choreography.
|
||||
claimVisualAuthority: false,
|
||||
...(current()
|
||||
? {
|
||||
signal: runOptions.signal,
|
||||
isCurrent: runOptions.isCurrent,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
return {
|
||||
...cockpitResult,
|
||||
contextRollback: withContextModeVocabulary(contextRollback),
|
||||
};
|
||||
}
|
||||
return cockpitResult;
|
||||
return cockpitResult?.ok === true ? cockpitResult : failed(cockpitResult);
|
||||
}
|
||||
|
||||
if (name === 'show_data_layers_menu') {
|
||||
@@ -2903,6 +2881,62 @@ export function formatTrackedEntityLabel(found, query = '') {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a layer just switched on to report its first data: its stats name
|
||||
* an update, or its next update lands. Bounded by that update, the layer
|
||||
* failing or going off, and the request's own cancellation.
|
||||
* @returns {Promise<boolean>} Whether the layer has reported data.
|
||||
*/
|
||||
function waitForLayerFirstData(
|
||||
dataManager,
|
||||
layerId,
|
||||
{ signal = null, isCurrent = null } = {},
|
||||
) {
|
||||
const reported = () => {
|
||||
try {
|
||||
const stats = dataManager.layers?.get?.(layerId)?.module?.getStats?.();
|
||||
return stats?.lastUpdate != null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
if (reported()) return Promise.resolve(true);
|
||||
if (typeof dataManager.subscribeActivity !== 'function' || signal?.aborted)
|
||||
return Promise.resolve(false);
|
||||
return new Promise((resolve) => {
|
||||
const offs = [];
|
||||
let settled = false;
|
||||
const done = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
for (const off of offs) off?.();
|
||||
resolve(value);
|
||||
};
|
||||
const onAbort = () => done(false);
|
||||
signal?.addEventListener?.('abort', onAbort, { once: true });
|
||||
offs.push(() => signal?.removeEventListener?.('abort', onAbort));
|
||||
offs.push(
|
||||
dataManager.subscribeActivity((change) => {
|
||||
if (
|
||||
!dataManager.isEnabled?.(layerId) ||
|
||||
(typeof isCurrent === 'function' && !isCurrent())
|
||||
)
|
||||
return done(false);
|
||||
if (reported()) return done(true);
|
||||
if (change?.type === 'data-updated' && change.layerId === layerId)
|
||||
done(reported());
|
||||
}),
|
||||
);
|
||||
offs.push(
|
||||
dataManager.subscribe?.((change) => {
|
||||
if (change?.layerId !== layerId) return;
|
||||
if (change.type === 'refresh-failed' || change.enabled === false)
|
||||
done(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Finds and tracks/selects an entity by spoken query across layer families. */
|
||||
async function trackEntity(
|
||||
viewer,
|
||||
@@ -3017,8 +3051,15 @@ async function trackEntity(
|
||||
'track_entity',
|
||||
() => {
|
||||
let trackedOk = false;
|
||||
// The id the layer selects by, which also names it in Context.
|
||||
const id =
|
||||
family.kind === 'vessel'
|
||||
? (found.id ?? found.mmsi)
|
||||
: family.kind === 'satellite'
|
||||
? found.noradId
|
||||
: found.icao24;
|
||||
if (family.kind === 'vessel') {
|
||||
trackedOk = !!module.selectById?.(found.id ?? found.mmsi);
|
||||
trackedOk = !!module.selectById?.(id);
|
||||
flyToLandmark(viewer, found.latitude, found.longitude, {
|
||||
range: 6000,
|
||||
pitch: -45,
|
||||
@@ -3026,10 +3067,8 @@ async function trackEntity(
|
||||
buildingHeight: 0,
|
||||
duration: 2.0,
|
||||
});
|
||||
} else if (family.kind === 'satellite') {
|
||||
trackedOk = !!module.trackById?.(found.noradId, { origin: 'voice' });
|
||||
} else {
|
||||
trackedOk = !!module.trackById?.(found.icao24, { origin: 'voice' });
|
||||
trackedOk = !!module.trackById?.(id, { origin: 'voice' });
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -3037,6 +3076,7 @@ async function trackEntity(
|
||||
action: 'track_entity',
|
||||
layerId: family.layerId,
|
||||
kind: family.kind,
|
||||
id: id == null ? null : String(id),
|
||||
// Aircraft follow the flight layers' label convention (callsign →
|
||||
// registration → icao24) so the spoken name matches what the UI shows;
|
||||
// `registration` is absent on vessels/satellites and simply falls
|
||||
|
||||
+270
-275
@@ -144,6 +144,9 @@ test('track_entity runner narrates a callsign-less aircraft by its registration'
|
||||
`${layerId} narration must speak the registration, not the ICAO hex`,
|
||||
);
|
||||
assert.equal(trackedId, 'ae1fa4', `${layerId} must still TRACK by icao24`);
|
||||
// The result names what it tracked, so Context can show it.
|
||||
assert.equal(result.id, 'ae1fa4');
|
||||
assert.equal(result.layerId, layerId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2974,7 +2977,7 @@ test('control_cockpit resolves spoken TR-3B spellings to the tr3b class id', asy
|
||||
}
|
||||
});
|
||||
|
||||
test('control_cockpit delegates selected-flight adoption to the canonical cockpit owner', async () => {
|
||||
test('control_cockpit delegates selected-flight adoption to the canonical cockpit owner and leaves Context alone', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
@@ -2995,16 +2998,7 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi
|
||||
changing: false,
|
||||
};
|
||||
},
|
||||
async setContextMode(mode) {
|
||||
calls.push({ action: 'context', mode });
|
||||
contextActive = mode === 'flights';
|
||||
return {
|
||||
ok: contextActive,
|
||||
mode,
|
||||
active: contextActive,
|
||||
changing: false,
|
||||
};
|
||||
},
|
||||
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
|
||||
controlCockpit(action, options) {
|
||||
calls.push({ action, selectedTarget: options.selectedTarget });
|
||||
return {
|
||||
@@ -3040,7 +3034,6 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi
|
||||
const result = await runner('control_cockpit', { action: 'enter' });
|
||||
assert.equal(result.ok, true);
|
||||
assert.deepEqual(calls, [
|
||||
{ action: 'context', mode: 'flights' },
|
||||
{
|
||||
action: 'enter',
|
||||
selectedTarget: { layerId: 'flights', id: 'abc123' },
|
||||
@@ -3048,46 +3041,6 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi
|
||||
]);
|
||||
});
|
||||
|
||||
test('control_cockpit does not mutate selection when Contacts entry fails', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
const styleManager = {
|
||||
getContextModeState: () => ({ mode: null, active: false, changing: false }),
|
||||
setContextMode: async () => ({
|
||||
ok: false,
|
||||
mode: null,
|
||||
active: false,
|
||||
changing: false,
|
||||
error: 'Contacts activation failed',
|
||||
}),
|
||||
controlCockpit: () =>
|
||||
assert.fail('Cockpit must not run after failed Contacts entry'),
|
||||
getCockpitState: () => ({ active: false }),
|
||||
};
|
||||
const viewer = {
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
};
|
||||
const runner = createGevActionRunner({
|
||||
viewer,
|
||||
styleManager,
|
||||
dataManager: {
|
||||
layers: new Map(),
|
||||
isEnabled: () => false,
|
||||
getAll: () => [],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await runner('control_cockpit', { action: 'enter' });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.error, 'Contacts activation failed');
|
||||
assert.deepEqual(result.state, { active: false });
|
||||
});
|
||||
|
||||
test('control_cockpit cancellation is inert when Contacts is already active', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
@@ -3134,77 +3087,7 @@ test('control_cockpit cancellation is inert when Contacts is already active', as
|
||||
assert.deepEqual(result.state, { active: false });
|
||||
});
|
||||
|
||||
test('control_cockpit rolls Contacts back when the turn becomes stale at commit', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
const calls = [];
|
||||
let requestCurrent = true;
|
||||
let contextMode = null;
|
||||
const styleManager = {
|
||||
getContextModeState: () => ({
|
||||
mode: contextMode,
|
||||
active: Boolean(contextMode),
|
||||
changing: false,
|
||||
}),
|
||||
async setContextMode(mode, options) {
|
||||
calls.push({ mode, options: options || null });
|
||||
contextMode = mode;
|
||||
if (mode === 'flights') requestCurrent = false;
|
||||
return { ok: true, mode, active: Boolean(mode), changing: false };
|
||||
},
|
||||
controlCockpit: () => assert.fail('stale turn must not enter Cockpit'),
|
||||
getCockpitState: () => ({ active: false }),
|
||||
};
|
||||
const viewer = {
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
};
|
||||
const runner = createGevActionRunner({
|
||||
viewer,
|
||||
styleManager,
|
||||
dataManager: {
|
||||
layers: new Map(),
|
||||
isEnabled: () => false,
|
||||
getAll: () => [],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await runner(
|
||||
'control_cockpit',
|
||||
{ action: 'enter' },
|
||||
{
|
||||
isCurrent: () => requestCurrent,
|
||||
},
|
||||
);
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.cancelled, true);
|
||||
assert.equal(contextMode, null);
|
||||
assert.deepEqual(
|
||||
calls.map(({ mode }) => mode),
|
||||
['flights', null],
|
||||
);
|
||||
assert.equal(
|
||||
calls[1].options?.signal ?? null,
|
||||
null,
|
||||
'rollback must not inherit stale cancellation authority',
|
||||
);
|
||||
assert.equal(
|
||||
calls[1].options?.isCurrent ?? null,
|
||||
null,
|
||||
'rollback must not inherit a stale currency probe',
|
||||
);
|
||||
assert.equal(
|
||||
calls[1].options?.claimVisualAuthority,
|
||||
false,
|
||||
'rollback is cockpit choreography and must not claim the visual lane',
|
||||
);
|
||||
});
|
||||
|
||||
test('control_cockpit adopts the newest selection after Contacts settles', async () => {
|
||||
test('control_cockpit enters on the current selection and keeps the prior track for rollback', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
@@ -3229,16 +3112,15 @@ test('control_cockpit adopts the newest selection after Contacts settles', async
|
||||
);
|
||||
contextStore.selectedEntityId = first.id;
|
||||
contextStore.selectedAt = Date.now();
|
||||
// A newer selection before the turn runs is the one entered.
|
||||
contextStore.selectedEntityId = second.id;
|
||||
contextStore.selectedAt = Date.now();
|
||||
let receivedTarget = null;
|
||||
let receivedRollbackTarget = null;
|
||||
const styleManager = {
|
||||
getAircraftTrackingTarget: () => ({ layerId: 'military', id: 'prior' }),
|
||||
getContextModeState: () => ({ mode: null, active: false, changing: false }),
|
||||
async setContextMode() {
|
||||
contextStore.selectedEntityId = second.id;
|
||||
contextStore.selectedAt = Date.now();
|
||||
return { ok: true, mode: 'flights', active: true, changing: false };
|
||||
},
|
||||
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
|
||||
controlCockpit(_action, options) {
|
||||
receivedTarget = options.selectedTarget;
|
||||
receivedRollbackTarget = options.rollbackTarget;
|
||||
@@ -3277,25 +3159,16 @@ test('control_cockpit adopts the newest selection after Contacts settles', async
|
||||
});
|
||||
});
|
||||
|
||||
test('control_cockpit restores the prior Context mode after Cockpit entry fails', async () => {
|
||||
test('a failed voice Cockpit entry leaves the Context mode as it was', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
const calls = [];
|
||||
let contextMode = null;
|
||||
const styleManager = {
|
||||
getContextModeState: () => ({
|
||||
mode: contextMode,
|
||||
active: Boolean(contextMode),
|
||||
changing: false,
|
||||
}),
|
||||
async setContextMode(mode) {
|
||||
contextMode = mode;
|
||||
calls.push(`context:${mode || 'off'}`);
|
||||
return { ok: true, mode, active: Boolean(mode), changing: false };
|
||||
},
|
||||
getContextModeState: () => ({ mode: null, active: false, changing: false }),
|
||||
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
|
||||
controlCockpit() {
|
||||
calls.push('cockpit:enter');
|
||||
return {
|
||||
@@ -3322,31 +3195,21 @@ test('control_cockpit restores the prior Context mode after Cockpit entry fails'
|
||||
|
||||
const result = await runner('control_cockpit', { action: 'enter' });
|
||||
assert.equal(result.ok, false);
|
||||
assert.deepEqual(calls, ['context:flights', 'cockpit:enter', 'context:off']);
|
||||
assert.equal(contextMode, null);
|
||||
assert.equal(result.contextRollback.ok, true);
|
||||
assert.equal(result.error, 'Cockpit entry was unavailable');
|
||||
assert.deepEqual(calls, ['cockpit:enter']);
|
||||
assert.equal(result.contextRollback, undefined);
|
||||
});
|
||||
|
||||
test('control_cockpit contains entry exceptions and still restores the prior Context mode', async () => {
|
||||
test('control_cockpit contains entry exceptions and passes the prior track for rollback', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
const calls = [];
|
||||
let contextMode = null;
|
||||
const styleManager = {
|
||||
getAircraftTrackingTarget: () => ({ layerId: 'military', id: 'prior' }),
|
||||
getContextModeState: () => ({
|
||||
mode: contextMode,
|
||||
active: Boolean(contextMode),
|
||||
changing: false,
|
||||
}),
|
||||
async setContextMode(mode) {
|
||||
contextMode = mode;
|
||||
calls.push(`context:${mode || 'off'}`);
|
||||
return { ok: true, mode, active: Boolean(mode), changing: false };
|
||||
},
|
||||
getContextModeState: () => ({ mode: null, active: false, changing: false }),
|
||||
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
|
||||
controlCockpit(_action, options) {
|
||||
calls.push(['cockpit:enter', options.rollbackTarget]);
|
||||
throw new Error('entry exploded');
|
||||
@@ -3371,15 +3234,11 @@ test('control_cockpit contains entry exceptions and still restores the prior Con
|
||||
const result = await runner('control_cockpit', { action: 'enter' });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.error, 'entry exploded');
|
||||
assert.equal(result.contextRollback.ok, true);
|
||||
assert.equal(contextMode, null);
|
||||
assert.deepEqual(result.state, { active: false });
|
||||
assert.deepEqual(calls, [
|
||||
'context:flights',
|
||||
['cockpit:enter', { layerId: 'military', id: 'prior' }],
|
||||
'context:off',
|
||||
]);
|
||||
});
|
||||
|
||||
test('set_context_mode forwards cancellation authority and reports a stale turn', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
@@ -3538,11 +3397,7 @@ test('control_cockpit enter skips selected non-flight context', async () => {
|
||||
active: contextActive,
|
||||
changing: false,
|
||||
}),
|
||||
async setContextMode(mode) {
|
||||
contextActive = mode === 'flights';
|
||||
calls.push(`context:${mode}`);
|
||||
return { ok: true, mode, active: true, changing: false };
|
||||
},
|
||||
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
|
||||
controlCockpit(action) {
|
||||
calls.push(`cockpit:${action}`);
|
||||
return {
|
||||
@@ -3577,7 +3432,7 @@ test('control_cockpit enter skips selected non-flight context', async () => {
|
||||
|
||||
const result = await runner('control_cockpit', { action: 'enter' });
|
||||
assert.equal(result.ok, true);
|
||||
assert.deepEqual(calls, ['context:flights', 'cockpit:enter']);
|
||||
assert.deepEqual(calls, ['cockpit:enter']);
|
||||
});
|
||||
|
||||
test('voice CCTV select, next, prev, and nearest report tracking-refused flights after selection', async () => {
|
||||
@@ -4543,6 +4398,66 @@ test('voice Radio Pause while disabled is a truthful playback-only no-op', async
|
||||
// THE TWO APART, which a claim-count-only assertion cannot.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('voice Cockpit entry, entered or failed, never changes the Context mode', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
for (const entered of [true, false]) {
|
||||
const calls = [];
|
||||
const styleManager = {
|
||||
getContextModeState: () => ({
|
||||
mode: null,
|
||||
active: false,
|
||||
changing: false,
|
||||
}),
|
||||
setPanelCollapsed() {},
|
||||
setContextMode: async (mode) => {
|
||||
calls.push(mode);
|
||||
return { ok: true, mode, active: true };
|
||||
},
|
||||
controlCockpit: async () =>
|
||||
entered
|
||||
? { ok: true, action: 'control_cockpit', state: { active: true } }
|
||||
: {
|
||||
ok: false,
|
||||
action: 'control_cockpit',
|
||||
error: 'entry failed',
|
||||
state: { active: false },
|
||||
},
|
||||
getCockpitState: () => ({ active: false }),
|
||||
getAircraftTrackingTarget: () => null,
|
||||
};
|
||||
const layerCalls = [];
|
||||
const viewer = {
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
};
|
||||
const runner = createGevActionRunner({
|
||||
viewer,
|
||||
styleManager,
|
||||
dataManager: {
|
||||
layers: new Map([
|
||||
['flights', { module: {} }],
|
||||
['military', { module: {} }],
|
||||
]),
|
||||
isEnabled: (layerId) => layerId === 'flights',
|
||||
setEnabled: async (...args) => {
|
||||
layerCalls.push(args);
|
||||
return true;
|
||||
},
|
||||
getAll: () => [],
|
||||
},
|
||||
});
|
||||
const result = await runner('control_cockpit', { action: 'enter' });
|
||||
assert.equal(result.ok, entered);
|
||||
assert.deepEqual(calls, [], 'no Context mode change');
|
||||
assert.deepEqual(layerCalls, [], 'no layer change');
|
||||
}
|
||||
});
|
||||
|
||||
function contextClaimProbe({
|
||||
entrySucceeds = true,
|
||||
cockpitSucceeds = true,
|
||||
@@ -4591,48 +4506,6 @@ function contextClaimProbe({
|
||||
return { runner, calls };
|
||||
}
|
||||
|
||||
test('Cockpit entry establishes Contacts WITHOUT claiming the visual lane', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
const probe = contextClaimProbe();
|
||||
await probe.runner('control_cockpit', { action: 'enter' });
|
||||
|
||||
assert.ok(probe.calls.length >= 1, 'Cockpit entry must establish Contacts');
|
||||
for (const call of probe.calls) {
|
||||
assert.equal(
|
||||
call.claimVisualAuthority,
|
||||
false,
|
||||
`cockpit choreography must not claim (mode=${call.mode})`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('Cockpit entry rollback also stays inert on the visual lane', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
const probe = contextClaimProbe({ cockpitSucceeds: false });
|
||||
await probe.runner('control_cockpit', { action: 'enter' });
|
||||
|
||||
// Establish + roll back: BOTH are this action's own choreography.
|
||||
assert.ok(
|
||||
probe.calls.length >= 2,
|
||||
`expected an entry and a rollback, saw ${probe.calls.length}`,
|
||||
);
|
||||
for (const call of probe.calls) {
|
||||
assert.equal(
|
||||
call.claimVisualAuthority,
|
||||
false,
|
||||
`rollback must not claim (mode=${call.mode})`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a genuine set_context_mode request DOES claim the visual lane', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
@@ -5083,71 +4956,6 @@ test('an absent secondary mode stays absent instead of claiming to be off', asyn
|
||||
);
|
||||
});
|
||||
|
||||
test('a nested Cockpit rollback result is translated too', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
// The prior mode is Contacts, whose INTERNAL id is 'flights' — the id that
|
||||
// must not reach the model. `active: false` keeps Contacts from reading as
|
||||
// ready, so entry runs and the failed Cockpit rolls back to it.
|
||||
let contextMode = 'flights';
|
||||
const styleManager = {
|
||||
getContextModeState: () => ({
|
||||
mode: contextMode,
|
||||
active: false,
|
||||
changing: false,
|
||||
}),
|
||||
getCockpitState: () => ({ active: false }),
|
||||
getAircraftTrackingTarget: () => null,
|
||||
async setContextMode(mode) {
|
||||
// Entry to Contacts succeeds; Cockpit then fails and the prior mode is
|
||||
// rolled back — the rollback result is what the model reads.
|
||||
contextMode = mode;
|
||||
return {
|
||||
ok: true,
|
||||
action: 'set_context_mode',
|
||||
mode,
|
||||
active: true,
|
||||
changing: false,
|
||||
};
|
||||
},
|
||||
controlCockpit: () => ({
|
||||
ok: false,
|
||||
error: 'Cockpit entry failed',
|
||||
state: { active: false },
|
||||
}),
|
||||
};
|
||||
const viewer = {
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
};
|
||||
const runner = createGevActionRunner({
|
||||
viewer,
|
||||
styleManager,
|
||||
dataManager: {
|
||||
layers: new Map(),
|
||||
isEnabled: () => false,
|
||||
getAll: () => [],
|
||||
},
|
||||
});
|
||||
const result = await runner('control_cockpit', { action: 'enter' });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(
|
||||
result.contextRollback?.mode,
|
||||
'contacts',
|
||||
'the rollback names the mode the tools name',
|
||||
);
|
||||
assert.equal(result.contextRollback?.modeInternal, 'flights');
|
||||
assert.doesNotMatch(
|
||||
JSON.stringify(result.contextRollback || {}),
|
||||
/"mode":"flights"/,
|
||||
'a nested rollback result must not leak the internal id either',
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Front 5 (owner's live trial, 2026-08-22 01:42-01:44). Contacts was active
|
||||
* with contact N546PC as its subject, a DATACENTER sat in the recency slot,
|
||||
@@ -5294,7 +5102,6 @@ function analystRunner(awareness, { getAll } = {}) {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
test('front5: a nearby ask centres on the Contacts SUBJECT, not the selected datacenter', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
@@ -8954,3 +8761,191 @@ test('show_street_level shows every photo it opens, also over a panel the user h
|
||||
});
|
||||
assert.deepEqual(missing.revealed, [], 'nothing opened, nothing revealed');
|
||||
});
|
||||
|
||||
test('a military voice Cockpit entry switches Military Flights on as a plain layer, never Contacts', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
for (const militaryOn of [false, true]) {
|
||||
const enabled = new Set(militaryOn ? ['flights', 'military'] : ['flights']);
|
||||
const layerCalls = [];
|
||||
const entries = [];
|
||||
const styleManager = {
|
||||
getContextModeState: () => ({
|
||||
mode: null,
|
||||
active: false,
|
||||
changing: false,
|
||||
}),
|
||||
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
|
||||
setDetection: () => assert.fail('Cockpit entry must not touch detection'),
|
||||
controlCockpit(action, options) {
|
||||
entries.push([action, options.targetLayer, options.aircraftClass]);
|
||||
return { ok: true, action: 'control_cockpit', state: { active: true } };
|
||||
},
|
||||
getCockpitState: () => ({ active: false }),
|
||||
getAircraftTrackingTarget: () => ({ layerId: 'flights', id: 'civil' }),
|
||||
};
|
||||
const viewer = {
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
};
|
||||
const runner = createGevActionRunner({
|
||||
viewer,
|
||||
styleManager,
|
||||
dataManager: {
|
||||
layers: new Map([
|
||||
['flights', { module: {} }],
|
||||
['military', { module: {} }],
|
||||
]),
|
||||
isEnabled: (layerId) => enabled.has(layerId),
|
||||
async setEnabled(layerId, on, options) {
|
||||
layerCalls.push([layerId, on, options.origin]);
|
||||
if (on) enabled.add(layerId);
|
||||
return true;
|
||||
},
|
||||
getAll: () => [],
|
||||
},
|
||||
});
|
||||
const result = await runner('control_cockpit', {
|
||||
action: 'enter',
|
||||
targetLayer: 'military',
|
||||
aircraftClass: 'helicopter',
|
||||
});
|
||||
assert.equal(result.ok, true, result.error);
|
||||
assert.deepEqual(
|
||||
layerCalls,
|
||||
militaryOn ? [] : [['military', true, 'voice']],
|
||||
'only a Military Flights layer that is off is switched on',
|
||||
);
|
||||
assert.deepEqual(entries, [['enter', 'military', 'helicopter']]);
|
||||
}
|
||||
});
|
||||
|
||||
// A data manager whose Military Flights layer is off, switches on empty and
|
||||
// reports its first data only when the test lands it.
|
||||
function militaryOffManager({ militaryOn = false } = {}) {
|
||||
const enabled = new Set(militaryOn ? ['flights', 'military'] : ['flights']);
|
||||
const activity = new Set();
|
||||
const layerCalls = [];
|
||||
let lastUpdate = militaryOn ? 1 : null;
|
||||
const manager = {
|
||||
layers: new Map([
|
||||
['flights', { module: {} }],
|
||||
['military', { module: { getStats: () => ({ lastUpdate }) } }],
|
||||
]),
|
||||
isEnabled: (layerId) => enabled.has(layerId),
|
||||
async setEnabled(layerId, on, options) {
|
||||
layerCalls.push([layerId, on, options.origin]);
|
||||
if (on) enabled.add(layerId);
|
||||
else enabled.delete(layerId);
|
||||
return true;
|
||||
},
|
||||
subscribeActivity(callback) {
|
||||
activity.add(callback);
|
||||
return () => activity.delete(callback);
|
||||
},
|
||||
getAll: () => [],
|
||||
};
|
||||
return {
|
||||
manager,
|
||||
layerCalls,
|
||||
enabled,
|
||||
listening: () => activity.size,
|
||||
landFirstData() {
|
||||
lastUpdate = 2;
|
||||
for (const callback of [...activity])
|
||||
callback({ type: 'data-updated', layerId: 'military' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function militaryEntryRunner(manager, controlCockpit) {
|
||||
return createGevActionRunner({
|
||||
viewer: {
|
||||
clock: { onTick: { addEventListener: () => () => {} } },
|
||||
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
|
||||
camera: { moveEnd: { addEventListener() {} } },
|
||||
},
|
||||
styleManager: {
|
||||
getContextModeState: () => ({
|
||||
mode: null,
|
||||
active: false,
|
||||
changing: false,
|
||||
}),
|
||||
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
|
||||
controlCockpit,
|
||||
getCockpitState: () => ({ active: false }),
|
||||
getAircraftTrackingTarget: () => ({ layerId: 'flights', id: 'civil' }),
|
||||
},
|
||||
dataManager: manager,
|
||||
});
|
||||
}
|
||||
|
||||
test('a military voice entry waits for a just-switched-on layer to report its first data', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
const fixture = militaryOffManager();
|
||||
let searchedWithData = null;
|
||||
const runner = militaryEntryRunner(fixture.manager, () => {
|
||||
searchedWithData =
|
||||
fixture.manager.layers.get('military').module.getStats().lastUpdate !==
|
||||
null;
|
||||
return { ok: true, action: 'control_cockpit', state: { active: true } };
|
||||
});
|
||||
const pending = runner('control_cockpit', {
|
||||
action: 'enter',
|
||||
targetLayer: 'military',
|
||||
aircraftClass: 'helicopter',
|
||||
});
|
||||
for (let i = 0; i < 10; i++) await Promise.resolve();
|
||||
assert.equal(searchedWithData, null, 'no search on an empty layer');
|
||||
assert.equal(fixture.listening(), 1);
|
||||
fixture.landFirstData();
|
||||
const result = await pending;
|
||||
assert.equal(result.ok, true, result.error);
|
||||
assert.equal(searchedWithData, true);
|
||||
assert.equal(fixture.listening(), 0, 'the wait lets go of the layer');
|
||||
});
|
||||
|
||||
test('a failed military voice entry switches off only the layer it switched on', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
for (const militaryOn of [false, true]) {
|
||||
const fixture = militaryOffManager({ militaryOn });
|
||||
const runner = militaryEntryRunner(fixture.manager, () => ({
|
||||
ok: false,
|
||||
action: 'control_cockpit',
|
||||
error: 'No helicopter military contact is available to enter',
|
||||
state: { active: false },
|
||||
}));
|
||||
const pending = runner('control_cockpit', {
|
||||
action: 'enter',
|
||||
targetLayer: 'military',
|
||||
aircraftClass: 'helicopter',
|
||||
});
|
||||
for (let i = 0; i < 10; i++) await Promise.resolve();
|
||||
if (!militaryOn) fixture.landFirstData();
|
||||
const result = await pending;
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.error, /No helicopter military contact/);
|
||||
assert.deepEqual(
|
||||
fixture.layerCalls,
|
||||
militaryOn
|
||||
? []
|
||||
: [
|
||||
['military', true, 'voice'],
|
||||
['military', false, 'voice'],
|
||||
],
|
||||
);
|
||||
assert.equal(fixture.enabled.has('military'), militaryOn);
|
||||
}
|
||||
});
|
||||
@@ -5,6 +5,11 @@ import { readFileSync } from 'node:fs';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createVoiceControl } from '../control.js';
|
||||
import { useVoiceStore } from '../../ui/stores/voice.js';
|
||||
import {
|
||||
createContextCardOpener,
|
||||
useEntityCardStore,
|
||||
} from '../../ui/stores/entityCard.js';
|
||||
import { applicationPinia } from '../../ui/vueRuntime.js';
|
||||
import { createGevActionRunner } from '../gevActions.js';
|
||||
import { createVoiceCommands as bind } from '../sessionCommands.js';
|
||||
import { createVoiceCommands as compose } from '../commands.js';
|
||||
@@ -138,6 +143,8 @@ function mounted(t, options = {}) {
|
||||
createSession: factory(instances, options),
|
||||
createControl: (control) => createTestVoiceUi({ ...control, pinia }),
|
||||
panelHost: host,
|
||||
styleManager: options.styleManager ?? null,
|
||||
contextCard: createContextCardOpener(applicationPinia()),
|
||||
nativePanelProvider: options.native
|
||||
? (options.nativeProvider ?? 'gemini')
|
||||
: null,
|
||||
@@ -779,7 +786,7 @@ test('voice timeout change preserves a pending voice reveal', async (t) => {
|
||||
assert.equal(f.commands.getVoicePreferences().minutes, 0);
|
||||
});
|
||||
|
||||
test('active provider output reveals Preview after done; manual choice wins until genuine input, replays do not reset idle', async (t) => {
|
||||
test('active provider output reveals Preview after done; manual choice wins until genuine input, replays change nothing', async (t) => {
|
||||
const f = mounted(t, { native: true, nativeProvider: 'openai', view: true });
|
||||
await f.commands.session.start();
|
||||
const emit = f.instances[0].hooks.emit;
|
||||
@@ -795,10 +802,12 @@ test('active provider output reveals Preview after done; manual choice wins unti
|
||||
emit({ type: 'completion', responseId: 'r1' });
|
||||
reply('Late answer');
|
||||
assert.equal(f.commands.voicePanel.snapshot().panelOpen, true);
|
||||
const timer = f.commands.voiceCard.hideTimer;
|
||||
const shown = f.commands.voiceCard.state;
|
||||
reply('Late answer');
|
||||
reply('Late', 'r1', { final: false });
|
||||
assert.equal(f.commands.voiceCard.hideTimer, timer);
|
||||
assert.equal(f.commands.voiceCard.state, shown);
|
||||
// The panel's card keeps its reply; it has no idle deadline.
|
||||
assert.equal(f.commands.voiceCard.hideTimer, null);
|
||||
assert.equal(f.commands.voiceCard.state.assistant, 'Late answer');
|
||||
f.commands.voicePanel.close();
|
||||
emit({
|
||||
@@ -1444,3 +1453,222 @@ test('teardown inside sendText prevents appending the submitted message', async
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
// What the selection actions report, as the real runner does.
|
||||
const selectionRunner = async (name) =>
|
||||
name === 'select_nearest_aircraft'
|
||||
? {
|
||||
ok: true,
|
||||
action: name,
|
||||
layerId: 'flights',
|
||||
label: 'UAL12',
|
||||
aircraft: { id: 'a1b2c3', callsign: 'UAL12' },
|
||||
}
|
||||
: name === 'track_entity'
|
||||
? {
|
||||
ok: true,
|
||||
action: name,
|
||||
layerId: 'military',
|
||||
kind: 'aircraft',
|
||||
id: 'ae01ce',
|
||||
label: 'RCH401',
|
||||
latitude: 42.3,
|
||||
longitude: -71,
|
||||
}
|
||||
: { ok: true };
|
||||
// The Context panel's entity card, cleared for each test.
|
||||
function contextCard(t) {
|
||||
const store = useEntityCardStore(applicationPinia());
|
||||
store.clear();
|
||||
t.after(() => store.clear());
|
||||
return store;
|
||||
}
|
||||
|
||||
// Docks the assistant panels into the right rail's lane for one test.
|
||||
async function dockIntoRail(t, f) {
|
||||
t.after(() => globalThis.localStorage.removeItem('gev.panel.docked'));
|
||||
f.ui.emit('layout-dock');
|
||||
await f.settle();
|
||||
await f.settle();
|
||||
}
|
||||
|
||||
test('a voice selection opens its Context card, steps the docked voice panel down and keeps the reply', async (t) => {
|
||||
const context = contextCard(t);
|
||||
const f = mounted(t, { view: true, runner: selectionRunner });
|
||||
await f.settle();
|
||||
await f.commands.session.start();
|
||||
f.commands.voicePanel.select('preview');
|
||||
await f.settle();
|
||||
await dockIntoRail(t, f);
|
||||
const panel = $('#gev-voice-panel');
|
||||
assert.equal(panel.dataset.placement, 'docked');
|
||||
assert.equal(globalThis.document.body.dataset.assistantDocked, 'true');
|
||||
const { emit, runAction } = f.instances[0].hooks;
|
||||
// A failed selection selects nothing, so the panel stays.
|
||||
emit({
|
||||
type: 'action-result',
|
||||
name: 'track_entity',
|
||||
result: { ok: false, error: 'Nothing matched' },
|
||||
});
|
||||
await f.settle();
|
||||
assert.equal(panel.dataset.minimized, undefined);
|
||||
assert.equal(context.card, null);
|
||||
await runAction('select_nearest_aircraft', { location: 'Boston' });
|
||||
// Context shows the aircraft, as after a click on it.
|
||||
assert.equal(context.card.layerId, 'flights');
|
||||
assert.equal(context.card.key, 'flights:a1b2c3');
|
||||
emit({
|
||||
type: 'transcript',
|
||||
role: 'assistant',
|
||||
text: 'The nearest aircraft is UAL12.',
|
||||
final: true,
|
||||
responseId: 'r1',
|
||||
});
|
||||
await f.settle();
|
||||
assert.equal(panel.dataset.minimized, 'true');
|
||||
// The rail, and its Context panel, show again.
|
||||
assert.equal(globalThis.document.body.dataset.assistantDocked, undefined);
|
||||
assert.equal(
|
||||
$('#gev-voice-mini-assistant').textContent,
|
||||
'The nearest aircraft is UAL12.',
|
||||
);
|
||||
// The reply is not retired on a timer: expanding the bar shows it.
|
||||
assert.equal(f.commands.voiceCard.hideTimer, null);
|
||||
f.commands.voicePanel.select('preview');
|
||||
await f.settle();
|
||||
assert.equal(panel.dataset.minimized, undefined);
|
||||
assert.equal(f.commands.voicePanel.snapshot().previewVisible, true);
|
||||
assert.equal($('#gev-voice-preview-empty').hidden, true);
|
||||
assert.equal(
|
||||
f.commands.voiceCard.snapshot().assistant.text,
|
||||
'The nearest aircraft is UAL12.',
|
||||
);
|
||||
// The next turn replaces it.
|
||||
emit({ type: 'interruption', reason: 'user-speech' });
|
||||
assert.equal(f.commands.voiceCard.state.assistant, null);
|
||||
});
|
||||
|
||||
test('a voice selection leaves a voice panel above the dock as it is', async (t) => {
|
||||
const context = contextCard(t);
|
||||
const f = mounted(t, { view: true, runner: selectionRunner });
|
||||
await f.settle();
|
||||
await f.commands.session.start();
|
||||
f.commands.voicePanel.select('preview');
|
||||
await f.settle();
|
||||
assert.equal($('#gev-voice-panel').dataset.placement, 'compact');
|
||||
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
|
||||
await f.settle();
|
||||
assert.equal(context.card.key, 'military:ae01ce');
|
||||
assert.equal($('#gev-voice-panel').dataset.minimized, undefined);
|
||||
});
|
||||
|
||||
test('a voice selection in Cockpit leaves the hidden Context card alone', async (t) => {
|
||||
const context = contextCard(t);
|
||||
const f = mounted(t, { view: true, runner: selectionRunner });
|
||||
await f.settle();
|
||||
await f.commands.session.start();
|
||||
globalThis.document.body.classList.add('cockpit-mode');
|
||||
t.after(() => globalThis.document.body.classList.remove('cockpit-mode'));
|
||||
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
|
||||
assert.equal(context.card, null);
|
||||
});
|
||||
|
||||
test('a typed chat selection opens its Context card and steps the docked chat panel down', async (t) => {
|
||||
const context = contextCard(t);
|
||||
const f = mounted(t, { view: true, runner: selectionRunner });
|
||||
typedChat(f);
|
||||
await f.settle();
|
||||
$('#gev-chat-button').click();
|
||||
await f.settle();
|
||||
await dockIntoRail(t, f);
|
||||
assert.equal($('#gev-chat-panel').dataset.placement, 'docked');
|
||||
await f.commands.session.start({ textOnly: true });
|
||||
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
|
||||
await f.settle();
|
||||
assert.equal(context.card.key, 'military:ae01ce');
|
||||
assert.equal($('#gev-chat-panel').dataset.minimized, 'true');
|
||||
assert.equal(f.ui.state.chat.open, true);
|
||||
assert.equal(globalThis.document.body.dataset.assistantDocked, undefined);
|
||||
});
|
||||
|
||||
test('the voice panel keeps the last reply until the next turn starts', async (t) => {
|
||||
const f = mounted(t, { view: true });
|
||||
await f.settle();
|
||||
await f.commands.session.start();
|
||||
f.commands.voicePanel.select('preview');
|
||||
const { emit } = f.instances[0].hooks;
|
||||
emit({
|
||||
type: 'transcript',
|
||||
role: 'assistant',
|
||||
text: 'Tracking UAL12.',
|
||||
final: true,
|
||||
responseId: 'r1',
|
||||
});
|
||||
await f.settle();
|
||||
// Only the card floating on a control without the panel hides when idle.
|
||||
assert.equal(f.commands.voiceCard.hideTimer, null);
|
||||
assert.equal(f.commands.voicePanel.snapshot().previewVisible, true);
|
||||
assert.equal($('#gev-voice-preview-empty').hidden, true);
|
||||
emit({ type: 'interruption', reason: 'user-speech' });
|
||||
emit({
|
||||
type: 'transcript',
|
||||
role: 'assistant',
|
||||
text: 'Now following DAL4.',
|
||||
final: true,
|
||||
responseId: 'r2',
|
||||
});
|
||||
assert.equal(f.commands.voiceCard.state.assistant, 'Now following DAL4.');
|
||||
});
|
||||
|
||||
test('a voice selection in Cockpit, as Cockpit reports it, leaves the Context card alone', async (t) => {
|
||||
const context = contextCard(t);
|
||||
let cockpit = true;
|
||||
const f = mounted(t, {
|
||||
view: true,
|
||||
runner: selectionRunner,
|
||||
styleManager: { getCockpitState: () => ({ active: cockpit }) },
|
||||
});
|
||||
await f.settle();
|
||||
await f.commands.session.start();
|
||||
// Cockpit's own state decides, not the page's classes.
|
||||
assert.equal(
|
||||
globalThis.document.body.classList.contains('cockpit-mode'),
|
||||
false,
|
||||
);
|
||||
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
|
||||
assert.equal(context.card, null);
|
||||
cockpit = false;
|
||||
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
|
||||
assert.equal(context.card.key, 'military:ae01ce');
|
||||
});
|
||||
|
||||
test('a slow voice selection never replaces a card clicked since it was asked', async (t) => {
|
||||
const context = contextCard(t);
|
||||
let finish;
|
||||
const f = mounted(t, {
|
||||
view: true,
|
||||
runner: (name) =>
|
||||
name === 'track_entity'
|
||||
? new Promise((resolve) => {
|
||||
finish = () => resolve(selectionRunner(name));
|
||||
})
|
||||
: selectionRunner(name),
|
||||
});
|
||||
await f.settle();
|
||||
await f.commands.session.start();
|
||||
const pending = f.instances[0].hooks.runAction('track_entity', {
|
||||
query: 'RCH401',
|
||||
});
|
||||
await Promise.resolve();
|
||||
// The person clicks another aircraft while the lookup runs.
|
||||
context.select({ layerId: 'flights', id: 'click1', label: 'CLICKED' });
|
||||
const clicked = context.card.key;
|
||||
finish();
|
||||
await pending;
|
||||
assert.equal(context.card.key, clicked);
|
||||
// A selection with no newer pick still opens its card.
|
||||
await f.instances[0].hooks.runAction('select_nearest_aircraft', {
|
||||
location: 'Boston',
|
||||
});
|
||||
assert.equal(context.card.key, 'flights:a1b2c3');
|
||||
});
|
||||
@@ -11,6 +11,31 @@ import { PointerReticle } from './pointerReticle.js';
|
||||
import { VOICE_PROVIDERS } from './providerCapabilities.js';
|
||||
import { t, translateKnown } from '../i18n/index.js';
|
||||
|
||||
/**
|
||||
* Actions whose success selects an entity on the map, and the identity each
|
||||
* result names it by.
|
||||
*/
|
||||
const SELECTION_ACTIONS = new Map([
|
||||
[
|
||||
'select_nearest_aircraft',
|
||||
(result) => ({
|
||||
layerId: result.layerId,
|
||||
id: result.aircraft?.id,
|
||||
label: result.label || result.aircraft?.callsign,
|
||||
}),
|
||||
],
|
||||
[
|
||||
'track_entity',
|
||||
(result) => ({
|
||||
layerId: result.layerId,
|
||||
id: result.id,
|
||||
label: result.label,
|
||||
lat: result.latitude,
|
||||
lon: result.longitude,
|
||||
}),
|
||||
],
|
||||
]);
|
||||
|
||||
function createDefaultReticle(pointer) {
|
||||
const element = pointer?.element;
|
||||
if (!element?.ownerDocument) return null;
|
||||
@@ -38,6 +63,12 @@ export function createVoiceCommands({
|
||||
onSessionEvent,
|
||||
canStartVoice,
|
||||
createCard = (options) => new VoiceCardControls(options),
|
||||
// Cockpit's own state; Context stays hidden while it runs.
|
||||
styleManager = null,
|
||||
// Opens a selection's card in the Context panel, as a click does
|
||||
// (`createContextCardOpener` in src/ui/stores/entityCard.js); the app
|
||||
// hands it in. Without one, selections open no card.
|
||||
contextCard = null,
|
||||
pointer = null,
|
||||
referents = null,
|
||||
createReticle = createDefaultReticle,
|
||||
@@ -147,10 +178,14 @@ export function createVoiceCommands({
|
||||
});
|
||||
});
|
||||
// Captions, plan and result card nested in the control; it only reads
|
||||
// provider-neutral session events.
|
||||
// provider-neutral session events. In the voice panel the card is the
|
||||
// Preview's content, so the last reply stays until the next turn replaces
|
||||
// it; only the card floating on the control hides when idle.
|
||||
const card = createCard({
|
||||
ui,
|
||||
...(panelHost ? { onRender: () => panelMount?.panel.sync() } : {}),
|
||||
...(panelHost
|
||||
? { onRender: () => panelMount?.panel.sync(), idleMs: null }
|
||||
: {}),
|
||||
});
|
||||
panelMount = panelHost?.mount({
|
||||
ui,
|
||||
@@ -279,6 +314,53 @@ export function createVoiceCommands({
|
||||
}),
|
||||
]
|
||||
: [];
|
||||
// A voice or chat selection shows in the right rail's Context panel, as a
|
||||
// click's does: its card opens there, and the assistant panel docked over
|
||||
// the rail steps down to its bar, where the latest reply stays readable. A
|
||||
// panel above the dock leaves the rail in view, so it stays as it is.
|
||||
const dockedOverRail = (name) => {
|
||||
const panel = ui.element(name);
|
||||
return Boolean(
|
||||
panel &&
|
||||
!panel.hidden &&
|
||||
panel.dataset?.placement === 'docked' &&
|
||||
!panel.dataset.minimized,
|
||||
);
|
||||
};
|
||||
// The Context card generation each selection was asked at, by call, so a
|
||||
// slow selection never replaces a card picked since.
|
||||
const askedAt = new Map();
|
||||
const callKey = (event) => event.callId ?? event.name;
|
||||
const cockpitActive = () =>
|
||||
typeof styleManager?.getCockpitState === 'function'
|
||||
? styleManager.getCockpitState()?.active === true
|
||||
: globalThis.document?.body?.classList?.contains('cockpit-mode') === true;
|
||||
layouts.push(
|
||||
session.subscribe((event) => {
|
||||
if (!SELECTION_ACTIONS.has(event.name)) return;
|
||||
if (event.type === 'action-call') {
|
||||
askedAt.set(callKey(event), contextCard?.generation?.() ?? null);
|
||||
return;
|
||||
}
|
||||
if (event.type !== 'action-result') return;
|
||||
const since = askedAt.get(callKey(event)) ?? null;
|
||||
askedAt.delete(callKey(event));
|
||||
if (event.result?.ok !== true) return;
|
||||
contextCard?.show?.(SELECTION_ACTIONS.get(event.name)(event.result), {
|
||||
since,
|
||||
cockpitActive: cockpitActive(),
|
||||
});
|
||||
if (!panelMount) return;
|
||||
if (adapter.getStartOptions?.().textOnly) {
|
||||
if (ui.state.chat.open && dockedOverRail('chatPanel'))
|
||||
chat?.minimize({ focus: false });
|
||||
} else if (
|
||||
panelMount.panel.snapshot().panelOpen &&
|
||||
dockedOverRail('voicePanel')
|
||||
)
|
||||
minimizeVoicePanel();
|
||||
}),
|
||||
);
|
||||
const unbindMiniPreview = panelMount
|
||||
? bindVoiceMiniPreview({ ui, session })
|
||||
: null;
|
||||
|
||||
@@ -20,7 +20,8 @@ export class VoiceCardControls {
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {object} options.ui The voice control presenter.
|
||||
* @param {number} [options.idleMs]
|
||||
* @param {number|null} [options.idleMs] How long an idle card stays shown;
|
||||
* null keeps it until the next turn, Stop or a dismissal.
|
||||
* @param {Function} [options.setTimer]
|
||||
* @param {Function} [options.clearTimer]
|
||||
*/
|
||||
@@ -103,6 +104,7 @@ export class VoiceCardControls {
|
||||
|
||||
scheduleIdle() {
|
||||
this.cancelIdle();
|
||||
if (this.idleMs === null) return;
|
||||
this.hideTimer = this.setTimer(() => {
|
||||
this.hideTimer = null;
|
||||
if (this.destroyed) return;
|
||||
|
||||
@@ -168,8 +168,7 @@ test('markup: the card nests inside the voice control with every element and a p
|
||||
'the card is part of the voice control',
|
||||
);
|
||||
assert.equal(document.querySelectorAll('#gev-voice-card').length, 1);
|
||||
if (panel)
|
||||
assert.equal(card.parentElement.id, 'gev-voice-preview-panel');
|
||||
if (panel) assert.equal(card.parentElement.id, 'gev-voice-preview-panel');
|
||||
for (const id of [
|
||||
'gev-voice-card-phase',
|
||||
'gev-voice-card-dismiss',
|
||||
@@ -531,7 +530,12 @@ test('additive presentation gates retain the current localized reducer labels',
|
||||
const steps = card.state.steps;
|
||||
const result = card.state.result;
|
||||
const who = () => ui.state.card.user.label;
|
||||
card.handle({ type: 'transcript', role: 'user', text: 'Same words', attribution: 'unverified' });
|
||||
card.handle({
|
||||
type: 'transcript',
|
||||
role: 'user',
|
||||
text: 'Same words',
|
||||
attribution: 'unverified',
|
||||
});
|
||||
assert.equal(card.state.userAttribution, 'unverified');
|
||||
assert.equal(card.snapshot().user.label, 'Habla reciente');
|
||||
assert.equal(who(), 'Habla reciente');
|
||||
@@ -615,3 +619,31 @@ test('manual panel and preference compose with the actual card without changing
|
||||
panel.destroy();
|
||||
card.destroy();
|
||||
});
|
||||
|
||||
test('a card without an idle deadline keeps its reply until the next turn', () => {
|
||||
const ui = createTestVoiceUi();
|
||||
let timers = 0;
|
||||
const card = new VoiceCardControls({
|
||||
ui,
|
||||
idleMs: null,
|
||||
setTimer() {
|
||||
timers++;
|
||||
return timers;
|
||||
},
|
||||
clearTimer() {},
|
||||
});
|
||||
card.handle({ type: 'interruption' });
|
||||
card.handle({
|
||||
type: 'transcript',
|
||||
role: 'assistant',
|
||||
text: 'Tracking UAL12.',
|
||||
final: true,
|
||||
responseId: 'r1',
|
||||
});
|
||||
assert.equal(timers, 0);
|
||||
assert.equal(card.hideTimer, null);
|
||||
assert.equal(card.snapshot().visible, true);
|
||||
card.handle({ type: 'interruption' });
|
||||
assert.equal(card.snapshot().assistant.visible, false);
|
||||
card.destroy();
|
||||
});
|
||||
Reference in new issue
Block a user