Merge branch 'main' into codex/fix-annotation-height-culling

This commit is contained in:
German Khokhlov authored and GitHub committed 2026-11-20 17:24:08 +04:00
commit f54d612aab
388 files changed
+32116 -1778

No files matched your search

+3 -1
View File
@@ -27,7 +27,9 @@ let instances = 0;
* records fully cover, reused for later views inside it) and `zoom` (their
* tile precision; `source.detailZoom(box)` names the zoom a view needs). Records use stable string ids and latitude /
* longitude in degrees; optional directionDeg is a compass bearing [0, 360).
* Manufacturer, operator and cameraType are optional display fields.
* Manufacturer, operator, cameraType and model are optional display fields;
* model only selects a vendored datasheet line (modelSpecs.js), never shown
* as text.
* Source label and attribution { name, description, text, href } identify the
* actual provider; href must be HTTPS. Provider payload parsing stays in source.
* Context services remove obsolete records with
+250
View File
@@ -0,0 +1,250 @@
/**
* @module alprModelSpecs
*
* Datasheet specs for the ALPR hardware that OpenStreetMap `model` tags name,
* vendored from the CCTV Camera Database (CC0-1.0) and matched with the CCTV
* layer's rules; DATA_SOURCES.md has the provenance. Flock Safety publishes no
* datasheet resolution, so Flock models stay unresolved; an unknown model
* never implies anything.
*
* Scope guardrail: records describe camera PRODUCTS (optics, resolution,
* night vision) — never endpoints, operators or what a camera records.
*/
import { createModelSpecLookup, lookupModelSpec } from '../cctv/modelSpecs.js';
/**
* Records from the dataset's model-enrichment extract (v2.29.0), with the
* bare product codes mappers tag ("L6Q") added as aliases where the title
* names the product line ("Vigilant L6Q"). A tag without a generation or
* variant could name any of them, so the SharpV G3 and SharpX XGA titles
* carry theirs. Fields the card does not read (type, url, fov_deg, …) stay as
* in the dataset, like the CCTV records.
*/
const RECORDS = [
{
id: 'motorola-solutions-l5f',
brand: 'Motorola Solutions',
model: 'Vigilant L5F',
type: 'box',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l5f/',
aliases: ['L5F', 'L5F Fixed LPR Camera System'],
resolution: { mp: 1.6, w: 1440, h: 1080 },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'motorola-solutions-l5m',
brand: 'Motorola Solutions',
model: 'Vigilant L5M',
type: 'box',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l5m/',
aliases: [
'L5M',
'L5M Mobile LPR Camera System',
'L5M Mobile ANPR Camera System',
],
resolution: { mp: 1.6, w: 1440, h: 1080 },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'motorola-solutions-l5q',
brand: 'Motorola Solutions',
model: 'Vigilant L5Q',
type: 'box',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l5q/',
aliases: ['L5Q', 'L5Q Quick Deploy LPR Camera System'],
resolution: { mp: 3 },
environment: ['outdoor'],
},
{
id: 'motorola-solutions-l6d',
brand: 'Motorola Solutions',
model: 'Vigilant L6D',
type: 'bullet',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l6d/',
aliases: [
'L6D',
'L6D Dual-Purpose LPR Camera',
'VSM-L6D-8IR',
'VSM-L6D-7IR',
],
fov_deg: '52-3 horizontal',
resolution: { mp: 1.6, w: 1440, h: 1080 },
lens_count: 2,
varifocal: true,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'motorola-solutions-l6q',
brand: 'Motorola Solutions',
model: 'Vigilant L6Q',
type: 'box',
url: 'https://www.cctv-database.com/camera/motorola-solutions-l6q/',
aliases: ['L6Q', 'L6Q Quick-Deploy LPR Camera System'],
resolution: { mp: 2.1, w: 1920, h: 1080, label: '1080p' },
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'genetec-autovu-sharpv',
brand: 'Genetec',
model: 'AutoVu SharpV G3',
type: 'box',
url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv/',
aliases: [
'AU-V-WS850-LC-G3-000',
'AU-V-BS850-LC-G3-0M0',
'AU-V-BS850-LC-G3-0M1',
],
resolution: { mp: 2.3, w: 1920, h: 1200, label: '1920x1200' },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'genetec-autovu-sharpv-g2',
brand: 'Genetec',
model: 'AutoVu SharpV G2',
type: 'box',
url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv-g2/',
aliases: ['AutoVu SharpV G1', 'AU-V-WS850-LC-G2', 'AU-V-WS850-LC'],
resolution: { mp: 1.2, w: 1280, h: 960, label: '1280x960' },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'genetec-autovu-sharpx',
brand: 'Genetec',
model: 'AutoVu SharpX XGA',
type: 'box',
url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpx/',
// i18n-ignore: datasheet label
resolution: { mp: 1, w: 1024, h: 946, label: 'XGA (1024x946)' },
lens_count: 2,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'genetec-autovu-sharpz3',
brand: 'Genetec',
model: 'AutoVu SharpZ3',
type: 'box',
url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpz3/',
resolution: { mp: 1.6, w: 1456, h: 1088, label: '1456x1088' },
lens_count: 3,
night_vision: { type: 'ir' },
environment: ['outdoor'],
},
{
id: 'axis-q1700-le',
brand: 'Axis',
model: 'Q1700-LE',
type: 'box',
url: 'https://www.cctv-database.com/camera/axis-q1700-le/',
fov_deg: '16-2.3 horizontal / 9.6-1.3 vertical',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' },
varifocal: true,
night_vision: { type: 'ir', range_m: 50 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'axis-q1800-le',
brand: 'Axis',
model: 'Q1800-LE',
type: 'bullet',
url: 'https://www.cctv-database.com/camera/axis-q1800-le/',
aliases: ['03107-001', 'Q1800-LE-3 (License Plate Verifier kit)'],
fov_deg: '38-2.3 horizontal',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' },
varifocal: true,
night_vision: { type: 'ir', range_m: 40 },
environment: ['indoor', 'outdoor'],
ndaa_compliant: true,
},
{
id: 'verkada-cb62-te-f',
brand: 'Verkada',
model: 'CB62-TE-F',
type: 'bullet',
url: 'https://www.cctv-database.com/camera/verkada-cb62-te-f/',
fov_deg: '42 to 17 H',
resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' },
varifocal: true,
night_vision: { type: 'ir', range_m: 50 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'verkada-ch52-e-f',
brand: 'Verkada',
model: 'CH52-E-F',
type: 'panoramic',
url: 'https://www.cctv-database.com/camera/verkada-ch52-e-f/',
fov_deg: '89 to 37 H (per sensor); up to 328 combined',
// i18n-ignore: datasheet label
resolution: { mp: 5, w: 2688, h: 1944, label: '4 x 5MP (20MP)' },
lens_count: 4,
varifocal: true,
night_vision: { type: 'ir', range_m: 30 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'verkada-cp63-e',
brand: 'Verkada',
model: 'CP63-E',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/verkada-cp63-e/',
fov_deg: '64 to 2 H',
resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' },
ptz: true,
varifocal: true,
night_vision: { type: 'ir', range_m: 100 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'verkada-cr63-e',
brand: 'Verkada',
model: 'CR63-E',
type: 'bullet',
url: 'https://www.cctv-database.com/camera/verkada-cr63-e/',
fov_deg: '109 to 49 H',
resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' },
varifocal: true,
night_vision: { type: 'ir', range_m: 20 },
environment: ['indoor', 'outdoor'],
},
// The CCTV layer's record: one colour-neutral title for the B/G/W variants.
lookupModelSpec('MIC-7522-Z30B', 'Bosch'),
];
const lookupDatasheetSpec = createModelSpecLookup(RECORDS);
/**
* Datasheet record for a mapped ALPR camera's `model` tag. A `manufacturer`
* naming another maker rejects the match, so a "Flock Safety" camera tagged
* "L6Q" stays unresolved rather than borrowing Motorola's specs.
* @param {string|null} model - The OSM `model` tag.
* @param {string|null} [manufacturer] - The OSM `manufacturer` tag.
* @returns {Object|null} The spec record, or null when unknown.
*/
export function lookupAlprModelSpec(model, manufacturer) {
// Adapter records arrive unnormalized and the matcher's word trim is
// quadratic on long punctuation runs: match only tag-sized strings (the
// built-in sources keep 180 characters).
if (typeof model !== 'string' || model.length > 180) return null;
if (
manufacturer != null &&
(typeof manufacturer !== 'string' || manufacturer.length > 180)
)
return null;
return lookupDatasheetSpec(model, manufacturer);
}
+157
View File
@@ -0,0 +1,157 @@
// src/layers/alpr/modelSpecs.test.mjs
// Mapped ALPR model tags resolve to vendored datasheets, and never guess.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { PbfWriter } from 'pbf';
import { lookupAlprModelSpec } from './modelSpecs.js';
import { decodeAlprTile } from './tileRecords.js';
import { alprLabelDetails } from './visuals.js';
const OSM = { attribution: { name: 'OpenStreetMap' } };
test('the model tags mappers write resolve to their datasheet record', () => {
// [model tag, manufacturer tag, record id] as they appear on OSM nodes.
for (const [model, manufacturer, id] of [
['L6Q', 'Motorola Solutions', 'motorola-solutions-l6q'],
['L5F', 'Motorola Solutions', 'motorola-solutions-l5f'],
['L6D', 'Motorola Solutions', 'motorola-solutions-l6d'],
['L6Q', null, 'motorola-solutions-l6q'],
['AutoVu SharpV G3', 'Genetec', 'genetec-autovu-sharpv'],
['AU-V-WS850-LC-G3-000', 'Genetec', 'genetec-autovu-sharpv'],
['AutoVu SharpV G2', 'Genetec', 'genetec-autovu-sharpv-g2'],
['AutoVu SharpV G1', 'Genetec', 'genetec-autovu-sharpv-g2'],
['AutoVu SharpX XGA', 'Genetec', 'genetec-autovu-sharpx'],
['Q1700-LE', 'Axis Communications', 'axis-q1700-le'],
['Q1800-LE', 'Axis Communications', 'axis-q1800-le'],
['CP63-E', 'Verkada Inc.', 'verkada-cp63-e'],
['CB62-TE-F', 'Verkada Inc.', 'verkada-cb62-te-f'],
['CH52-E-F', 'Verkada Inc.', 'verkada-ch52-e-f'],
['CR63-E', 'Verkada', 'verkada-cr63-e'],
['MIC-7522-Z30B', 'The Bosch Group', 'bosch-mic-7522-z30b'],
])
assert.equal(
lookupAlprModelSpec(model, manufacturer)?.id,
id,
`${manufacturer} ${model}`,
);
});
test('unknown, mis-attributed or partial models stay unresolved', () => {
for (const [model, manufacturer] of [
['Falcon', 'Flock Safety'],
// A Motorola code under another maker is a mapping error, not a match.
['L6Q', 'Flock Safety'],
// "AutoVu Sharp" is an older line than SharpV; "Q1800" names no variant.
['AutoVu Sharp', 'Genetec'],
['Q1800', 'Axis Communications'],
// Without a maker, a code-less product name is never trusted.
['AutoVu SharpV', null],
// A SharpV without its generation could be G1, G2 or G3, and a SharpX
// without XGA could be the VGA model.
['AutoVu SharpV', 'Genetec'],
['AutoVu SharpV HD', 'Genetec'],
['Genetec AutoVu SharpV', 'Genetec'],
['AutoVu SharpX', 'Genetec'],
['UnicamVELOCITY3', null],
[null, 'Motorola Solutions'],
// Adapter text is matched only as a string of tag size.
[['L6Q'], 'Motorola Solutions'],
['L6Q' + ' IP'.repeat(60), 'Motorola Solutions'],
])
assert.equal(lookupAlprModelSpec(model, manufacturer), null);
});
/** A one-point `cameras` vector tile (z0) with string attributes. */
function cameraTile(properties) {
const tile = new PbfWriter();
tile.writeMessage(3, (_, layer) => {
layer.writeVarintField(15, 2);
layer.writeStringField(1, 'cameras');
layer.writeVarintField(5, 4096);
const keys = Object.keys(properties);
layer.writeMessage(2, (_, feature) => {
feature.writePackedVarint(
2,
keys.flatMap((_, i) => [i, i]),
);
feature.writeVarintField(3, 1); // Point
feature.writePackedVarint(4, [9, 4096, 4096]); // MoveTo(2048, 2048)
});
for (const key of keys) layer.writeStringField(3, key);
for (const key of keys)
layer.writeMessage(4, (_, value) =>
value.writeStringField(1, String(properties[key])),
);
});
return tile.finish();
}
test('extract tiles carry the model tag to the card', () => {
const [record] = decodeAlprTile(
cameraTile({
osmType: 'node',
osmId: '7',
brand: 'Motorola Solutions',
model: 'L6Q',
}),
0,
0,
0,
);
assert.equal(record.model, 'L6Q');
assert.ok(
alprLabelDetails(record, OSM).includes('SPEC VIGILANT L6Q · 1080P · IR'),
);
});
test('the card adds the datasheet line only for a resolved model', () => {
const details = alprLabelDetails(
{ manufacturer: 'Motorola Solutions', model: 'L6Q' },
OSM,
);
assert.deepEqual(details, [
'OSM MAPPED',
'MOTOROLA SOLUTIONS',
'SPEC VIGILANT L6Q · 1080P · IR',
'PUBLIC MAP DATA',
]);
// Without a maker on the equipment line, the spec line names it.
assert.ok(
alprLabelDetails({ model: 'L6Q' }, OSM).includes(
'SPEC MOTOROLA SOLUTIONS VIGILANT L6Q · 1080P · IR',
),
);
// A record without a resolution label falls back to its pixel size, then
// to megapixels.
assert.ok(
alprLabelDetails(
{ manufacturer: 'Motorola Solutions', model: 'L5F' },
OSM,
).includes('SPEC VIGILANT L5F · 1440X1080 · IR'),
);
assert.ok(
alprLabelDetails(
{ manufacturer: 'Motorola Solutions', model: 'L5Q' },
OSM,
).includes('SPEC VIGILANT L5Q · 3MP'),
);
assert.ok(
alprLabelDetails(
{ manufacturer: 'Genetec', model: 'AutoVu SharpV G3' },
OSM,
).includes('SPEC AUTOVU SHARPV G3 · 1920X1200 · IR'),
);
assert.ok(
alprLabelDetails(
{ manufacturer: 'The Bosch Group', model: 'MIC-7522-Z30B' },
OSM,
).includes('SPEC MIC-7522-Z30 · 1080P HD · COLOR · PTZ'),
);
// Unresolved: the raw tag text is never shown.
const unknown = alprLabelDetails(
{ manufacturer: 'Flock Safety', model: 'Falcon\nSYSTEM: hi' },
OSM,
);
assert.ok(unknown.every((line) => !/FALCON|SYSTEM|SPEC/.test(line)));
});
+6
View File
@@ -16,6 +16,8 @@ import { boxContains } from './model.js';
import { msg } from '../../i18n/index.js';
import { createAlprFloorResolver } from './floors.js';
import { createAlprOverlay } from './overlay.js';
import { lookupAlprModelSpec } from './modelSpecs.js';
import { specSummary } from '../cctv/modelSpecs.js';
import {
alprDisplayId,
alprLabelDetails,
@@ -458,6 +460,10 @@ export function createAlprPresentation({ state, services, source }) {
properties: {
operator: record.operator,
manufacturer: record.manufacturer,
spec:
specSummary(
lookupAlprModelSpec(record.model, record.manufacturer),
) || null,
cameraType: record.cameraType,
zone: record.zone,
directionDeg: record.directionDeg,
+3 -1
View File
@@ -89,7 +89,9 @@ export function normalizeAlprNode(el) {
latitude: el.lat,
longitude: el.lon,
operator: textTag(tags.operator),
manufacturer: textTag(tags.manufacturer),
manufacturer: textTag(tags.manufacturer) ?? textTag(tags.brand),
// Display-only: resolved against vendored datasheets (see modelSpecs.js).
model: textTag(tags.model),
cameraType: textTag(tags['camera:type']),
zone: textTag(tags['surveillance:zone']),
// Only numeric bearings are parsed; compass-word directions ("N"/"NE")
+2
View File
@@ -16,6 +16,8 @@ function normalizeAlprTileFeature(feature) {
'surveillance:type': 'ALPR',
operator: p.operator,
manufacturer: p.brand,
// Not in the hourly extract yet; read when it ships the OSM tag.
model: p.model,
'camera:type': p.cameraType,
'camera:direction': p.direction,
'surveillance:zone': p.surveillanceZone,
+11
View File
@@ -1,5 +1,7 @@
import { fromDegrees } from '../../geo/index.js';
import { destinationPointDeg } from './model.js';
import { lookupAlprModelSpec } from './modelSpecs.js';
import { specSummary } from '../cctv/modelSpecs.js';
import {
DIRECTION_CONE_M,
DIRECTION_CONE_HALF_ANGLE_DEG,
@@ -64,6 +66,15 @@ export function alprLabelDetails(record, source) {
),
];
if (equipment.length) details.push(equipment.join(' · '));
// Only a datasheet match is shown: the raw OSM `model` text never is.
const spec = lookupAlprModelSpec(record.model, record.manufacturer);
if (spec) {
// The equipment line usually names the maker already; the card does not wrap.
const withBrand = !equipment.some((line) =>
line.includes(spec.brand.toUpperCase()),
);
details.push(`SPEC ${specSummary(spec, { withBrand }).toUpperCase()}`);
}
if (sourceName === 'OpenStreetMap') details.push('PUBLIC MAP DATA');
return details;
}
+1 -1
View File
@@ -229,7 +229,7 @@ export function createCards({ state: layerState, services, parts, source }) {
let rank = 0;
const push = (id, { pinned = false, active = false } = {}) => {
const record = layerState._recordById.get(id);
if (!record?.position) return;
if (!record?.position || (!active && record.viewGrouped)) return;
entries.push(
createCctvThumbnailOverlayEntry({
id,
+2 -1
View File
@@ -219,7 +219,8 @@ export function createControls({ state: layerState, services, parts, source }) {
for (let i = start; i < records.length; i += stride) {
const camera = records[i].camera;
objects.push({
position: records[i].position,
// A camera sharing its mount is drawn beside its mates.
position: records[i].spreadPosition ?? records[i].position,
sourceId: camera.id,
// Short semantic code where the id is opaque (see cameraDisplayCode).
id: `CAM-${camera.code || camera.id}`,
+430
View File
@@ -0,0 +1,430 @@
import {
cellCenter,
cellLonLat,
formatCameraCount,
mergeCountCells,
withoutLoneCameras,
} from '../../data/cctvCellCounts.js';
import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js';
import {
CAMERA_GREEN,
COUNT_CAMERA_ICON,
CAMERA_ICON_PX,
COUNT_MERGE_GAP_PX,
} from './policy.js';
import { liftedForHorizon } from '../../geo/horizon.js';
// Diameter at one camera before applying the size limits, in CSS pixels.
const COUNT_BASE_PX = 38;
// Extra diameter for each tenfold increase in camera count.
const COUNT_PX_PER_DECADE = 5;
// Minimum height of a count marker in CSS pixels.
const COUNT_MIN_HEIGHT_PX = 40;
// Maximum height of a count marker in CSS pixels.
const COUNT_MAX_HEIGHT_PX = 58;
// Clear fill between the count and the inside of the ring, in CSS pixels.
const COUNT_TEXT_PADDING_PX = 6;
// Height of the camera glyph in the smallest and the largest marker.
const COUNT_GLYPH_MIN_PX = 7.5;
const COUNT_GLYPH_MAX_PX = 10;
// Clear fill above the glyph in the smallest and the largest marker.
const COUNT_GLYPH_TOP_MIN_PX = 3;
const COUNT_GLYPH_TOP_MAX_PX = 4;
// Clear fill between the glyph's top corners and the inside of the ring.
const COUNT_GLYPH_PADDING_PX = 2;
// The middle of the digits sits this share of the inner radius below the
// marker's centre, which leaves the glyph clear of the count.
const COUNT_LABEL_DROP = 0.2;
// Merge passes per view. A merged centre and wider label can reach a further
// marker. The cap bounds work on motion ticks.
const COUNT_MERGE_PASSES = 3;
const FONT = WORLD_OVERLAY_STYLE.fontTitle;
// Reserve the camera's landscape slot even while the map sprite is loading.
const GLYPH_ASPECT = 1.5;
const RING_PX = 2;
const RIM_PX = 1;
const STROKE_INSET = RIM_PX + RING_PX / 2;
// Painted bounds of the camera art, scaled from its viewBox to source pixels.
const GLYPH_SOURCE = [3.4, 13.4, 28.1, 19.5].map((v) => (v * 48) / 36);
const GLYPH_SOURCE_ASPECT = 28.1 / 19.5;
/** Merged camera groups and their last painted hit rectangles in CSS pixels. */
export function createCountMarkers(
registerPaintLane,
id,
refreshView,
keyholeAlpha,
) {
let hardUi = null;
let sprite = null;
let spriteReady = false;
const markers = [];
const hits = [];
const textMetrics = new Map();
const fonts = globalThis.document?.fonts;
let measureCtx;
let hitCount = 0;
const lane = registerPaintLane?.('ambient-label', paint, {
id,
active: false,
target: 'shared',
});
function loadSprite() {
if (sprite || typeof Image === 'undefined') return;
sprite = new Image();
sprite.onload = () => {
spriteReady = true;
if (markers.length) lane?.requestPaint();
};
sprite.src = COUNT_CAMERA_ICON;
}
fonts?.addEventListener?.('loadingdone', fontsLoaded);
/** Font changes can widen a pill enough to merge it with its neighbor. */
function fontsLoaded() {
textMetrics.clear();
if (!markers.length) return;
refreshView();
lane?.requestPaint();
}
/** Seat the glyph under the top of the ring and the count just below centre. */
function sizeFor(count) {
const text = formatCameraCount(count);
let metrics = textMetrics.get(text);
if (!metrics) {
measureCtx ??= globalThis.document
.createElement('canvas')
.getContext('2d');
measureCtx.font = FONT;
measureCtx.textBaseline = 'middle';
metrics = measureCtx.measureText(text);
textMetrics.set(text, metrics);
}
const diameter = COUNT_BASE_PX + COUNT_PX_PER_DECADE * Math.log10(count);
const clamped = Math.max(
COUNT_MIN_HEIGHT_PX,
Math.min(COUNT_MAX_HEIGHT_PX, diameter),
);
const height = 2 * Math.round(clamped / 2);
const grown =
(height - COUNT_MIN_HEIGHT_PX) /
(COUNT_MAX_HEIGHT_PX - COUNT_MIN_HEIGHT_PX);
const glyphHeight =
COUNT_GLYPH_MIN_PX + (COUNT_GLYPH_MAX_PX - COUNT_GLYPH_MIN_PX) * grown;
const radius = height / 2 - RIM_PX - RING_PX;
const glyphTop =
COUNT_GLYPH_TOP_MIN_PX +
(COUNT_GLYPH_TOP_MAX_PX - COUNT_GLYPH_TOP_MIN_PX) * grown -
radius;
const ascent = metrics.actualBoundingBoxAscent;
const descent = metrics.actualBoundingBoxDescent;
const labelY = COUNT_LABEL_DROP * radius + (ascent - descent) / 2;
// Each row must clear the ring at the edge where the circle is narrowest.
const chordAt = (y) => 2 * Math.sqrt(Math.max(0, radius ** 2 - y ** 2));
const extra = Math.max(
0,
Math.ceil(
Math.max(
metrics.width + 2 * COUNT_TEXT_PADDING_PX - chordAt(labelY + descent),
glyphHeight * GLYPH_ASPECT +
2 * COUNT_GLYPH_PADDING_PX -
chordAt(glyphTop),
),
),
);
return {
text,
width: height + extra,
height,
glyphHeight,
glyphBottom: glyphTop + glyphHeight,
labelY,
};
}
/** Keep covered icons in the restored count if its new label clears the HUD. */
function retainCoveredCameras(group, core, project) {
const anchor = cellCenter(core);
const at = project(anchor);
if (!at) return core;
const { x, y } = at; // The projector reuses its result.
const size = sizeFor(core.count);
const halfSegment = (size.width - size.height) / 2;
const covered = group.lone.filter((lone) => {
const p = project(cellCenter(lone));
if (!p) return false;
// The pill outline that merging measures, without its gap.
const dx = Math.max(
0,
Math.abs(p.x + (lone.offsetPx ?? 0) - x) - halfSegment,
);
const reach = (size.height + (lone.iconPx ?? CAMERA_ICON_PX)) / 2;
return dx * dx + (p.y - y) ** 2 < reach * reach;
});
if (!covered.length) return core;
const { width, height } = sizeFor(core.count + covered.length);
if (hardUi({ x: x - width / 2, y: y - height / 2, w: width, h: height }))
return core;
const held = withoutLoneCameras(group, covered);
held.anchor = anchor;
held.groundM = core.groundM;
for (const lone of covered) lone.absorbed = true;
return held;
}
/**
* Reuse marker slots in ground-key order, and invalidate only changed frames.
* `groundHeight(lon, lat)` gives the drawn terrain in metres, or a non-finite
* value where it has not loaded. A count stands on that ground when available
* and otherwise uses its cameras' mean mount height.
*/
function update(cells, project, groundHeight = null) {
// Lone cameras take part so that one beside a count joins it.
let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key));
const footprint = (count, cell) => {
if (count > 1) return sizeFor(count);
const px = cell.iconPx ?? CAMERA_ICON_PX;
return { width: px, height: px };
};
/** A lone camera keeps its icon's own position; a count goes to ground. */
const ground = (list) => {
if (!groundHeight) return;
for (const cell of list) {
if (cell.count === 1 || cell.groundM !== undefined) continue;
const { lon, lat } = cellLonLat(cell);
const height = groundHeight(lon, lat);
cell.groundM = Number.isFinite(height) ? Math.round(height) : null;
}
};
for (
let pass = 0;
pass < COUNT_MERGE_PASSES &&
visible.length > 1 &&
visible.some((cell) => cell.count > 1);
pass++
) {
ground(visible);
const merged = mergeCountCells(
visible,
project,
footprint,
COUNT_MERGE_GAP_PX,
);
if (merged.length === visible.length) break;
visible = merged;
}
// A lone camera that is no longer its own entry now counts in a marker.
const apart = new Set(visible);
for (const cell of cells)
if (cell.count === 1) cell.absorbed = !apart.has(cell);
visible = visible.filter((cell) => cell.count > 1);
ground(visible);
let changed = visible.length !== markers.length;
for (let i = 0; i < visible.length; i++) {
let cell = visible[i];
// If the merged count is under the HUD, restore the count and its lone icons.
if (hardUi && cell.lone?.length) {
const at = project(cellCenter(cell));
const { width, height } = sizeFor(cell.count);
const rect = at && {
x: at.x - width / 2,
y: at.y - height / 2,
w: width,
h: height,
};
if (rect && hardUi(rect)) {
for (const lone of cell.lone) lone.absorbed = false;
const core = withoutLoneCameras(cell);
if (core) {
ground([core]);
cell = retainCoveredCameras(cell, core, project);
cell.releasedAt = rect;
}
}
}
const marker = (markers[i] ??= { focus: 1 });
const last = marker.cell;
const size = sizeFor(cell.count);
if (
!last ||
last.count !== cell.count ||
last.latSum !== cell.latSum ||
last.lonSum !== cell.lonSum ||
last.heightSum !== cell.heightSum ||
last.groundM !== cell.groundM ||
last.anchor?.x !== cell.anchor?.x ||
last.anchor?.y !== cell.anchor?.y ||
last.anchor?.z !== cell.anchor?.z
) {
marker.pos = cell.anchor ?? cellCenter(cell);
marker.cullPos = liftedForHorizon(marker.pos);
marker.hudHidden = undefined;
changed = true;
}
changed ||=
size.text !== marker.text ||
size.width !== marker.width ||
size.glyphBottom !== marker.glyphBottom ||
size.labelY !== marker.labelY;
marker.cell = cell;
Object.assign(marker, size);
// Paint never grows the hit buffer, even when a pan reveals every group.
hits[i] ??= {};
}
markers.length = visible.length;
if (markers.length) loadSprite();
// Keep the last frame pickable until the host clears its pixels.
lane?.setActive(markers.length > 0 || hitCount > 0);
if (changed) lane?.requestPaint();
}
/** Draw at device density using the host's CSS-pixel transform and projection. */
function paint(frame) {
hardUi = frame.overlapsHardUi ?? hardUi;
if (!markers.length) {
// Deactivating invalidates the host, so finish the shared frame first.
if (hitCount) queueMicrotask(deactivateIfEmpty);
hitCount = 0;
return;
}
hitCount = 0;
const { ctx, occluder, viewProjectionMatrix: m } = frame;
let refresh = false;
ctx.save();
try {
ctx.font = FONT;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (let i = 0; i < markers.length; i++) {
const marker = markers[i];
// The core can stay visible while the HUD uncovers the merged count.
if (marker.cell.releasedAt) refresh ||= !hardUi(marker.cell.releasedAt);
const { height } = marker;
const { x: px, y: py, z: pz } = marker.pos;
const w = m[3] * px + m[7] * py + m[11] * pz + m[15];
if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.cullPos)))
continue;
const x =
(0.5 + (0.5 * (m[0] * px + m[4] * py + m[8] * pz + m[12])) / w) *
frame.width;
const y =
(0.5 - (0.5 * (m[1] * px + m[5] * py + m[9] * pz + m[13])) / w) *
frame.height;
const rect = hits[hitCount];
rect.x = x - marker.width / 2;
rect.y = y - height / 2;
rect.w = marker.width;
rect.h = height;
if (
rect.x >= frame.width ||
rect.y >= frame.height ||
rect.x + rect.w <= 0 ||
rect.y + rect.h <= 0
)
continue;
const hidden = Boolean(hardUi?.(rect));
const previous = marker.hudHidden;
if (previous !== hidden) {
marker.hudHidden = hidden;
// The active icon steps aside only for visible counts beside it.
refresh ||=
((hidden || previous !== undefined) && marker.besideActive) ||
marker.cell.lone?.some((cell) => cell.absorbed === hidden);
}
if (hidden) continue;
const fade =
frame.keyhole && keyholeAlpha ? keyholeAlpha(x, y, frame.keyhole) : 1;
if (!(fade > 0)) continue;
ctx.globalAlpha = marker.focus * fade;
ctx.beginPath();
ctx.roundRect(
rect.x + STROKE_INSET,
rect.y + STROKE_INSET,
rect.w - 2 * STROKE_INSET,
height - 2 * STROKE_INSET,
height / 2 - STROKE_INSET,
);
ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)';
ctx.lineWidth = RING_PX + 2 * RIM_PX;
ctx.stroke();
ctx.fillStyle = '#0e1720';
ctx.fill();
ctx.strokeStyle = CAMERA_GREEN;
ctx.lineWidth = RING_PX;
ctx.stroke();
ctx.fillStyle = CAMERA_GREEN;
if (spriteReady) {
const width = marker.glyphHeight * GLYPH_SOURCE_ASPECT;
ctx.drawImage(
sprite,
...GLYPH_SOURCE,
x - width / 2,
y + marker.glyphBottom - marker.glyphHeight,
width,
marker.glyphHeight,
);
}
ctx.fillText(marker.text, x, y + marker.labelY);
rect.cell = marker.cell;
hitCount++;
}
} finally {
ctx.restore();
}
if (refresh) queueMicrotask(refreshView);
}
/** Resolve the topmost group actually painted at this screen position. */
function pickedCell(point) {
if (!point) return null;
for (let i = hitCount - 1; i >= 0; i--) {
const rect = hits[i];
const radius = rect.h / 2;
// Distance from the pill's horizontal centre segment.
const dx = Math.max(
0,
Math.abs(point.x - (rect.x + rect.w / 2)) - (rect.w - rect.h) / 2,
);
const dy = point.y - (rect.y + radius);
if (dx * dx + dy * dy <= radius * radius) return rect.cell;
}
return null;
}
/** A new group may already have arrived since the empty frame. */
function deactivateIfEmpty() {
if (!markers.length) lane?.setActive(false);
}
/** Release the visible groups and clear their hit targets immediately. */
function hide() {
markers.length = hits.length = hitCount = 0;
lane?.setActive(false);
}
/** Unhook this viewer's painter and its font listener. */
function dispose() {
hide();
fonts?.removeEventListener?.('loadingdone', fontsLoaded);
lane?.unregister();
}
return {
markers,
update,
pickedCell,
hide,
dispose,
requestPaint: () => lane?.requestPaint(),
};
}
+179
View File
@@ -0,0 +1,179 @@
import { test, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
const W = 800;
const H = 600;
const A = 6378137;
// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture).
const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 });
const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI;
const matrix = new Float64Array([
0,
0,
0,
0,
2 / (30 * W),
0,
0,
0,
0,
2 / (30 * H),
0,
0,
0,
0,
0,
1,
]);
function cellAt(key, x, count, height = 0) {
const cell = createCameraCell(key);
for (let i = 0; i < count; i++)
addCellCamera(cell, { lon: lonFor(x), lat: 0, absoluteHeightM: height });
return cell;
}
let painter;
function makeCtx() {
return {
labels: [],
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
roundRect() {},
stroke() {},
fill() {},
drawImage() {},
fillText(text, x, y) {
this.labels.push({ text, x, y, alpha: this.globalAlpha });
},
};
}
function paint(overrides = {}) {
const ctx = makeCtx();
painter({
ctx,
width: W,
height: H,
dpr: 1,
viewProjectionMatrix: matrix,
occluder: { isPointVisible: () => true },
overlapsHardUi: () => false,
...overrides,
});
return ctx.labels;
}
function counts(refresh = () => {}, keyholeAlpha) {
return createCountMarkers(
(_lane, paintFn) => {
painter = paintFn;
return { requestPaint() {}, setActive() {}, unregister() {} };
},
'counts',
refresh,
keyholeAlpha,
);
}
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 7,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
});
test('a count on ground below the ellipsoid stays painted while its mounts are above the horizon', () => {
const m = counts();
m.update([cellAt('a', 400, 2, -20)], project, () => -30);
const eye = fromDegrees(-0.009, 0, 30); // about 1 km away, 30 m above the ellipsoid
const horizon = horizonFrom(eye);
assert.equal(horizon.isPointVisible(fromDegrees(lonFor(400), 0, -20)), true);
assert.equal(paint({ occluder: horizon }).length, 1);
});
test('a lone camera clear of the HUD keeps its icon when the count beside it is hidden', async () => {
const hud = { overlapsHardUi: (rect) => rect.x < 200 };
for (const paintedFirst of [true, false]) {
const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)];
const m = counts(() => m.update(cells, project));
if (paintedFirst) paint(hud);
m.update(cells, project);
const labels = paint(hud);
await Promise.resolve();
assert.ok(!cells[1].absorbed || labels.length > 0);
// Moving the HUD at rest also changes whether the lone icon is needed.
paint();
await Promise.resolve();
assert.equal(cells[1].absorbed, true);
paint(hud);
await Promise.resolve();
assert.equal(cells[1].absorbed, false);
m.dispose();
}
});
test('a count stays visible when a lone camera would move it under the HUD', async () => {
const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)];
const hud = { overlapsHardUi: (rect) => rect.x + rect.w > 225 };
const m = counts(() => m.update(cells, project));
paint(hud);
m.update(cells, project);
assert.equal(paint(hud)[0]?.text, '2');
assert.equal(cells[1].absorbed, false);
await Promise.resolve();
paint(hud);
await Promise.resolve();
paint();
await Promise.resolve();
assert.equal(cells[1].absorbed, true);
assert.equal(paint()[0]?.text, '3');
m.dispose();
});
test('a restored count includes the lone camera it still covers at the HUD edge', async () => {
const cells = [cellAt('a', 200, 2), cellAt('b', 206, 1)];
const hud = { overlapsHardUi: (rect) => rect.x + rect.w > 221 };
const scratch = {};
const update = () =>
m.update(cells, (p) => Object.assign(scratch, project(p)));
const m = counts(update);
update();
assert.equal(Math.round(paint()[0].x), 202);
paint(hud);
await Promise.resolve();
const [marker] = paint(hud);
assert.equal(marker?.text, '3');
assert.equal(Math.round(marker.x), 200);
assert.equal(cells[1].absorbed, true);
assert.ok(m.pickedCell({ x: 206, y: 300 }).parts.includes(cells[1]));
paint();
await Promise.resolve();
assert.equal(Math.round(paint()[0].x), 202);
m.dispose();
});
test('counts fade with the Scope keyhole like the callouts', () => {
const m = counts(undefined, (_x, _y, keyhole) => keyhole.alpha);
m.update([cellAt('a', 400, 2)], project);
assert.equal(paint({ keyhole: { alpha: 0.25 } })[0].alpha, 0.25);
assert.deepEqual(paint({ keyhole: { alpha: 0 } }), []);
assert.equal(m.pickedCell({ x: 400, y: 300 }), null);
assert.equal(paint()[0].alpha, 1);
});
@@ -0,0 +1,76 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
// Cesium's default 60 degree field of view spans the wider side, so a 4:3
// window has a vertical fovy of about 46.8 degrees. Two pairs 50 km and 80 km
// east of an eye 800 m up merge into one count. At half the distance all four
// fit in the frame (the group is wide, not tall), so the flight must keep all
// four in frame instead of approaching only the near pair.
test('a count click on an east-west group that fits keeps every member in the frame', () => {
const viewer = {};
const flights = [];
const aspectRatio = 800 / 600;
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio);
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: 800 },
});
try {
const members = [];
const cells = [50_000, 80_000].map((start) => {
const cell = createCameraCell(String(start));
for (const eastM of [start, start + 10]) {
const lon = eastM / M;
addCellCamera(cell, { lat: 0, lon, absoluteHeightM: 8 });
members.push(lon);
}
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 433, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 4);
// Reference: a north-up top-down frame at half the distance holds all four.
const halfwayM = 65_005 / 2;
const refHalfX = halfwayM * Math.tan(fovy / 2) * aspectRatio;
assert.ok(members.every((lon) => Math.abs(lon * M - 65_005) <= refHalfX));
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
assert.equal(flights.length, 1);
const { range } = flights[0].options.offset;
const center = toLonLatH(flights[0].bounds.center);
const halfX = range * Math.tan(fovy / 2) * aspectRatio;
const inFrame = members.filter(
(lon) => Math.abs((lon - center.lon) * M) <= halfX,
);
assert.equal(
inFrame.length,
4,
`only ${inFrame.length} of 4 members in frame (range ${Math.round(range)} m)`,
);
} finally {
unbind();
}
});
@@ -0,0 +1,67 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance } from '../../geo/vector.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
// A count of four merged in a tilted view: two pairs 10 km and 40 km north of
// an eye 800 m up. After the click, at least one member must be in frame.
test('a count click from a tilted view keeps the group members in the frame', () => {
const viewer = {};
const flights = [];
const fovy = Math.PI / 3;
const aspectRatio = 800 / 600;
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: 800 },
});
try {
const metresPerDegree = 111_320;
const members = [];
const cells = [10_000, 40_000].map((start) => {
const cell = createCameraCell(String(start));
for (const northM of [start, start + 10]) {
const lat = northM / metresPerDegree;
addCellCamera(cell, { lat, lon: 0, absoluteHeightM: 8 });
members.push(fromDegrees(0, lat, 8));
}
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 433, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 4);
const state = { _viewer: viewer };
const navigation = createNavigation({ state, parts: {} });
navigation.zoomToCell(groups[0]);
assert.equal(flights.length, 1);
const { range, pitch } = flights[0].options.offset;
assert.equal(pitch, -Math.PI / 2);
const { center } = flights[0].bounds;
const halfSpanM = range * Math.tan(fovy / 2);
assert.ok(
members.some((point) => distance(point, center) <= halfSpanM),
'no member of the group is in the final frame',
);
assert.ok(range < distance(fromDegrees(0, 0, 800), center));
} finally {
unbind();
}
});
@@ -0,0 +1,69 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
// A count of 40 cameras 40 km north of an eye 800 m up takes in a lone camera
// 10 km north that is drawn just below it. The click must not land on the lone
// camera alone: at least one of the 40 counted cameras must be in the frame.
test('a count click does not fly to a lone camera that joined the count', () => {
const viewer = {};
const flights = [];
const fovy = Math.PI / 3;
const aspectRatio = 800 / 600;
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: 800 },
});
try {
const crowd = createCameraCell('crowd');
const counted = [];
for (let i = 0; i < 40; i++) {
const lat = (40_000 + i / 4) / M;
addCellCamera(crowd, { lat, lon: 0, absoluteHeightM: 8 });
counted.push(lat);
}
const lone = createCameraCell('lone');
addCellCamera(lone, { lat: 10_000 / M, lon: 0, absoluteHeightM: 8 });
const screens = [
{ x: 400, y: 300 },
{ x: 400, y: 330 },
];
const groups = mergeCountCells(
[crowd, lone],
() => screens.shift(),
(count) =>
count > 1 ? { width: 40, height: 40 } : { width: 24, height: 24 },
2,
);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 41);
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
assert.equal(flights.length, 1);
const { range } = flights[0].options.offset;
const center = toLonLatH(flights[0].bounds.center);
const halfY = range * Math.tan(fovy / 2);
const inFrame = counted.filter(
(lat) => Math.abs((lat - center.lat) * M) <= halfY,
);
assert.ok(
inFrame.length > 0,
`none of the 40 counted cameras is in the frame (range ${Math.round(range)} m, centre ${Math.round(center.lat * M)} m north)`,
);
} finally {
unbind();
}
});
@@ -0,0 +1,65 @@
import * as picking from '../../data/pickRegistry.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
function setup() {
let zooms = 0,
clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({}) },
_cctvOverlayHost: { hitTest: () => null },
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: { extractPickedCameraId: () => null },
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
return { click, counts: () => [zooms, clicks] };
}
test('a click a painted overlay target took (Space Missions label) does not fly to the count', () => {
const { click, counts } = setup();
// What the dispatcher hands subscribers after an onOverlayClick handler returned true.
click({
screenPosition: { x: 20, y: 26 },
overlay: true,
topHit: { set: '', id: null, surface: false },
drawHit: null,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.equal(
counts()[0],
0,
'count flight ran although an overlay target handled the click',
);
});
test("another layer's world-overlay card on top (clickCard) takes the click from the count", () => {
const { click, counts } = setup();
picking.setClickCardHitTest(() => ({
sourceId: 'earthquakes',
entryId: 'eq-1',
}));
try {
click({
screenPosition: { x: 20, y: 26 },
topHit: null,
drawHit: null,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.ok(
picking.isUnderOtherCard({ screenPosition: { x: 1, y: 1 } }, ['cctv']),
);
assert.equal(counts()[0], 0, 'count flight ran under another layer card');
} finally {
picking.setClickCardHitTest(null);
}
});
@@ -0,0 +1,96 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
function run({ aspectRatio, fovy, eye, pairs, groundM }) {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: eye }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: Math.round(600 * aspectRatio) },
});
try {
const members = [];
const cells = pairs.map(({ eastM = 0, northM = 0, h }, i) => {
const cell = createCameraCell(String(i));
for (const d of [0, 10]) {
const m = { lon: (eastM + d) / M, lat: northM / M, h };
addCellCamera(cell, { lat: m.lat, lon: m.lon, absoluteHeightM: h });
members.push(m);
}
cell.groundM = h;
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 420, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
groups[0].groundM = groundM;
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
const { range } = flights[0].options.offset;
const c = toLonLatH(flights[0].bounds.center);
const eyeH = c.height + range;
const tanY = Math.tan(fovy / 2);
const inFrame = members.filter((m) => {
const depth = eyeH - m.h;
if (!(depth > 0)) return false;
return (
Math.abs((m.lon - c.lon) * M) <= depth * tanY * aspectRatio &&
Math.abs((m.lat - c.lat) * M) <= depth * tanY
);
});
return { range, inFrame: inFrame.length, centerH: c.height };
} finally {
unbind();
}
}
test('a count click on pairs 300 m above the ground under the group centre keeps a member in the frame', () => {
const aspectRatio = 4 / 3;
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio);
const r = run({
aspectRatio,
fovy,
eye: fromDegrees(0, 0, 900),
pairs: [
{ eastM: 3000, h: 800 },
{ eastM: 5000, h: 800 },
],
groundM: 500,
});
const flat = run({
aspectRatio,
fovy,
eye: fromDegrees(0, 0, 900),
pairs: [
{ eastM: 3000, h: 500 },
{ eastM: 5000, h: 500 },
],
groundM: 500,
});
assert.equal(flat.inFrame, 4);
assert.ok(r.inFrame > 0, `no member in frame: ${JSON.stringify(r)}`);
});
@@ -0,0 +1,84 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addCellCamera,
createCameraCell,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { createNavigation } from './navigation.js';
const M = 111_320;
function run({ aspectRatio, fovy, eye, pairs, groundM }) {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy, aspectRatio, position: eye }),
flyToBounds: (bounds, options) => flights.push({ bounds, options }),
},
canvas: { clientHeight: 600, clientWidth: Math.round(600 * aspectRatio) },
});
try {
const members = [];
const cells = pairs.map(({ eastM = 0, northM = 0, h }, i) => {
const cell = createCameraCell(String(i));
for (const d of [0, 10]) {
const m = { lon: (eastM + d) / M, lat: northM / M, h };
addCellCamera(cell, { lat: m.lat, lon: m.lon, absoluteHeightM: h });
members.push(m);
}
cell.groundM = h;
return cell;
});
const screens = [
{ x: 400, y: 300 },
{ x: 420, y: 300 },
];
const groups = mergeCountCells(
cells,
() => screens.shift(),
() => ({ width: 40, height: 40 }),
2,
);
assert.equal(groups.length, 1);
groups[0].groundM = groundM;
createNavigation({ state: { _viewer: viewer }, parts: {} }).zoomToCell(
groups[0],
);
const { range } = flights[0].options.offset;
const c = toLonLatH(flights[0].bounds.center);
const eyeH = c.height + range;
const tanY = Math.tan(fovy / 2);
const inFrame = members.filter((m) => {
const depth = eyeH - m.h;
if (!(depth > 0)) return false;
return (
Math.abs((m.lon - c.lon) * M) <= depth * tanY * aspectRatio &&
Math.abs((m.lat - c.lat) * M) <= depth * tanY
);
});
return { range, inFrame: inFrame.length, centerH: c.height };
} finally {
unbind();
}
}
test('a count click on a north-south group in a 32:9 window keeps every member in the frame', () => {
const aspectRatio = 32 / 9;
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / aspectRatio);
const r = run({
aspectRatio,
fovy,
eye: fromDegrees(0, 0, 800),
pairs: [
{ northM: 15_000, h: 8 },
{ northM: 17_000, h: 8 },
],
groundM: 8,
});
assert.equal(r.inFrame, 4, JSON.stringify(r));
});
+145
View File
@@ -0,0 +1,145 @@
import { test, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
const W = 800;
const H = 600;
const A = 6378137;
// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture).
const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 });
const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI;
const matrix = new Float64Array([
0,
0,
0,
0,
2 / (30 * W),
0,
0,
0,
0,
2 / (30 * H),
0,
0,
0,
0,
0,
1,
]);
function cellAt(key, x, count, height = 0, y = H / 2) {
const cell = createCameraCell(key);
for (let i = 0; i < count; i++)
addCellCamera(cell, {
lon: lonFor(x),
lat: (Math.asin(((H / 2 - y) * 30) / A) * 180) / Math.PI,
absoluteHeightM: height,
});
return cell;
}
let painter;
function makeCtx() {
return {
labels: [],
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
roundRect() {},
stroke() {},
fill() {},
drawImage() {},
fillText(text, x, y) {
this.labels.push({ text, x, y, alpha: this.globalAlpha });
},
};
}
function paint(overrides = {}) {
const ctx = makeCtx();
painter({
ctx,
width: W,
height: H,
dpr: 1,
viewProjectionMatrix: matrix,
occluder: { isPointVisible: () => true },
overlapsHardUi: () => false,
...overrides,
});
return ctx.labels;
}
function counts(refresh = () => {}, keyholeAlpha) {
return createCountMarkers(
(_lane, paintFn) => {
painter = paintFn;
return { requestPaint() {}, setActive() {}, unregister() {} };
},
'counts',
refresh,
keyholeAlpha,
);
}
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 7,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
});
// 75 counts in five staggered rows, no lone cameras and no active camera,
// pan right 7 CSS px per frame for 60 frames past a left HUD rail. Counts must
// still hide and reappear at the rail, but the paint must not start a full
// view pass on almost every frame: the motion timer passes the view every
// 250 ms, about 4 times in these 60 frames at 60 Hz.
test('a pan past the HUD edge does not pass the view on every frame', async () => {
const run = async (hud) => {
const cells = [];
for (let row = 0; row < 5; row++)
for (let col = 0; col < 15; col++)
cells.push(
cellAt(
`r${row}c${String(col).padStart(2, '0')}`,
30 + col * 50 + row * 10,
2,
0,
120 + row * 60,
),
);
let refreshes = 0;
let hiddenFrames = 0;
const m = counts(() => refreshes++);
m.update(cells, project);
for (let f = 0; f < 60; f++) {
const panned = matrix.slice();
panned[12] = (2 * (f * 7)) / W;
const labels = paint({ ...hud, viewProjectionMatrix: panned });
if (labels.length < 75) hiddenFrames++;
await Promise.resolve();
}
m.dispose();
return { refreshes, hiddenFrames };
};
const control = await run({});
const withHud = await run({ overlapsHardUi: (rect) => rect.x < 150 });
assert.equal(control.refreshes, 0);
assert.ok(withHud.hiddenFrames > 0, 'the HUD hides no count');
assert.ok(
withHud.refreshes <= 4,
`${withHud.refreshes} full view passes from paint in 60 frames`,
);
});
@@ -0,0 +1,59 @@
import * as picking from '../../data/pickRegistry.js';
import { CCTV_COUNT_CARD_SOURCE_ID } from '../../data/cctvCards.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
// Earthquake discs (like fire perimeters and drone airspace) are deliberately
// unowned background fills. A clean tap on a count painted over a disc must
// zoom to the count and be the card on top for every layer, so Earthquakes
// opens no card. An owned scene object (an aircraft) still takes the click.
test('a count over an earthquake disc takes the click', () => {
let zooms = 0;
let clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({ key: 'g' }) },
_cctvOverlayHost: { hitTest: () => null },
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
const event = (hit) => ({
screenPosition: { x: 20, y: 26 },
topHit: hit,
drawHit: hit,
hit,
gesture: { travelPx: 0, durationMs: 20 },
});
picking.registerClickClaim('cctv', selection.countClickCard);
picking.registerPickOwner('flights', (id) => id.startsWith('aircraft:'));
try {
const disc = event({ set: 'earthquakes:1:discs', id: 'earthquake:abc' });
assert.deepEqual(picking.clickCard(disc), {
sourceId: CCTV_COUNT_CARD_SOURCE_ID,
entryId: 'g',
});
click(disc);
assert.deepEqual([zooms, clicks], [1, 0]);
const aircraft = event({ set: 'flights:icons', id: 'aircraft:abc' });
assert.equal(picking.clickCard(aircraft), null);
click(aircraft);
assert.deepEqual([zooms, clicks], [1, 1]);
} finally {
picking.unregisterClickClaim('cctv');
picking.unregisterPickOwner('flights');
}
});
+31
View File
@@ -139,3 +139,34 @@ test('same pixels at a new aspect redraw at the new fit', () => {
]);
assert.equal(runtime.canvasStamp, 2);
});
test('same pixels at a new resolution with the same fit skip the redraw', () => {
const { runtime, load } = stillHarness();
load(640, 480);
assert.deepEqual(load(1280, 960), []);
assert.equal(runtime.canvasStamp, 1);
assert.equal(runtime.drawnImageStamp, 2);
});
test('changed pixels redraw even when the fitted rectangle is unchanged', () => {
const { runtime, load } = stillHarness();
load(640, 480);
const changedPixels = new Uint8ClampedArray(
FRAME_SIGNATURE_W * FRAME_SIGNATURE_H * 4,
).fill(90);
runtime.signatureCtx.getImageData = () => ({ data: changedPixels });
const calls = load(640, 480);
assert.equal(calls[0][0], 'fillRect');
assert.deepEqual(calls[1], ['drawImage', 240, 0, 1440, 1080]);
assert.equal(runtime.canvasStamp, 2);
});
test('a failed pixel signature redraws rather than assuming equal content', () => {
const { runtime, load } = stillHarness();
load(640, 480);
runtime.signatureCtx.getImageData = () => {
throw new Error('tainted canvas');
};
assert.deepEqual(load(640, 480).at(-1), ['drawImage', 240, 0, 1440, 1080]);
assert.equal(runtime.canvasStamp, 2);
});
+77 -47
View File
@@ -1,4 +1,4 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { findGlobe } from '../../render/rendererOf.js';
import {
SUPPORT_KEYS,
@@ -22,11 +22,12 @@ export function createGround({ state: layerState, services, parts, source }) {
* - `google-3d` — photoreal stack: globe hidden, the visible Google 3D
* tileset IS the surface → one-shot scene sampling refines.
* - `terrain-globe` — any globe stack: the Re:Earth point-height prior IS the
* resolution (zero scene queries).
* resolution. A camera the batch left unanswered takes the
* drawn terrain from the view pass (`adoptDrawnGround`).
*
* Only an explicit `false` (the photoreal stack hides the globe) selects
* `google-3d`; undefined/null (no viewer / torn down) must fall to the regime
* that never touches the scene. Pure — exported for the unit suite.
* that never samples the scene's tiles. Pure — exported for the unit suite.
* @param {boolean|undefined|null} globeShow - Whether the renderer shows the
* globe (`globe.isGlobeVisible()`).
* @returns {'google-3d'|'terrain-globe'}
@@ -214,56 +215,84 @@ export function createGround({ state: layerState, services, parts, source }) {
let applied = 0;
let moved = 0;
for (let i = 0; i < records.length && i < priors.length; i++) {
const record = records[i];
const prior = priors[i];
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) continue;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) continue;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (record.position) {
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
);
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
moved += 1;
}
continue;
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
applied += 1;
} else if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
applied += 1;
}
const outcome = applyGroundPrior(records[i], priors[i]);
if (outcome === 'moved') moved += 1;
else if (outcome === 'applied') applied += 1;
}
if (moved && parts.rendering.refreshHorizonCulling())
parts.geometryQueue.enqueueViewGeometry();
if (applied || moved) parts.presentation.notifyListeners();
}
/**
* Gives one live record a ground prior: `'moved'` when only its icon went
* onto the prior in place, `'applied'` when its geometry was recomputed,
* null when nothing changed. Pure recomputes, no scene queries.
*/
function applyGroundPrior(record, prior) {
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) return null;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) return null;
// The drawn terrain beats a fallback. Only a real batch answer replaces it.
if (
prior.source === 'geoid-fallback' &&
record.groundPrior?.source === 'drawn-terrain'
)
return null;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (!record.position) return null;
// In place: the record keeps its position object.
fromDegreesInto(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
record.position,
);
parts.rendering.moveCameraIcon(record);
return 'moved';
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
return 'applied';
}
if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
return 'applied';
}
return null;
}
/**
* Applies drawn terrain as a drawn-terrain prior. The read records the eye
* distance (rangeM), globe surface version (surface) and whether terrain
* loading had finished (settled). Reading from under half that range or
* receiving a later Re:Earth answer replaces the height.
* @returns {'moved'|'applied'|null} As `applyGroundPrior`.
*/
function adoptDrawnGround(record, heightM, read) {
return applyGroundPrior(record, {
ellipsoid: heightM,
source: 'drawn-terrain',
...read,
});
}
/**
* Task 5: surface-regime change handler ('gev:map-stack-changed'
* CustomEvent, dispatched by main.js from MapStackController.onChange). The
@@ -399,6 +428,7 @@ export function createGround({ state: layerState, services, parts, source }) {
resolveCommittedGroundAnchor,
resolveGroundPriors,
applyLateGroundPriors,
adoptDrawnGround,
handleMapStackChanged,
};
}
+64
View File
@@ -0,0 +1,64 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createGround } from './ground.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
function setup(record) {
const calls = { culling: 0, geometry: [], notify: 0 };
const state = {
_viewer: null,
_recordById: new Map([[record.camera.id, record]]),
};
const parts = {
rendering: {
refreshHorizonCulling: () => (calls.culling++, true),
moveCameraIcon() {},
},
geometryQueue: { enqueueViewGeometry() {} },
presentation: { notifyListeners: () => calls.notify++ },
geometry: {
// Same choice as geometry.updateRecordGeometry on a globe with a cold floor cell.
updateRecordGeometry(r) {
calls.geometry.push(
ground.groundPriorAltFor(r) + r.camera.mountHeightM,
);
},
},
};
const ground = createGround({
state,
services: {
ground: { resolveGroundFloorCells: async () => {} },
terrain: { resolveEllipsoidalGround: async () => [] },
},
parts,
});
return { ground, calls };
}
test('a late geoid fallback leaves a drawn-terrain height in place', () => {
const camera = {
id: 'a',
lat: 42,
lon: -118,
mountHeightM: 8,
absoluteHeightM: 1880,
};
const record = {
camera,
position: fromDegrees(camera.lon, camera.lat, 1880),
frustumGeometry: {},
frustumPositions: {},
groundSamples: {},
groundResolved: {},
groundPrior: { ellipsoid: 1872, source: 'drawn-terrain', rangeM: 2000 },
};
const { ground, calls } = setup(record);
ground.applyLateGroundPriors(
[record],
[{ ellipsoid: 0, source: 'geoid-fallback' }],
);
assert.equal(record.groundPrior.source, 'drawn-terrain');
assert.ok(!calls.geometry.includes(8), 'mount not lowered to the fallback');
});
+45 -6
View File
@@ -1,6 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance, dot } from '../../geo/vector.js';
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { canvasOf, findCamera, findGlobe } from '../../render/rendererOf.js';
import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js';
@@ -23,8 +23,14 @@ export function createLifecycle({
source,
}) {
const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
services.picking;
const {
resolvePickId,
registerPickOwner,
unregisterPickOwner,
clickCard,
registerClickClaim,
unregisterClickClaim,
} = services.picking;
const { onFocusTargetAppear } = services.focus;
const { releaseContinuousRender } = services.render;
@@ -103,6 +109,30 @@ export function createLifecycle({
* listeners to its camera; one against the same viewer keeps them.
*/
function attachViewListeners() {
const globe = findGlobe(layerState._viewer);
if (layerState._surfaceListenerGlobe !== globe) {
layerState._surfaceListener?.();
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = globe;
}
if (!layerState._surfaceListener && globe?.on) {
// Refresh drawn heights when terrain finishes loading or the surface changes.
let version = globe.surfaceVersion?.();
let terrainPending = globe.isSettled?.('terrain') === false ? 1 : 0;
layerState._surfaceListener = globe.on('progress', (progress) => {
const next = globe.surfaceVersion?.();
const loaded = progress?.terrainPending === 0 && terrainPending !== 0;
const swapped = next !== version;
version = next;
terrainPending = progress?.terrainPending ?? terrainPending;
if (
(loaded || swapped) &&
layerState._enabled &&
!layerState._cameraMoving
)
settleView();
});
}
const viewCamera = findCamera(layerState._viewer);
if (
layerState._viewListenerCamera &&
@@ -140,6 +170,9 @@ export function createLifecycle({
/** Drop the move listeners; nothing reports the end of a move after it. */
function detachViewListeners() {
layerState._surfaceListener?.();
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = null;
layerState._horizonCullListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener?.();
@@ -163,9 +196,11 @@ export function createLifecycle({
layerState._records = [];
layerState._recordById = new Map();
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
layerState._coverageCohort = null;
layerState._viewUnpublished = false;
layerState._viewPose = null;
layerState._viewMotionPass = null;
@@ -285,9 +320,8 @@ export function createLifecycle({
coverageEntities: [],
projection: null,
// Task 5 (height-datum fix): regime-aware ground resolution state.
// groundPrior — { ellipsoid, source } from the Re:Earth batch
// (null until a late batch lands). The prior applies in EVERY
// regime and is the terrain-globe resolution outright.
// groundPrior — { ellipsoid, source } from the Re:Earth batch, or
// drawn-terrain with its read conditions for an unanswered camera.
// groundResolved — PER-REGIME one-shot latch (regime key →
// boolean): true once this record's resolution completed for that
// regime; such records are excluded from the completion pass so
@@ -386,6 +420,7 @@ export function createLifecycle({
parts.rendering.refreshHorizonCulling();
const input = inputFor(layerState._viewer);
layerState._clickSubscription?.();
const unsubscribeClick = parts.selection.bindCctvWorldClickGesture(
input,
(event) => {
@@ -481,6 +516,7 @@ export function createLifecycle({
);
return Boolean(coverage && layerState._recordById.has(coverage[1]));
});
registerClickClaim?.('cctv', parts.selection.countClickCard);
if (!layerState._activeCameraId && layerState._records.length) {
layerState._activeCameraId = parts.navigation.openingCameraId();
layerState._autoHopSuspended = false;
@@ -517,6 +553,7 @@ export function createLifecycle({
services.credits?.hideOsmCredit?.(layerState._viewer, 'cctv');
layerState._enabled = false;
unregisterPickOwner('cctv');
unregisterClickClaim?.('cctv');
// ADJUST mode does not survive a layer toggle — predictable re-entry.
layerState._calibrationMode = false;
releaseContinuousRender('cctv-adjust');
@@ -532,6 +569,7 @@ export function createLifecycle({
parts.rendering.hideCctvVisuals();
// Nothing is in view while the layer is off.
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
parts.presentation.notifyListeners();
},
@@ -550,6 +588,7 @@ export function createLifecycle({
parts.cards.handleVisibilityChange,
);
unregisterPickOwner('cctv');
unregisterClickClaim?.('cctv');
if (layerState._mapStackListener && typeof window !== 'undefined') {
window.removeEventListener(
'gev:map-stack-changed',
+34
View File
@@ -77,6 +77,40 @@ test('the view listeners follow the camera port and let go on teardown', () => {
assert.equal(state._viewListenerCamera, null);
});
test('terrain loading and surface changes rerun the view pass', () => {
const viewer = {};
let version = 1,
progress,
removed = false;
bindRenderer(viewer, {
camera: fakeCameraPort().port,
globe: {
surfaceVersion: () => version,
on(event, cb) {
assert.equal(event, 'progress');
progress = cb;
return () => {
removed = true;
};
},
},
});
const { lifecycle, passes } = lifecycleFor({
_viewer: viewer,
_enabled: true,
});
lifecycle.attachViewListeners();
progress({ terrainPending: 2 });
assert.equal(passes.length, 0);
progress({ terrainPending: 0 });
assert.equal(passes.length, 1);
version++;
progress({ terrainPending: 0 });
assert.equal(passes.length, 2);
lifecycle.detachViewListeners();
assert.ok(removed);
});
/** A part whose members are `own`'s, and any other a function that does
* nothing. */
const inert = (own = {}) =>
+64 -57
View File
@@ -456,33 +456,60 @@ const BRAND_ALIASES = {
Hikvision: ['hiwatch'],
};
function brandWords(record) {
return new Set([
...words(record.brand),
...(BRAND_ALIASES[record.brand] || []),
]);
}
/**
* One entry per record name (model + aliases). `required` is every
* non-generic word of the name — all must appear in a query, so a generation
* or suffix ("Mk II", "7000i" vs "7000") is never dropped. `hasCode` marks
* names carrying a letter+digit model code; names without one ("3950",
* "01959-004", "AUTODOME 800 Series") match only when the brand does.
*/
const NAME_INDEX = RECORDS.flatMap((record) => {
const brand = brandWords(record);
return [record.model, ...(record.aliases || [])].map((name) => {
const nameWords = words(name);
return {
record,
brand,
allowed: new Set(nameWords),
required: nameWords.filter((word) => !isGeneric(word)),
hasCode: nameWords.some(isModelCode),
};
/** A model lookup over `records` with this module's matching rules (see lookupModelSpec). */
export function createModelSpecLookup(records) {
/**
* One entry per record name (model + aliases). `required` is every
* non-generic word of the name — all must appear in a query, so a
* generation or suffix ("Mk II", "7000i" vs "7000") is never dropped.
* `hasCode` marks names carrying a letter+digit model code; names without
* one ("3950", "01959-004", "AUTODOME 800 Series") match only when the
* brand does.
*/
const nameIndex = records.flatMap((record) => {
const brand = new Set([
...words(record.brand),
...(BRAND_ALIASES[record.brand] || []),
]);
return [record.model, ...(record.aliases || [])].map((name) => {
const nameWords = words(name);
return {
record,
brand,
allowed: new Set(nameWords),
required: nameWords.filter((word) => !isGeneric(word)),
hasCode: nameWords.some(isModelCode),
};
});
});
});
return (model, manufacturer) => {
const query = words(model).map(stripVariantSuffix);
if (!query.length) return null;
const maker = words(manufacturer);
const found = new Set();
for (const entry of nameIndex) {
const makerMatches = maker.some((word) => entry.brand.has(word));
if (maker.length && !makerMatches) continue;
if (
!entry.hasCode &&
!makerMatches &&
!query.some((word) => entry.brand.has(word))
)
continue;
if (!entry.required.length) continue;
if (!entry.required.every((word) => query.includes(word))) continue;
if (
!query.every(
(word) =>
entry.allowed.has(word) || entry.brand.has(word) || isGeneric(word),
)
)
continue;
found.add(entry.record);
}
return found.size === 1 ? [...found][0] : null;
};
}
/**
* Looks up a spec record for a hardware-model string.
@@ -502,33 +529,7 @@ const NAME_INDEX = RECORDS.flatMap((record) => {
* @param {string} [manufacturer] - The source's manufacturer, when published.
* @returns {Object|null} The matched spec record, or null when unknown.
*/
export function lookupModelSpec(model, manufacturer) {
const query = words(model).map(stripVariantSuffix);
if (!query.length) return null;
const maker = words(manufacturer);
const found = new Set();
for (const entry of NAME_INDEX) {
const makerMatches = maker.some((word) => entry.brand.has(word));
if (maker.length && !makerMatches) continue;
if (
!entry.hasCode &&
!makerMatches &&
!query.some((word) => entry.brand.has(word))
)
continue;
if (!entry.required.length) continue;
if (!entry.required.every((word) => query.includes(word))) continue;
if (
!query.every(
(word) =>
entry.allowed.has(word) || entry.brand.has(word) || isGeneric(word),
)
)
continue;
found.add(entry.record);
}
return found.size === 1 ? [...found][0] : null;
}
export const lookupModelSpec = createModelSpecLookup(RECORDS);
/**
* Datasheet horizontal FOV as the range the hardware can cover. Only
@@ -602,13 +603,19 @@ export function specFovCapabilityToken(
/**
* One-line spec summary for HUD meta text.
* @param {Object} spec - A record from this module.
* @param {Object} spec - A spec record (CCTV or ALPR). Resolution falls back
* from label to WxH to NMP.
* @param {{withBrand?: boolean}} [options] - `withBrand: false` leaves the
* brand out.
* @returns {string} e.g. 'Axis Q6135-LE · 1080p · IR 250m · PTZ' ('' for null).
*/
export function specSummary(spec) {
export function specSummary(spec, { withBrand = true } = {}) {
if (!spec) return '';
const parts = [`${spec.brand} ${spec.model}`];
if (spec.resolution?.label) parts.push(spec.resolution.label);
const parts = [withBrand ? `${spec.brand} ${spec.model}` : spec.model];
const { label, w, h, mp } = spec.resolution || {};
if (label) parts.push(label);
else if (w && h) parts.push(`${w}x${h}`);
else if (mp) parts.push(`${mp}MP`);
if (spec.night_vision) {
parts.push(
`${spec.night_vision.type.toUpperCase()}${spec.night_vision.range_m ? ` ${spec.night_vision.range_m}m` : ''}`,
+88 -10
View File
@@ -1,6 +1,14 @@
import { distance } from '../../geo/vector.js';
import { toLonLatH } from '../../geo/ellipsoid.js';
import { rangeForBoundingSphere } from '../../data/cameraFraming.js';
import { isFollowing } from '../../data/followed.js';
import { CCTV_FOCUS_RESULT } from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
import {
cellBounds,
cellCenter,
cellHalfExtents,
} from '../../data/cctvCellCounts.js';
import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js';
import { cameraOf, canvasOf } from '../../render/rendererOf.js';
export function createNavigation({
state: layerState,
@@ -73,12 +81,21 @@ export function createNavigation({
return false;
const nearest = nearestCameraIdToViewer();
if (!nearest || nearest === layerState._activeCameraId) return false;
parts.selection.setActiveCamera(nearest);
// setActiveCamera ends the opening pick; this is still that pick.
layerState._openingCameraProvisional = true;
// Still the opening pick: later settled moves may replace it.
parts.selection.setActiveCamera(nearest, { opening: true });
return true;
}
/** What holds the view instead of a CCTV flight, or null when it is free. */
function viewHeldBy(viewer) {
if (
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode')
)
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
return isFollowing(viewer) ? CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW : null;
}
/**
* Flies the viewer's camera to frame the specified CCTV camera,
* looking along its heading from above.
@@ -90,14 +107,12 @@ export function createNavigation({
function focusCctvRecord(viewer, record, duration = 2.2) {
if (!viewer || !record) return CCTV_FOCUS_RESULT.NO_ACTIVE_CAMERA;
if (
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode')
) {
const held = viewHeldBy(viewer);
if (held === CCTV_FOCUS_RESULT.COCKPIT_ACTIVE) {
console.debug('[Data:CCTV] focus ignored while cockpit owns the camera');
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
}
if (isFollowing(viewer)) {
if (held === CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW) {
console.debug(
'[Data:CCTV] focus ignored while a tracked entity owns the camera',
);
@@ -120,6 +135,68 @@ export function createNavigation({
return CCTV_FOCUS_RESULT.FOCUSED;
}
/** The nearest ground cell with two or more cameras, or the group itself if unmerged. */
function nearestPart(cell, eye) {
let nearest = cell;
let best = Infinity;
for (const part of cell.parts ?? []) {
if (part.count < 2) continue;
const d = distance(eye, cellCenter(part));
if (d < best) {
best = d;
nearest = part;
}
}
return nearest;
}
/** Frame a group's padded bounds from above, including coincident mounts. */
function zoomToCell(cell) {
const viewer = layerState._viewer;
if (!viewer || viewHeldBy(viewer)) return;
const camera = cameraOf(viewer);
const pose = camera.pose();
const tanHalfY = Math.tan((pose.fovy || Math.PI / 3) / 2);
const canvas = canvasOf(viewer);
const height = canvas?.clientHeight || canvas?.height || 1;
// Half the range where cells stop grouping, so even coincident mounts split.
const closeRange =
(VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY);
const tanHalfX = tanHalfY * (pose.aspectRatio || 1);
// Range where a cell's ground extent, times `pad`, fits the frame at the
// depth of its highest mount above the bounds centre.
const extentRange = (target, bounds, pad = 1) => {
const { halfWidthM, halfHeightM } = cellHalfExtents(target);
const rise = Math.max(0, target.high - toLonLatH(bounds.center).height);
return (
rise + pad * Math.max(halfWidthM / tanHalfX, halfHeightM / tanHalfY)
);
};
// The sphere fit spans the wider side, so a very wide window also needs the extent.
const fitRange = (target, bounds) =>
Math.max(
closeRange,
rangeForBoundingSphere(viewer, bounds.radius),
extentRange(target, bounds, 1.2),
);
// Approach long groups in halves so every click gets closer.
const halfway = (bounds) =>
pose.position ? distance(pose.position, bounds.center) / 2 : Infinity;
let bounds = cellBounds(cell);
let range = Math.min(halfway(bounds), fitRange(cell, bounds));
// If the group overflows the frame at that range, approach its nearest counted cell.
if (range < extentRange(cell, bounds)) {
const part = nearestPart(cell, pose.position);
bounds = cellBounds(part);
range = Math.min(halfway(bounds), fitRange(part, bounds));
}
camera.flyToBounds(bounds, {
offset: { heading: 0, pitch: -Math.PI / 2, range },
durationS: 1.2,
easing: 'cubicInOut',
});
}
function focusCamera(cameraId, duration = 2.2) {
return focusCctvRecord(
layerState._viewer,
@@ -196,6 +273,7 @@ export function createNavigation({
openingCameraId,
reopenNearestCamera,
focusCctvRecord,
zoomToCell,
focusCamera,
maybeAutoHop,
cctvCycleIndex,
+66 -18
View File
@@ -60,17 +60,38 @@ export const GEO_PROGRESS_NOTIFY_INTERVAL_MS = 300;
export const GEO_PROGRESS_NOTIFY_BATCH_LIMIT = 10;
// View thinning: camera icons show only on or near the screen, and each
// camera competes for a world-anchored grid cell sized to about VIEW_CELL_PX
// at its distance from the viewer (in power-of-two metre steps, so a pan
// keeps the same winners until a camera's distance crosses a step). Cells
// smaller than VIEW_MIN_CELL_M do not thin:
// close up every camera shows, co-located ones included.
// View thinning groups cameras into world-anchored cells of about VIEW_CELL_PX
// at their distance. Power-of-two metre steps keep cells stable during a pan.
// A cell with several cameras draws one count. Its best-ranked camera represents
// it in the picker. Cells smaller than VIEW_MIN_CELL_M do not group, so
// every camera shows close up.
export const VIEW_CELL_PX = 40;
export const VIEW_MIN_CELL_M = 60;
// Cameras within this horizontal distance in metres share a mount.
export const VIEW_SITE_M = 1.5;
// Cameras on one mount (VIEW_SITE_M) draw side by side,
// this many pixels apart, once they show as icons.
export const VIEW_SITE_SPREAD_PX = 30;
// Drawn-terrain reads per view pass for unanswered cameras and for re-reads
// of drawn heights. Off-screen cameras can use at most half of the budget.
// Remaining reads wait for the next pass.
export const VIEW_GROUND_READS = 300;
/**
* The camera icon's drawn size (px). Its SVG is 48 px: 1.25×
* near scale on a 2× display draws it at 60 device px, so it is rasterised
* past the drawn size to stay sharp there.
*/
export const CAMERA_ICON_PX = 24;
// Minimum gap between the outer rims of two separate markers.
export const COUNT_MERGE_GAP_PX = 4;
// Icons this far past the screen edge (fraction of its size) still show, so
// a pan does not reveal empty ground before the next view pass.
@@ -182,28 +203,51 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({
/**
* Base64-encoded SVG camera icon for the camera icons. Icons rasterise an
* SVG at its own size, so it is 48 px: drawn at 24 px, 1.25× near scale on a
* 2× display draws it at 60 device px, and it stays sharp there.
* 2× display draws it at 60 device px, and it stays sharp there. Active and
* live cameras use cyan art with a billboard tint. Idle cameras use white
* and gray art so the billboard green shows true. The overlay draws the
* green variant directly.
*/
export const CAMERA_ICON = (() => {
function cameraIcon(tint = null) {
function tone(original, gray) {
if (!tint) return original;
const shade = parseInt(gray.slice(1, 3), 16) / 255;
return (
'#' +
tint
.slice(1)
.match(/../g)
.map((channel) =>
Math.round(parseInt(channel, 16) * shade)
.toString(16)
.padStart(2, '0'),
)
.join('')
);
}
const stroke = tone('#75e7ff', '#ffffff');
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 36 36">
<defs>
<linearGradient id="lens" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#c9f6ff"/>
<stop offset="45%" stop-color="#6fd9ff"/>
<stop offset="100%" stop-color="#1a5f78"/>
<stop offset="0%" stop-color="${tone('#c9f6ff', '#ffffff')}"/>
<stop offset="45%" stop-color="${tone('#6fd9ff', '#dddddd')}"/>
<stop offset="100%" stop-color="${tone('#1a5f78', '#666666')}"/>
</linearGradient>
</defs>
<g transform="translate(4 6)">
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="#0e1720" stroke="#75e7ff" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="#132433" stroke="#75e7ff" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="#dbfbff" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="#10212d" stroke="#75e7ff" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="#0b151d" stroke="#4ecde7" stroke-width="0.8"/>
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="${tone('#0e1720', '#181818')}" stroke="${stroke}" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="${tone('#132433', '#222222')}" stroke="${stroke}" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="${tone('#dbfbff', '#ffffff')}" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="${tone('#10212d', '#202020')}" stroke="${stroke}" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="${tone('#0b151d', '#151515')}" stroke="${tone('#4ecde7', '#cccccc')}" stroke-width="0.8"/>
</g>
</svg>`;
return 'data:image/svg+xml;base64,' + btoa(svg);
})();
}
export const CAMERA_ICON = cameraIcon();
export const IDLE_CAMERA_ICON = cameraIcon('#ffffff');
/**
* Seed camera definitions used when no live sources are available.
@@ -441,7 +485,11 @@ export const CAMERA_SEEDS = [
// Visual style constants: renderer colours, [r, g, b, a] in 0..1
// ---------------------------------------------------------------------------
export const IDLE_CAMERA_COLOR = hexColor('#6be8ff', 0.88);
/** Shared accent for idle still cameras and grouped cameras. */
export const CAMERA_GREEN = '#5dff8f';
export const COUNT_CAMERA_ICON = cameraIcon(CAMERA_GREEN);
export const IDLE_CAMERA_COLOR = hexColor(CAMERA_GREEN);
export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95);
+12 -9
View File
@@ -229,9 +229,12 @@ export function createPresentation({
// separately from the currently applied frustum ground. Google-3D may
// legitimately refine the latter to the rendered mesh, so callers must
// not infer the prior by subtracting mount height from live geometry.
groundPriorM: Number.isFinite(record.groundPrior?.ellipsoid)
? record.groundPrior.ellipsoid
: null,
// A height read from drawn terrain is unavailable as a Re:Earth prior.
groundPriorM:
Number.isFinite(record.groundPrior?.ellipsoid) &&
record.groundPrior.source !== 'drawn-terrain'
? record.groundPrior.ellipsoid
: null,
intrinsics: camera.intrinsics ? { ...camera.intrinsics } : null,
extrinsics: camera.extrinsics ? { ...camera.extrinsics } : null,
anchor: camera.anchor ? { ...camera.anchor } : null,
@@ -310,16 +313,16 @@ export function createPresentation({
}
/**
* `{ id, city, name }` for the active camera, then every camera the view
* pass shows: what the camera picker lists. A whole catalog would put tens
* of thousands of options in the DOM and slow every layout. The same array
* is returned until the view or the active camera changes, so a consumer
* can compare it by identity.
* `{ id, city, name }` for the active camera, then each camera shown as an
* icon and the best-ranked camera of each visible group. A whole catalog
* would put tens of thousands of options in the DOM and slow every layout.
* Consumers can compare the array by identity until the picker records or
* active camera change.
* @returns {{id: string, city: string, name: string}[]}
*/
function cameraIndex() {
const view = layerState._viewRecords;
const view = layerState._pickerRecords;
const active = parts.selection.getActiveRecord();
const cached = layerState._cameraIndexCache;
if (cached?.view === view && cached.active === active) return cached.list;
+416 -87
View File
@@ -1,7 +1,13 @@
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { isHeadingEstimated } from './headingConfidence.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
CAMERA_ICON_PX,
COUNT_MERGE_GAP_PX,
VIEW_SITE_M,
IDLE_CAMERA_ICON,
IDLE_CAMERA_COLOR,
LIVE_CAMERA_COLOR,
ACTIVE_COVERAGE_CENTER,
@@ -14,6 +20,8 @@ import {
VIEW_CELL_PX,
VIEW_ICON_MARGIN,
VIEW_MIN_CELL_M,
VIEW_SITE_SPREAD_PX,
VIEW_GROUND_READS,
} from './policy.js';
import { createIconBook } from '../../render/motion/iconBook.js';
import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js';
@@ -24,11 +32,21 @@ import {
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js';
import { heightsOf } from '../../queries/heights.js';
import {
fromDegrees,
fromDegreesInto,
toLonLatH,
WGS84,
} from '../../geo/ellipsoid.js';
import { eastNorthUp } from '../../geo/frames.js';
import { poseProjector } from '../../geo/frustum.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distance } from '../../geo/vector.js';
import { add, distance, dot, scale, sub } from '../../geo/vector.js';
const IDLE_ICON_STYLE = { image: IDLE_CAMERA_ICON, color: IDLE_CAMERA_COLOR };
const ACTIVE_ICON_STYLE = { image: CAMERA_ICON, color: ACTIVE_CAMERA_COLOR };
const LIVE_ICON_STYLE = { image: CAMERA_ICON, color: LIVE_CAMERA_COLOR };
/** An RGBA colour with another alpha. */
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
@@ -46,12 +64,6 @@ const samePoint = (a, b) =>
/** Degrees to radians. */
const toRadians = (degrees) => (degrees * Math.PI) / 180;
/**
* The camera icon's drawn size (px). Its SVG is 48 px (policy.js): 1.25×
* near scale on a 2× display draws it at 60 device px, so it is rasterised
* past the drawn size to stay sharp there.
*/
const CAMERA_ICON_PX = 24;
const CAMERA_SCALE_BY_DISTANCE = Object.freeze({
near: 350,
nearValue: 1.25,
@@ -139,6 +151,12 @@ export function createRendering({
// with its first camera.
set.setColumns?.({ ids: [] });
layerState._icons = createIconBook(set);
layerState._counts = createCountMarkers(
services.overlays?.registerWorldOverlayPaintLane,
`cctv:${iconSets}:counts`,
refreshViewFromCounts,
services.overlays?.keyholeAlpha,
);
return set.id;
}
@@ -146,6 +164,8 @@ export function createRendering({
function destroyCameraIcons() {
layerState._icons?.dispose();
layerState._icons = null;
layerState._counts?.dispose();
layerState._counts = null;
}
/** The icon item a camera record draws, idle and shown, at its position. */
@@ -153,10 +173,9 @@ export function createRendering({
const id = record.camera.id;
return {
id,
pos: copyPoint(record.position),
image: CAMERA_ICON,
pos: copyPoint(record.spreadPosition ?? record.position),
...cameraIconStyleFor(record),
size: [CAMERA_ICON_PX, CAMERA_ICON_PX],
color: cameraColorFor(record),
scale: 1,
scaleByDistance: CAMERA_SCALE_BY_DISTANCE,
disableDepthTest: Infinity,
@@ -195,22 +214,26 @@ export function createRendering({
function moveCameraIcon(record) {
const icons = layerState._icons;
if (!icons || !record.position) return;
// A camera drawn beside its mount mates keeps its offset from the mount.
if (record.spreadOffset)
record.spreadPosition = add(record.position, record.spreadOffset);
const pos = record.spreadPosition ?? record.position;
const item = icons.item(record.camera.id);
// A camera whose icon waited for a position is drawn now.
if (!item) {
icons.put(cameraIconItem(record));
return;
}
if (samePoint(item.pos, record.position)) return;
icons.put({ ...item, pos: copyPoint(record.position) });
if (samePoint(item.pos, pos)) return;
icons.put({ ...item, pos: copyPoint(pos) });
}
/** Icon color: active wins, then live-capable video feeds, then idle stills. */
function cameraColorFor(record) {
/** Select the sprite and tint together when a camera changes state. */
function cameraIconStyleFor(record) {
if (record.camera.id === layerState._activeCameraId)
return ACTIVE_CAMERA_COLOR;
if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_CAMERA_COLOR;
return IDLE_CAMERA_COLOR;
return ACTIVE_ICON_STYLE;
if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_ICON_STYLE;
return IDLE_ICON_STYLE;
}
const {
@@ -219,11 +242,14 @@ export function createRendering({
focusPassIsNeeded,
advanceSpriteFocus,
focusAlphaNeedsWrite,
nearFarScalarValueAtDistance,
} = services.focus;
const iconScaleAt = (range) =>
nearFarScalarValueAtDistance?.(CAMERA_SCALE_BY_DISTANCE, range) ?? 1;
/**
* Focus modulation rides the layer's existing animation loop; no additional
* scene listener is installed. Only camera-icon alpha changes here — coverage
* scene listener is installed. Camera and count icons share the fade. Coverage
* geometry and monitor-plane styling retain their established cadence.
*/
@@ -276,61 +302,76 @@ export function createRendering({
let writes = 0;
let transitioning = false;
let activeCount = 0;
for (const record of records || []) {
const id = record.camera?.id;
const item = icons?.item(id);
if (!item) continue;
const position = record.position;
const scale = item.scale ?? 1;
// CCTV never publishes a tracked focus target, so every icon is ambient.
const focus = advanceSpriteFocus(item.meta, {
// Keep hidden icons in the state/release pass so the active count cannot
// drop while a stale dim alpha remains waiting to reappear.
screenPosition:
item.show === false || !position ? null : screenPositionFor(position),
/**
* A changed focus factor for an icon or count. CCTV publishes no tracked
* focus target, so every icon is ambient.
*/
function changedFocus(owner, position, shown, width, height, current) {
const focus = advanceSpriteFocus(owner, {
// Keep hidden owners in the active count until their dim alpha clears,
// so the focus pass keeps running while they recover.
screenPosition: shown && position ? screenPositionFor(position) : null,
cameraDistance: position ? cameraDistanceFor(position) : Number.NaN,
nowMs,
target,
params,
spriteHalfWidthPx: item.size[0] * scale * 0.5,
spriteHalfHeightPx: item.size[1] * scale * 0.5,
spriteHalfWidthPx: width / 2,
spriteHalfHeightPx: height / 2,
});
transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1;
// Order-independent narrow amendment to always-visible icons: CCTV
// contacts retain a non-zero floor while yielding near the tracked target.
if (focusAlphaNeedsWrite(icons.focus(id), focus.factor, params)) {
icons.setFocus(id, focus.factor);
writes += 1;
}
if (focus.active) activeCount++;
if (!focusAlphaNeedsWrite(current, focus.factor, params)) return null;
writes++;
return focus.factor;
}
for (const record of records || []) {
const id = record.camera?.id;
const item = icons?.item(id);
if (!item) continue;
const scale = item.scale ?? 1;
const factor = changedFocus(
item.meta,
record.position,
item.show !== false,
item.size[0] * scale,
item.size[1] * scale,
icons.focus(id),
);
if (factor !== null) icons.setFocus(id, factor);
}
const counts = layerState._counts;
const iconWrites = writes;
for (const marker of counts?.markers ?? []) {
const factor = changedFocus(
marker,
marker.pos,
true,
marker.width,
marker.height,
marker.focus,
);
if (factor !== null) marker.focus = factor;
}
if (writes > iconWrites) counts.requestPaint();
return { writes, transitioning, activeCount, ran: true };
}
/** During camera motion the timer and settle pass refresh the counts. */
function refreshViewFromCounts() {
if (!layerState._cameraMoving) refreshHorizonCulling();
}
/**
* Updates visual styles (colors, widths, visibility) for all camera icons,
* coverage polylines, viewshed volumes, and projection entities based on which
* camera is active, whether the layer is enabled, and the current
* coverage-mode/projection toggle states.
*/
/**
* Field-test fix (2026-07-06): horizon-culls camera icons on the CPU as the
* icon shader does on the GPU. With the globe hidden (Google-3D
* regime) nothing writes far-side depth and the icons are always-on-top, so
* the shown set (cards, geometry, the picker) must not include London's
* cluster from a US viewpoint.
*
* The same pass thins the view so a large catalog stays readable and cheap:
* icons well off screen hide, and each camera competes for a world-anchored
* cell sized to VIEW_CELL_PX at its distance (healthiest first, then a stable
* id order). The active camera shows whenever it is above the horizon
* and near the screen, even in a crowded cell. The shown records become
* `_viewRecords`, the working set for geometry, cards and the camera picker;
* the array keeps its identity while the shown set is unchanged.
* Cull far-side cameras on the CPU because the hidden globe writes no depth.
* Group the rest by ground cell. _viewRecords holds the active camera and
* every nearby icon outside a count for geometry and cards. Cells smaller
* than VIEW_MIN_CELL_M do not form groups. _pickerRecords adds the
* best-ranked camera of each visible cell. Both arrays keep their identity
* while their contents are unchanged.
*
* Runs on camera settle, throttled during motion, on resize, enable and
* activation changes — never per frame.
* @returns {boolean} Whether the shown set changed.
* @returns {boolean} Whether the shown set or the picker list changed.
*/
function refreshHorizonCulling() {
@@ -365,7 +406,30 @@ export function createRendering({
const project = screenProjector(pose, width, height);
const pass = (layerState._viewPassId = (layerState._viewPassId || 0) + 1);
const shown = [];
const picker = [];
const cells = new Map();
const visibleCells = [];
// Drawn terrain where the globe is the surface. The photoreal stack has
// no reader, and unloaded tiles return a non-finite height.
const heights = heightsOf(layerState._viewer);
const globe = findGlobe(layerState._viewer);
const groundHeight =
findQuery(layerState._viewer) && globe?.isGlobeVisible?.() === true
? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' })
: null;
const surface = globe?.surfaceVersion?.() ?? 0;
const terrainSettled = globe?.isSettled?.('terrain') ?? true;
let groundReads = groundHeight ? VIEW_GROUND_READS : 0;
let offscreenReads = groundReads / 2;
let eyeGround;
const column = { x: 0, y: 0, z: 0 };
const inReadWindow = (s) =>
s &&
s.x >= -width &&
s.x <= 2 * width &&
s.y >= -height &&
s.y <= 2 * height;
const regrounded = [];
for (const record of layerState._records) {
const position = record.position;
if (!position) continue;
@@ -380,48 +444,307 @@ export function createRendering({
(vtDotVc * vtDotVc) / (vx * vx + vy * vy + vz * vz) > limbSquared
)
continue;
const screen = project(position);
let screen = project(position);
let range = distance(position, viewer);
// Missing, unresolved and fallback priors can put a mount kilometres
// below the terrain, shifting its projection and inflating its cell.
// Read nearby mounts again from under half the range, on finer terrain
// after loading, or on a different surface.
const prior = record.groundPrior;
const drawn = prior?.source === 'drawn-terrain';
const unanswered =
!Number.isFinite(prior?.ellipsoid) || prior.source === 'geoid-fallback';
if (
!screen ||
!(screen.x >= minX && screen.x <= maxX) ||
!(screen.y >= minY && screen.y <= maxY)
)
continue;
const dx = position.x - viewer.x;
const dy = position.y - viewer.y;
const dz = position.z - viewer.z;
const cellM =
VIEW_CELL_PX *
metresPerPixelPerMetre *
Math.sqrt(dx * dx + dy * dy + dz * dz);
if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) {
record.viewPass = pass;
groundReads > 0 &&
!record.regroundPending &&
(unanswered ||
(drawn &&
(prior.rangeM > 2 * range ||
prior.surface !== surface ||
(!prior.settled && terrainSettled))))
) {
let probe = inReadWindow(screen) ? screen : null;
if (!probe && unanswered) {
// Its height is a guess. Try the ground under the eye instead.
if (eyeGround === undefined) {
const eye = toLonLatH(viewer);
eyeGround = eye ? (groundHeight(eye.lon, eye.lat) ?? null) : null;
groundReads--;
}
if (Number.isFinite(eyeGround)) {
fromDegreesInto(
record.camera.lon,
record.camera.lat,
eyeGround + (record.camera.mountHeightM || 0),
column,
);
const at = project(column);
if (inReadWindow(at)) probe = at;
}
}
const onScreen =
probe &&
probe.x >= 0 &&
probe.x <= width &&
probe.y >= 0 &&
probe.y <= height;
if (probe && groundReads > 0 && (onScreen || offscreenReads > 0)) {
groundReads--;
if (!onScreen) offscreenReads--;
const ground = groundHeight(record.camera.lon, record.camera.lat);
if (Number.isFinite(ground)) {
const read = { rangeM: range, surface, settled: terrainSettled };
if (drawn && Math.abs(ground - prior.ellipsoid) < 1)
Object.assign(prior, read);
else if (record.frustumGeometry) {
// Recomputing geometry writes draw sets after this pass.
record.regroundPending = true;
regrounded.push([record, ground, read]);
} else parts.ground.adoptDrawnGround(record, ground, read);
}
}
// The probe reuses the projector's result, and the mount may have moved.
screen = project(position);
range = distance(position, viewer);
}
const nearScreen =
screen &&
screen.x >= minX &&
screen.x <= maxX &&
screen.y >= minY &&
screen.y <= maxY;
const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range;
if (record.camera.id === activeId) {
if (!nearScreen) continue;
record.viewPass = record.pickerPass = pass;
shown.push(record);
picker.push(record);
continue;
}
if (!(cellM >= VIEW_MIN_CELL_M)) {
if (!nearScreen) continue;
// Too close to group, but a count beside it can still take it in.
const cell = createCameraCell(`near:${record.camera.id}`);
addCellCamera(cell, record.camera);
cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range);
cell.winner = record;
cell.rank = 0;
record.viewCell = cell;
visibleCells.push(cell);
continue;
}
const key = worldCellKey(record, cellM);
let cell = cells.get(key);
if (!cell) {
cell = createCameraCell(key);
cells.set(key, cell);
}
addCellCamera(cell, record.camera);
if (cell.count === 1) cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range);
record.viewCell = cell;
if (!nearScreen) continue;
// The picker ranks only candidates that were in its padded viewport.
if (!cell.winner) visibleCells.push(cell);
const rank = viewRank(record);
const holder = cells.get(key);
if (!holder || rank < holder.rank) cells.set(key, { record, rank });
if (rank < cell.rank) {
cell.winner = record;
cell.rank = rank;
}
}
for (const { record } of cells.values()) {
record.viewPass = pass;
shown.push(record);
// Check each mount mate against counts where its icon will be drawn.
const lone = visibleCells.filter((cell) => cell.count === 1);
spreadSharedMounts(
shown.concat(lone.map((cell) => cell.winner)),
pose,
metresPerPixelPerMetre,
pass,
);
for (const cell of lone)
cell.offsetPx =
cell.winner.spreadPass === pass ? cell.winner.spreadPx : 0;
// A count stands on the drawn terrain too: its cell may be too far for
// its cameras to have been read. Marks each lone camera that a count
// marker beside it has taken in.
layerState._counts?.update(visibleCells, project, groundHeight);
for (const cell of visibleCells) {
const record = cell.winner;
picker.push(record);
record.pickerPass = pass;
if (cell.count === 1 && !cell.absorbed) {
record.viewPass = pass;
shown.push(record);
}
}
clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass);
const writes = [];
let coverageChanged = false;
let cardsChanged = false;
for (const record of layerState._records) {
const item = patchedCameraIcon(record.camera.id, {
show: record.viewPass === pass,
});
const cell = record.viewCell;
record.viewCell = null;
const grouped = Boolean(
cell?.winner && (cell.count > 1 || cell.absorbed),
);
if (grouped !== !!record.viewGrouped) {
const id = record.camera.id;
coverageChanged ||= layerState._coverageCohort?.has(id);
cardsChanged ||=
layerState._cardIds?.has(id) || layerState._hoverCardId === id;
}
record.viewGrouped = grouped;
const fields = { show: record.viewPass === pass };
if (record.spreadPass === pass) {
const drawn = layerState._icons?.item(record.camera.id)?.pos;
if (!drawn || !samePoint(drawn, record.spreadPosition))
fields.pos = copyPoint(record.spreadPosition);
} else if (record.spreadPosition) {
// No longer beside a mount mate: back onto its own position.
record.spreadOffset = null;
record.spreadPosition = null;
fields.pos = copyPoint(record.position);
}
const item = patchedCameraIcon(record.camera.id, fields);
if (item) writes.push(item);
}
writeCameraIcons(writes);
if (regrounded.length) queueMicrotask(() => reground(regrounded));
const previous = layerState._viewRecords;
const changed =
previous.length !== shown.length ||
previous.some((record) => record.viewPass !== pass);
if (changed) layerState._viewRecords = shown;
return changed;
const oldPicker = layerState._pickerRecords ?? [];
const pickerChanged =
picker.length !== oldPicker.length ||
oldPicker.some((record) => record.pickerPass !== pass);
if (pickerChanged) layerState._pickerRecords = picker;
if (coverageChanged) refreshCoverageStyles();
if (cardsChanged) parts.cards.pushAmbientCardEntries();
return changed || pickerChanged;
}
/**
* Cameras that have geometry take the drawn terrain after the pass that
* read it, then the view is passed again from their new positions.
*/
function reground(entries) {
let changed = false;
for (const [record, ground, read] of entries) {
record.regroundPending = false;
changed =
parts.ground.adoptDrawnGround(record, ground, read) !== null || changed;
}
if (!changed) return;
if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry();
parts.presentation.notifyListeners();
}
/**
* Cameras on one mount would draw as one icon with several callouts. Among
* icon candidates, those within VIEW_SITE_M horizontally get draw positions
* side by side in id order, `VIEW_SITE_SPREAD_PX` apart on screen. A mate
* absorbed by a count keeps its place in the row. Geometry and cards stay
* on the mount.
*/
function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) {
const { right, direction, position: eye } = pose;
if (!right || !direction || shown.length < 2) return;
const grid = new Map();
const mounts = [];
const axes = eastNorthUp(eye);
for (const record of shown) {
// Sea-level coordinates compare horizontal distance across longitude
// and latitude boundaries, including the antimeridian.
const p = fromDegrees(record.camera.lon, record.camera.lat, 0);
const col = Math.floor(dot(p, axes.x) / VIEW_SITE_M);
const row = Math.floor(dot(p, axes.y) / VIEW_SITE_M);
let mount;
for (let i = col - 1; !mount && i <= col + 1; i++)
for (let j = row - 1; !mount && j <= row + 1; j++)
mount = grid
.get(`${i}:${j}`)
?.find((site) => distance(p, site.p) <= VIEW_SITE_M);
if (!mount) {
mount = { p, mates: [] };
mounts.push(mount);
const key = `${col}:${row}`;
if (!grid.has(key)) grid.set(key, []);
grid.get(key).push(mount);
}
mount.mates.push(record);
}
for (const { mates } of mounts) {
if (mates.length < 2) continue;
mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id));
for (let i = 0; i < mates.length; i++) {
const record = mates[i];
const p = record.position;
// A pixel's width on the ground grows with depth along the view.
const depth =
(p.x - eye.x) * direction.x +
(p.y - eye.y) * direction.y +
(p.z - eye.z) * direction.z;
const px = (i - (mates.length - 1) / 2) * VIEW_SITE_SPREAD_PX;
record.spreadPx = px;
const metres = px * metresPerPixelPerMetre * depth;
record.spreadOffset = scale(right, metres);
record.spreadPosition = add(p, record.spreadOffset);
record.spreadPass = pass;
}
}
}
/** Only counts visible outside the HUD push the active icon aside. */
function clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass) {
const markers = layerState._counts?.markers;
for (const marker of markers ?? []) marker.besideActive = false;
if (!layerState._activeCameraId) return;
const record = layerState._recordById.get(layerState._activeCameraId);
if (
record?.viewPass !== pass ||
!markers?.length ||
!pose.right ||
!pose.direction
)
return;
const spread = record.spreadPass === pass;
const p = spread ? record.spreadPosition : record.position;
const screen = project(p);
if (!screen) return;
const { x, y } = screen;
const half =
(CAMERA_ICON_PX * 1.25 * iconScaleAt(distance(p, pose.position))) / 2;
const spans = [];
for (const marker of markers) {
const at = project(marker.pos);
if (
!at ||
Math.abs(y - at.y) >= marker.height / 2 + half + COUNT_MERGE_GAP_PX
)
continue;
marker.besideActive = true;
if (marker.hudHidden) continue;
const reach = marker.width / 2 + half + COUNT_MERGE_GAP_PX;
spans.push([at.x - reach, at.x + reach]);
}
// Leave the entire overlapping interval, including an adjacent count.
spans.sort((a, b) => a[0] - b[0]);
let left = Infinity,
right = -Infinity;
for (const [start, end] of spans) {
if (start >= right) {
if (left < x && x < right) break;
left = start;
right = end;
} else right = Math.max(right, end);
}
if (!(left < x && x < right)) return;
const shift = x - left < right - x ? left - x : right - x;
const depth = dot(sub(p, pose.position), pose.direction);
const offset = scale(pose.right, shift * metresPerPixelPerMetre * depth);
record.spreadOffset = spread ? add(record.spreadOffset, offset) : offset;
record.spreadPosition = add(record.position, record.spreadOffset);
record.spreadPass = pass;
}
/**
@@ -526,6 +849,7 @@ export function createRendering({
);
parts.projection.clearProjectionOverlay();
if (layerState._icons) layerState._icons.show = false;
layerState._counts?.hide();
parts.projection.pauseInactiveProjectionFeeds(null);
}
@@ -535,8 +859,12 @@ export function createRendering({
const activeRecord = parts.selection.getActiveRecord();
parts.geometry.ensureActiveCoverageEntities(activeRecord);
const activeId = activeRecord?.camera.id || null;
const coverageVisible =
parts.geometry.buildCoverageVisibleSet(activeRecord);
const cohort = parts.geometry.buildCoverageVisibleSet(activeRecord);
layerState._coverageCohort = cohort;
const coverageVisible = new Set();
for (const id of cohort) {
if (!layerState._recordById.get(id)?.viewGrouped) coverageVisible.add(id);
}
// Drawn coverage needs geometry too (geometryQueue's working set).
layerState._coverageVisibleIds = coverageVisible;
const coverageOn = layerState._coverageMode !== 'off';
@@ -553,7 +881,7 @@ export function createRendering({
for (const record of layerState._records) {
const isActive = record.camera.id === activeId;
const icon = patchedCameraIcon(record.camera.id, {
color: cameraColorFor(record),
...cameraIconStyleFor(record),
scale: isActive ? 1.25 : 1.0,
});
if (icon) restyled.push(icon);
@@ -865,6 +1193,7 @@ export function createRendering({
* @returns {string|null}
*/
function pickCameraIdAt(position) {
if (layerState._counts?.pickedCell(position)) return null;
let hit = null;
try {
hit = findQuery(layerState._viewer)?.pick(position.x, position.y) ?? null;
+159 -2
View File
@@ -1,7 +1,7 @@
// src/layers/cctv/rendering.test.mjs
// Icon colors under focus de-emphasis (#1200): the focus pass fades each icon
// from the same base color the coverage refresh assigns, so a video-feed camera
// stays violet while it dims instead of falling back to the idle cyan.
// stays violet while it dims instead of falling back to the idle green.
// Teardown lets go of the icon set of the viewer that drew it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
@@ -114,29 +114,80 @@ test('focus de-emphasis fades each icon from its own color', () => {
}
});
test('focus uses the painted half-width and half-height of each count', () => {
const markers = [
{ width: 40, height: 40 },
{ width: 72, height: 58 },
];
const sizes = [];
const rendering = createRendering({
state: { _counts: { markers } },
services: {
focus: {
focusPassIsNeeded: () => true,
advanceSpriteFocus(_owner, { spriteHalfWidthPx, spriteHalfHeightPx }) {
sizes.push([spriteHalfWidthPx, spriteHalfHeightPx]);
return { factor: 1 };
},
focusAlphaNeedsWrite: () => false,
},
},
});
rendering.applyCctvFocusDeemphasis({});
assert.deepEqual(sizes, [
[20, 20],
[36, 29],
]);
});
test('the icons go with the viewer that drew them, whichever tears down', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const lanes = [];
const overlays = {
registerWorldOverlayPaintLane(name, paint, options) {
const lane = {
name,
paint,
options,
setActive() {},
unregister() {
this.disposed = true;
},
};
lanes.push(lane);
return lane;
},
};
const { createCameraIcons, destroyCameraIcons } = createRendering({
state,
services: { focus: {} },
services: { focus: {}, overlays },
parts: {},
source: {},
});
try {
const old = createCameraIcons(first);
assert.equal(one.draw.sets.size, 1);
assert.equal(lanes[0].name, 'ambient-label');
assert.equal(lanes[0].options.target, 'shared');
assert.equal(lanes[0].options.active, false);
state._viewer = second;
const current = createCameraIcons(second);
assert.notEqual(old, current);
assert.equal(one.draw.sets.get(old).disposed, true, 'a re-init lets go');
assert.equal(two.draw.sets.get(current).disposed, false);
assert.equal(lanes[0].disposed, true);
lanes[0].paint({});
destroyCameraIcons();
assert.equal(two.draw.sets.get(current).disposed, true);
assert.equal(state._icons, null);
assert.equal(lanes[1].disposed, true);
lanes[1].paint({});
assert.equal(state._counts, null);
} finally {
one.unbind();
two.unbind();
@@ -376,3 +427,109 @@ test('a pose with no perspective field of view is projected by the renderer', ()
unbind();
}
});
test('focus release restores video hue and alpha after the style throttle', () => {
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: 6378137 + 1000, y: 0, z: 0 } },
});
const { unbind } = bindFakeDraw(viewer, {
camera: camera.port,
query: { project: () => ({ x: 10, y: 20 }) },
});
let target = {};
const records = ['mp4', 'webm'].map((feedType) => ({
camera: { id: feedType, feedType },
position: { x: 6378137, y: 0, z: 0 },
}));
const state = {
_enabled: true,
_viewer: viewer,
_records: records,
_activeCameraId: null,
_activeFocusStyleCount: 0,
_lastFocusStyleAt: -Infinity,
};
const focus = {
focusNowMs: (nowMs) => nowMs,
getFocusTarget: () => target,
focusPassIsNeeded: (value, count) => !!value || count > 0,
advanceSpriteFocus: () => ({
factor: target ? FOCUS_FACTOR : 1,
active: !!target,
transitioning: false,
}),
focusAlphaNeedsWrite: (before, after) => before !== after,
};
const { createCameraIcons, addCameraIcon, refreshCctvFocusStyles } =
createRendering({
state,
services: { focus },
parts: {
model: {
isVideoFeedCamera: (camera) => isVideoFeedType(camera.feedType),
},
},
source: {},
});
try {
createCameraIcons(viewer);
for (const record of records) addCameraIcon(record);
const icons = state._icons;
refreshCctvFocusStyles(1000);
for (const record of records) {
assertKeepsColor(
icons,
record.camera.id,
LIVE_CAMERA_COLOR,
record.camera.id,
);
}
target = null;
refreshCctvFocusStyles(1050);
for (const record of records) {
assert.equal(icons.focus(record.camera.id), FOCUS_FACTOR, 'throttled');
}
refreshCctvFocusStyles(1100);
for (const record of records) {
assert.deepEqual(icons.item(record.camera.id).color, LIVE_CAMERA_COLOR);
assert.equal(icons.focus(record.camera.id), 1);
}
assert.equal(state._activeFocusStyleCount, 0);
} finally {
unbind();
}
});
test('hover picks the underlying camera only outside a painted count', () => {
const viewer = {};
const icon = { set: 'icons', id: 'camera' };
let picks = 0;
const unbind = bindRenderer(viewer, {
query: {
pick() {
picks++;
return icon;
},
},
});
try {
const state = {
_viewer: viewer,
_counts: { pickedCell: ({ x }) => (x <= 17 ? {} : null) },
_icons: { setId: icon.set, has: () => true },
_recordById: new Map([[icon.id, {}]]),
};
const rendering = createRendering({
state,
services: { focus: {} },
parts: {},
});
assert.equal(rendering.pickCameraIdAt({ x: 17, y: 0 }), null);
assert.equal(picks, 0);
assert.equal(rendering.pickCameraIdAt({ x: 18, y: 0 }), icon.id);
} finally {
unbind();
}
});
+73 -7
View File
@@ -1,3 +1,7 @@
import {
CCTV_COUNT_CARD_SOURCE_ID,
CCTV_OVERLAY_SOURCE_ID,
} from '../../data/cctvCards.js';
import { isTrackingClickGesture } from '../../data/trackingClickGesture.js';
export function createSelection({
@@ -7,7 +11,13 @@ export function createSelection({
source,
}) {
const { CCTV_ACTIVATION_RESULT } = services.activation;
const { resolvePickId } = services.picking;
const {
resolvePickId,
findPickOwner,
isOwnedByOtherLayer,
isUnderOtherCard,
} = services.picking;
const OWN_CARD_SOURCES = [CCTV_OVERLAY_SOURCE_ID, CCTV_COUNT_CARD_SOURCE_ID];
/**
* Returns the camera record for the currently active camera. A stale ID falls
@@ -29,6 +39,49 @@ export function createSelection({
return fallback;
}
/** Whether another layer's scene object owns the click at this count. */
function sceneTakesCountClick(event) {
const top = event.topHit;
if (!top) return false;
const drawHit = event.drawHit;
if (drawHit) {
// Unowned fills, such as earthquake discs, let the count take the click.
if (parts.rendering.extractPickedCameraId(drawHit)) return false;
const id = resolvePickId(drawHit);
return id !== null && Boolean(isOwnedByOtherLayer?.('cctv', id));
}
const id = resolvePickId(top);
return id !== null && findPickOwner?.(id) !== 'cctv';
}
/** Leave other layers' cards to the caller since clickCard also calls this. */
function clickedCount(event) {
if (
!isTrackingClickGesture(event.gesture) ||
!layerState._enabled ||
event.overlay
)
return null;
const cell = layerState._counts?.pickedCell(event.screenPosition);
if (!cell) return null;
const { x, y } = event.screenPosition;
if (
layerState._cctvOverlayHost?.hitTest(x, y, {
sourceId: CCTV_OVERLAY_SOURCE_ID,
})?.entryId
)
return null;
return sceneTakesCountClick(event) ? null : cell;
}
/** The count marker as the card on top of a click it takes, for every layer's clickCard. */
function countClickCard(event) {
const cell = clickedCount(event);
return cell
? { sourceId: CCTV_COUNT_CARD_SOURCE_ID, entryId: String(cell.key ?? '') }
: null;
}
/**
* Bind CCTV activation to clean taps. Drag-like and long-press gestures do
* not reach camera activation or focus dispatch.
@@ -41,6 +94,12 @@ export function createSelection({
function bindCctvWorldClickGesture(input, onClick) {
return input.onClick((event) => {
if (!isTrackingClickGesture(event.gesture)) return;
const cell = clickedCount(event);
// Another layer's card or label painted above the count takes the click.
if (cell && !isUnderOtherCard?.(event, OWN_CARD_SOURCES)) {
parts.navigation.zoomToCell(cell);
return;
}
onClick(event);
});
}
@@ -49,10 +108,13 @@ export function createSelection({
* Sets the active camera by ID, initializes its projection runtime, refreshes
* its frame, and updates styles.
* @param {string} cameraId - ID of the camera to activate.
* @param {Object} [options]
* @param {boolean} [options.opening=false] - The opening camera following
* the view, not someone's pick: settled moves may still replace it.
* @returns {'activated'|'unchanged'|'not-found'} Discriminated activation result.
*/
function setActiveCamera(cameraId) {
function setActiveCamera(cameraId, { opening = false } = {}) {
if (!cameraId || !layerState._recordById.has(cameraId))
return CCTV_ACTIVATION_RESULT.NOT_FOUND;
const record = layerState._recordById.get(cameraId);
@@ -70,6 +132,9 @@ export function createSelection({
record,
)
) {
// Picking the camera a settled move re-opened is still a pick: later
// settled moves must leave it alone.
if (!opening) layerState._openingCameraProvisional = false;
// Browser-only feeds have a separate player; a reselect retries it
// without re-running activation or touching the projection geometry.
if (parts.model.isBrowserOverlayCamera(record.camera)) {
@@ -80,7 +145,7 @@ export function createSelection({
}
layerState._activeCameraId = cameraId;
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = false;
layerState._openingCameraProvisional = opening;
// A real activation creates projection work — wake the self-stopping loop.
parts.projection.startProjectionLoop();
if (previousActiveRecord && previousActiveRecord !== record) {
@@ -139,11 +204,11 @@ export function createSelection({
// is looking at ever asks.
void parts.ground.resolveFootprintGround(record);
record.activationDone = true;
parts.rendering.refreshCoverageStyles();
// The active camera's icon always shows; the previously active one
// competes for its cell again. Its coverage neighbours join the working
// set and are queued for grounding.
// The active icon always shows and the previous one rejoins its cell.
// Restyle coverage after the view pass sets grouping. Its coverage
// neighbours join the working set and are queued for grounding.
parts.rendering.refreshHorizonCulling();
parts.rendering.refreshCoverageStyles();
parts.geometryQueue.enqueueViewGeometry();
// The newly active camera leaves the ambient ring (its monitor plane takes
// over); the freed slot re-fills on this same pass.
@@ -218,6 +283,7 @@ export function createSelection({
return {
getActiveRecord,
bindCctvWorldClickGesture,
countClickCard,
setActiveCamera,
deactivateActiveCamera,
cctvEmptyClickDeselects,
+176
View File
@@ -1,6 +1,10 @@
import * as picking from '../../data/pickRegistry.js';
import { CCTV_COUNT_CARD_SOURCE_ID } from '../../data/cctvCards.js';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { createNavigation } from './navigation.js';
import { createSelection } from './selection.js';
function makeSelection(sourceKind) {
@@ -52,3 +56,175 @@ test('same-camera selection notifies browser-overlay feeds so playback can retry
assert.equal(fixture.state._activeCameraReselection, 1);
assert.equal(fixture.notifications(), 1);
});
test('a count click preserves the provisional opening pick until the view settles', () => {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy: Math.PI / 3, aspectRatio: 1 }),
flyToBounds: (bounds) => flights.push(bounds),
},
canvas: { height: 600 },
});
try {
const cell = { west: 1, east: 2, south: 0, north: 0, low: 0, high: 0 };
const state = {
_enabled: true,
_viewer: viewer,
_openingCameraProvisional: true,
_activeCameraId: 'opening',
_counts: {
pickedCell: (point) => (point?.x === 14 && point.y === 26 ? cell : null),
},
};
const parts = {};
parts.navigation = createNavigation({ state, parts });
const selection = createSelection({
state,
parts,
services: { activation: {}, picking: {} },
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => {
assert.fail('a count click reached activation or deselection');
},
);
click({
screenPosition: { x: 14, y: 26 },
get drawHit() {
assert.fail('the camera underneath was picked');
},
gesture: { travelPx: 0, durationMs: 20 },
});
assert.equal(flights.length, 1);
assert.equal(state._activeCameraId, 'opening');
assert.equal(state._openingCameraProvisional, true);
} finally {
unbind();
}
});
test("a count click yields to a card above it and to another layer's object, not to a CCTV icon", () => {
let zooms = 0,
clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: () => ({}) },
_cctvOverlayHost: {
hitTest: (x) => (x === 14 ? { entryId: 'cam-1' } : null),
},
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
picking.registerPickOwner('cctv', (id) => id.startsWith('cam-'));
picking.registerPickOwner('flights', (id) => id === 'abc' || id === 'cam-2');
try {
for (const [x, topHit, expected] of [
[14, null, [0, 1]],
[20, { set: 'flights', id: 'abc' }, [0, 2]],
[20, { set: 'cctv-icons', id: 'cam-2' }, [1, 2]],
[20, null, [2, 2]],
[20, { set: 'flights', id: 'cam-2' }, [2, 3]],
]) {
click({
screenPosition: { x, y: 26 },
topHit,
drawHit: topHit,
gesture: { travelPx: 0, durationMs: 20 },
});
assert.deepEqual([zooms, clicks], expected);
}
} finally {
picking.unregisterPickOwner('cctv');
picking.unregisterPickOwner('flights');
}
});
test('a count click is the card on top for every layer, unless the count yields', () => {
let zooms = 0;
let clicks = 0;
const selection = createSelection({
services: { activation: {}, picking },
state: {
_enabled: true,
_counts: { pickedCell: (p) => (p?.x === 20 ? { key: 'g' } : null) },
_cctvOverlayHost: { hitTest: () => null },
},
parts: {
navigation: { zoomToCell: () => zooms++ },
rendering: {
extractPickedCameraId: (hit) =>
hit?.set === 'cctv-icons' ? hit.id : null,
},
},
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => clicks++,
);
const event = (topHit = null, x = 20, durationMs = 20) => ({
screenPosition: { x, y: 26 },
topHit,
drawHit: topHit,
gesture: { travelPx: 0, durationMs },
});
picking.registerClickClaim('cctv', selection.countClickCard);
picking.registerPickOwner('flights', (id) => id === 'abc');
try {
const aircraftFirst = event();
assert.equal(picking.isUnderOtherCard(aircraftFirst), true);
assert.deepEqual(picking.clickCard(aircraftFirst), {
sourceId: CCTV_COUNT_CARD_SOURCE_ID,
entryId: 'g',
});
click(aircraftFirst);
assert.deepEqual([zooms, clicks], [1, 0]);
const cctvFirst = event();
click(cctvFirst);
assert.equal(picking.isUnderOtherCard(cctvFirst), true);
assert.deepEqual([zooms, clicks], [2, 0]);
for (const [e, claimed, expected] of [
[event({ set: 'flights', id: 'abc' }), false, [2, 1]],
[event({ set: 'cctv-icons', id: 'cam-2' }), true, [3, 1]],
[event(null, 20, 1000), false, [3, 1]],
[event(null, 60), false, [3, 2]],
[{ ...event(), overlay: true }, false, [3, 3]],
]) {
assert.equal(picking.isUnderOtherCard(e), claimed);
click(e);
assert.deepEqual([zooms, clicks], expected);
}
} finally {
picking.unregisterClickClaim('cctv');
picking.unregisterPickOwner('flights');
}
});
test('same-camera selection ends the opening pick without notifying snapshot feeds', () => {
const fixture = makeSelection('tripcheck-odot');
fixture.state._openingCameraProvisional = true;
assert.equal(
fixture.selection.setActiveCamera('same-camera'),
CCTV_ACTIVATION_RESULT.UNCHANGED,
);
assert.equal(fixture.state._openingCameraProvisional, false);
assert.equal(fixture.state._activeCameraReselection, 0);
assert.equal(fixture.notifications(), 0);
});
-2
View File
@@ -22,8 +22,6 @@ function frameUrlFor(camera, refreshMs = ACTIVE_FRAME_REFRESH_MS) {
const params = new URLSearchParams({
label: camera.name,
city: camera.city,
lat: camera.lat.toFixed(6),
lon: camera.lon.toFixed(6),
heading: String(Math.round(camera.headingDeg)),
fov: String(Math.round(camera.fovDeg)),
pitch: String(Math.round(camera.pitchDeg || -10)),
+2 -2
View File
@@ -82,8 +82,8 @@ test('frame and media URLs preserve registered camera identity and encoded metad
);
assert.equal(frame.searchParams.get('label'), camera.name);
assert.equal(frame.searchParams.get('city'), camera.city);
assert.equal(frame.searchParams.get('lat'), '30.267000');
assert.equal(frame.searchParams.get('lon'), '-97.744000');
assert.equal(frame.searchParams.has('lat'), false);
assert.equal(frame.searchParams.has('lon'), false);
assert.equal(frame.searchParams.get('heading'), '45');
assert.equal(frame.searchParams.get('pitch'), '-12');
assert.deepEqual([...media.searchParams.keys()], ['ts']);
+11 -3
View File
@@ -15,6 +15,7 @@ export function createState({ services }) {
/** The catalog's camera icons: the icon book over their draw set. */
layerState._icons = null;
layerState._counts = null;
layerState._records = [];
@@ -95,10 +96,14 @@ export function createState({ services }) {
// work over these, not the whole catalog.
layerState._viewRecords = [];
// The view records plus the best-ranked camera of each visible cell.
layerState._pickerRecords = [];
// Coverage ids refreshCoverageStyles last drew: part of the geometry
// working set even when their icons are thinned out.
// The active camera's coverage neighbours, including grouped ones. A
// grouping change in this cohort requires a coverage refresh.
layerState._coverageCohort = null;
// The cohort minus grouped cameras, last drawn by refreshCoverageStyles.
// These belong to the geometry working set even off screen.
layerState._coverageVisibleIds = new Set();
// View pass triggers besides camera settle: an interval while the camera
@@ -113,6 +118,9 @@ export function createState({ services }) {
// The camera port the moveStart/moveEnd listeners are on.
layerState._viewListenerCamera = null;
// Reruns the view pass when terrain loads or the surface changes.
layerState._surfaceListener = null;
layerState._surfaceListenerGlobe = null;
// A motion pass changed the shown set and the settle pass has not yet told
// subscribers; the camera pose the last view pass ran at.
+13
View File
@@ -1,3 +1,4 @@
import { createCountMarkers } from './countMarkers.js';
import { createIconBook } from '../../render/motion/iconBook.js';
/** A draw set that draws nothing, for the icon book the tests read. */
@@ -90,6 +91,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
* @param {'off'|'on'|'viewshed'} [options.coverageMode='on'] Coverage mode.
* @param {boolean} [options.showProjection=false] Projection visibility.
* @param {Map<string, Object>} [options.healthById] Health rows by camera id.
* @param {Function} [options.registerPaintLane] Receives the count painter.
* @returns {void}
*/
@@ -102,9 +104,11 @@ export function createTesting({ state: layerState, services, parts, source }) {
showProjection = false,
healthById = new Map(),
openingCameraProvisional = false,
registerPaintLane,
} = {}) {
layerState._viewer = viewer;
layerState._records = Array.isArray(records) ? records : [];
layerState._count = layerState._records.length;
layerState._recordById = new Map(
layerState._records
.filter((record) => record?.camera?.id)
@@ -123,12 +127,20 @@ export function createTesting({ state: layerState, services, parts, source }) {
layerState._showProjection = !!showProjection;
layerState._healthById = healthById;
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
layerState._coverageCohort = null;
// A real book (over a set that draws nothing): every record gets its
// icon as init adds it.
layerState._icons = createIconBook(testIconSet());
layerState._counts?.dispose();
layerState._counts = createCountMarkers(
registerPaintLane,
'cctv:test:counts',
parts.rendering.refreshHorizonCulling,
);
for (const record of layerState._records)
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
}
@@ -148,6 +160,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
for (const runtime of layerState._projectionEntities)
if (runtime?.plane) planes[runtime.plane.id] = runtime.plane;
return {
counts: layerState._counts,
gizmo: layerState._gizmo?.partsForTest() ?? {},
coverage,
planes,
+44 -1
View File
@@ -21,6 +21,7 @@ import {
followsClock,
} from './policy.js';
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
import { locateOnTrack } from '../../data/locate.js';
export function createQueries({
flightState,
@@ -545,7 +546,9 @@ export function createQueries({
object._labelCallsign = callsign;
object._labelRegistration = registration;
}
const altitude = info?.altitude;
// A grounded contact shows no flight level: its sticky `altitude` may
// still be the approach height.
const altitude = info?.onGround ? 0 : info?.altitude;
if (object._altitude !== altitude) {
object._altitude = altitude;
object.metric = formatFlightLevel(altitude); // altitude is metres
@@ -778,6 +781,46 @@ export function createQueries({
return result;
},
/**
* The track reference of a loaded aircraft, so it can be looked up again
* once it has left the feed (see locate).
* @param {string} icao24
* @returns {string|null}
*/
referenceOf(icao24) {
const id = String(icao24 ?? '')
.trim()
.toLowerCase();
if (!id) return null;
return flightState.records.data.get(id)?.sourceReference ?? id;
},
/**
* Where an aircraft is at the layer's time (the world clock's while the
* layer follows it, else now), from its own track: for an aircraft that
* has left the feed, so it can be found again.
* @param {string} icao24
* @param {{reference?: string, signal?: AbortSignal}} [options]
* @returns {Promise<{status: 'found', lat: number, lon: number,
* altitudeM: ?number, observedAtMs: number}|{status: 'none'}>}
*/
locate(icao24, { reference, signal } = {}) {
const atMs = followsClock(flightState) ? flightState.now() : undefined;
return locateOnTrack(
flightState.feed._source,
reference ??
flightState.records.data.get(
String(icao24 ?? '')
.trim()
.toLowerCase(),
)?.sourceReference ??
String(icao24 ?? '')
.trim()
.toLowerCase(),
{ atMs, signal },
);
},
/**
* Ask for an aircraft's scheduled route (origin and destination airports),
* as tracking does; it lands on the record when the lookup answers.
+14 -3
View File
@@ -232,7 +232,13 @@ export class FlightRecords {
surfaceM = geoidSurfaceLastResortM({
geoAltM: geo_alt,
baroAltM: baro_alt,
priorRenderM: prevMeta?.renderAltitudeM,
// Only a height held ON THE GROUND counts as prior: straight after a
// landing the previous render height is the approach height, and
// holding it left the plane hanging there until a cell warmed —
// forever for a contact far from the viewer, whose cell is never
// queued (HAL-1032).
priorRenderM:
prevMeta?.onGround === true ? prevMeta.renderAltitudeM : null,
geoidN,
});
}
@@ -266,10 +272,15 @@ export class FlightRecords {
let renderAltitudeM;
if (pickedAltM != null) {
renderAltitudeM = pickedAltM;
} else if (Number.isFinite(prevMeta?.renderAltitudeM)) {
} else if (
Number.isFinite(prevMeta?.renderAltitudeM) &&
(!onGround || prevMeta.onGround === true)
) {
renderAltitudeM = prevMeta.renderAltitudeM;
} else {
renderAltitudeM = alt;
// A grounded contact with nothing better sits at 0 m: `alt` is sticky,
// so after a landing it still holds the approach altitude.
renderAltitudeM = onGround ? 0 : alt;
}
// Field-test fix (WAKE01/RS46 class, 2026-07-06; widened round 3):
// floor a low airborne contact's render height at the local coarse
+40 -4
View File
@@ -112,16 +112,52 @@ test('civil record owners isolate state and preserve partial, missing-poll and l
);
});
test('ground transitions preserve last render height while a surface cell is cold', () => {
test('a landing with a cold surface cell sits on the geoid, not at its approach height', () => {
const store = records();
store.geoidReady = true;
store.receive(observation({ ellipsoidAltitudeM: 1040 }), view());
// Every grounded poll, not just the first: a contact far from the viewer
// never has its cell warmed (HAL-1032).
for (let poll = 0; poll < 3; poll += 1) {
const next = store.receive(
observation({
onGround: true,
baroAltitudeM: null,
positionTimeMs: 1700000010000 + poll * 10000,
}),
view(),
);
assert.equal(next.groundFlipped, poll === 0);
assert.equal(next.meta.renderAltitudeM, 40);
assert.equal(next.meta.wasAirborne, true);
}
});
test('a landing before the geoid loads sits at 0 m, not at its approach height', () => {
const store = records();
store.receive(observation({ baroAltitudeM: 1539 }), view());
const next = store.receive(
observation({ onGround: true, baroAltitudeM: null }),
view(),
);
assert.equal(next.groundFlipped, true);
assert.equal(next.meta.renderAltitudeM, 1040);
assert.equal(next.meta.wasAirborne, true);
assert.equal(next.meta.renderAltitudeM, 0);
});
test('a parked contact whose surface cell goes cold holds its ground height', () => {
let floor = 312;
const store = new FlightRecords({
geoidHeight: () => 40,
cachedGroundFloor: () => floor,
floorAltitudeM: (altitude) => altitude,
approxDistanceKm: () => 0,
fleetModels: () => null,
});
store.geoidReady = true;
const grounded = () =>
store.receive(observation({ onGround: true, baroAltitudeM: null }), view());
assert.equal(grounded().meta.renderAltitudeM, 312);
floor = null;
assert.equal(grounded().meta.renderAltitudeM, 312);
});
test('complete snapshots age out vanished aircraft and retain position-less ones unless landed', () => {
+9 -3
View File
@@ -900,13 +900,19 @@ export function createTracking({
// the ICAO hex, so a callsign-less enriched contact heads its readout with
// the tail number rather than raw hex.
const cs = parts.queries._contactLabel(icao24, info);
const altFt = Math.round((info.altitude || 0) * 3.28084);
const altFt = info.onGround
? null
: Math.round((info.altitude || 0) * 3.28084);
// Flight levels are an aviation code; feet and knots read in the active
// language ("0 фт · 1 уз").
const quantity = (value, unit) =>
`${formatNumber(value, { useGrouping: false })} ${unitLabel(unit)}`;
const fl =
altFt >= 18000 ? `FL${Math.round(altFt / 100)}` : quantity(altFt, 'ft');
altFt == null
? t('On the ground')
: altFt >= 18000
? `FL${Math.round(altFt / 100)}`
: quantity(altFt, 'ft');
const spd = info.velocity
? quantity(Math.round(info.velocity * 1.944), 'kts')
: '';
@@ -1164,7 +1170,7 @@ export function createTracking({
// viewFrom — behind + above, distance scaled to altitude — for a readable
// initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.)
const followRange = Math.min(
Math.max((info.altitude || 1500) * 1.1 + 2500, 3000),
Math.max((info.onGround ? 0 : info.altitude || 1500) * 1.1 + 2500, 3000),
30000,
);
const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55);
+30 -1
View File
@@ -10,7 +10,13 @@ import { surfaceDistance } from '../../geo/geodesic.js';
import { toDegrees, toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createControls({ state: layerState, services, parts, source }) {
export function createControls({
state: layerState,
services,
parts,
source,
overlayHost,
}) {
const methods = {
id: LAYER_ID,
@@ -171,6 +177,29 @@ export function createControls({ state: layerState, services, parts, source }) {
return id ? methods.getById(id) : null;
},
/**
* The mapped installation whose label box the shared overlay paints at a
* canvas position: what a click lands on from far out, where the dot is
* 7 px. Another layer's card or label that takes clicks there wins, so
* this answers null. The dot, outline and fill themselves are query port
* hits, read with {@link findByPick}. Null for anything else.
* @param {{x: number, y: number}|null|undefined} position Canvas CSS px.
* @returns {object|null} As {@link getById}.
*/
findAt(position) {
if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y))
return null;
let top = null;
try {
top = overlayHost?.hitTest?.(position.x, position.y) ?? null;
} catch {
top = null;
}
if (top) return null;
const id = parts.namedMarkers?.labelAt?.(position) ?? null;
return id ? methods.getById(id) : null;
},
/**
* Select and frame a mapped installation from another contextual UI.
* @param {string} id Source-backed installation id.
@@ -0,0 +1,83 @@
// src/layers/installations/labelBoxClick.test.mjs — a click on a mapped
// installation's label box finds the site, read from the box the overlay
// painted for it, unless another layer's card or label that takes clicks is
// painted there.
import assert from 'node:assert/strict';
import test from 'node:test';
import { createControls } from './controls.js';
const RECORD = Object.freeze({
id: 'base',
kind: 'installation',
name: 'Base',
class: 'base',
latitude: 10,
longitude: 20,
});
const inside = (box, { x, y }) =>
x >= box.x && x <= box.x + box.w && y >= box.y && y <= box.y + box.h;
/**
* The installations controls over a fake overlay: `cards` are the hit rects
* of entries that take clicks (other layers'), `labels` the boxes painted
* for this layer's labels, which are not cards.
*/
function controlsWith({ cards = [], labels = {} }) {
const overlayHost = {
// As the world overlay does: the last painted card under the point wins.
hitTest(x, y) {
for (let i = cards.length - 1; i >= 0; i--)
if (inside(cards[i], { x, y }))
return { sourceId: cards[i].sourceId, entryId: cards[i].entryId };
return null;
},
};
const namedMarkers = {
labelAt: (position) =>
Object.keys(labels).find((id) => inside(labels[id], position)) ?? null,
};
const controls = createControls({
state: {
enabled: true,
records: [RECORD],
recordById: new Map([[RECORD.id, RECORD]]),
},
services: {},
parts: {
rendering: { installationSurfaceHeightM: () => 0 },
namedMarkers,
},
source: {},
overlayHost,
});
return controls.methods;
}
const BASE_LABEL = { x: 100, y: 100, w: 80, h: 20 };
test("a click on the site's own label box finds the site", () => {
const methods = controlsWith({ labels: { base: BASE_LABEL } });
assert.equal(methods.findAt({ x: 120, y: 110 })?.id, 'base');
assert.equal(methods.findAt({ x: 10, y: 10 }), null, 'outside every box');
assert.equal(methods.findAt(null), null);
});
test("another layer's card painted over the site's label keeps the click", () => {
const methods = controlsWith({
labels: { base: BASE_LABEL },
cards: [
{ sourceId: 'flights', entryId: 'abc123', x: 110, y: 105, w: 40, h: 12 },
],
});
assert.equal(
methods.findAt({ x: 120, y: 110 }),
null,
'the flight card is on top',
);
assert.equal(
methods.findAt({ x: 170, y: 110 })?.id,
'base',
'past the card, the site is found',
);
});
+31
View File
@@ -221,6 +221,11 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
// What `visit` hands out: the marker's id, position and whether
// it is on this side of the horizon.
point: { id: { installationId: record.id }, position, show: false },
// Not an interactive overlay entry: those are cards that take every
// click from what is drawn under them, and an aircraft or vessel
// under a base's label must stay selectable. The label box still
// finds the site through its painted box (labelAt), which the
// layer's click claim reads where nothing else is drawn.
entry: createInfrastructureOverlayEntry({
id: record.id,
source: LAYER_ID,
@@ -274,6 +279,32 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
visitor(marker.recordId, marker.point);
}
},
/**
* The site whose label box the shared overlay painted at a canvas
* position in its last frame, or null: what a click lands on from far
* out, where the dot is 7 px.
* @param {{x: number, y: number}|null|undefined} position Canvas CSS px.
* @returns {string|null} The installation id.
*/
labelAt(position) {
if (!state.enabled) return null;
const x = position?.x;
const y = position?.y;
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
for (let i = ordered.length - 1; i >= 0; i--) {
const { recordId } = ordered[i];
const box = overlayHost.paintRect?.(LAYER_ID, recordId);
if (
box &&
x >= box.x &&
x <= box.x + box.w &&
y >= box.y &&
y <= box.y + box.h
)
return recordId;
}
return null;
},
refresh,
enable,
hide,
+111 -23
View File
@@ -9,15 +9,30 @@ import { fakeSceneFrame, fakeSceneQuery } from '../../testSupport/fakeCesiumScen
import { createLocalInfrastructureOverlayEntry } from '../../data/localGeojsonCore.js';
function setup(t) {
let labels = [], options, publications = 0, visible = false;
let labels = [],
options,
publications = 0,
visible = false;
const overlayHost = {
setEntries(id, entries, policy) {
assert.equal(id, 'military-installations');
labels = entries; options = policy; publications++;
labels = entries;
options = policy;
publications++;
},
clearSource() {
labels = [];
},
setVisible(_id, value) {
visible = value;
},
// The boxes the overlay painted last frame, by entry id.
paintRect(id, entryId) {
assert.equal(id, 'military-installations');
return boxes.get(entryId) ?? null;
},
clearSource() { labels = []; },
setVisible(_id, value) { visible = value; },
};
const boxes = new Map();
let x = -100;
t.mock.method(C.SceneTransforms, 'worldToWindowCoordinates', () => new C.Cartesian2(x, 300));
const camera = { changed: new C.Event(), moveEnd: new C.Event(), positionWC: C.Cartesian3.fromDegrees(0, 0, 1e6), directionWC: new C.Cartesian3(0, 0, -1) };
@@ -33,14 +48,16 @@ function setup(t) {
lifecycle.init(state.viewer); lifecycle.enable();
const records = [1, 2].map((n) => ({ id: `osm:military:w${n}`, name: `Site ${n}`, namedArea: true, areaM2: 100 / n, latitude: 0, longitude: 0, pointOnly: true }));
const points = () => [...draw.sets.values()].find((set) => set.kind === 'points' && !set.disposed);
return { state, camera, draw, points, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, records, markers: parts.namedMarkers, lifecycle, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads };
return { state, camera, draw, points, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, records, markers: parts.namedMarkers, lifecycle, boxes, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads };
}
test('Contacts camera motion reprojects and declutters existing labels without source loads or primitive replacement', (t) => {
const h = setup(t);
h.markers.sync(h.records);
assert.equal(h.markers.stats().pointsOnScreen, 0);
h.setX(600); h.camera.changed.raiseEvent(); h.camera.moveEnd.raiseEvent();
h.setX(600);
h.camera.changed.raiseEvent();
h.camera.moveEnd.raiseEvent();
assert.equal(h.markers.stats().pointsOnScreen, 2);
assert.equal(h.labels.length, 2);
assert.equal(h.options.collisionCapacity, 24);
@@ -61,7 +78,8 @@ test('Contacts camera motion reprojects and declutters existing labels without s
assert.equal(h.labels.length, 0);
assert.equal(h.visible, false);
h.state.records = h.records;
h.setX(600); h.lifecycle.enable();
h.setX(600);
h.lifecycle.enable();
assert.equal(h.labels.length, 2);
assert.equal(h.publications(), 5);
h.lifecycle.destroy(h.state.viewer);
@@ -73,13 +91,25 @@ test('Contacts camera motion reprojects and declutters existing labels without s
test('wide named markers retain primitives until close polygons publish with the same identity', async (t) => {
const { retainNamedHandoff } = await import('./ingestion.js');
const h = setup(t);
h.setX(600); h.markers.sync(h.records);
h.setX(600);
h.markers.sync(h.records);
const first = h.labels[0];
const box = { west: -1, east: 1, south: -1, north: 1 };
h.markers.sync(retainNamedHandoff(h.records, [], box));
assert.equal(h.labels[0], first);
assert.equal(first.title, 'Site 1');
const polygon = { ...h.records[0], namedArea: false, name: 'Military area', pointOnly: false, footprint: [[0, 0], [0.1, 0], [0, 0.1], [0, 0]] };
const polygon = {
...h.records[0],
namedArea: false,
name: 'Military area',
pointOnly: false,
footprint: [
[0, 0],
[0.1, 0],
[0, 0.1],
[0, 0],
],
};
const handed = retainNamedHandoff(h.records, [polygon], box);
assert.equal(handed.length, 2);
assert.equal(handed[0].name, 'Site 1');
@@ -88,7 +118,11 @@ test('wide named markers retain primitives until close polygons publish with the
assert.equal(h.labels[0], first);
assert.equal(first.title, 'Site 1');
assert.equal(h.labels.length, 2, 'no duplicate title at handoff');
assert.equal(retainNamedHandoff(h.records, [], { west: 1, east: 2, south: 1, north: 2 }).length, 0);
assert.equal(
retainNamedHandoff(h.records, [], { west: 1, east: 2, south: 1, north: 2 })
.length,
0,
);
h.lifecycle.destroy(h.state.viewer);
});
@@ -98,7 +132,9 @@ test('canonical aliases transfer named marker ownership without replacing marker
const parent = h.records[1];
h.markers.sync([parent]);
let originalPoint;
h.markers.visit((_id, point) => { originalPoint = point; });
h.markers.visit((_id, point) => {
originalPoint = point;
});
const label = h.labels[0];
for (const record of [
{ ...parent, id: h.records[0].id, aliasIds: [parent.id], pointOnly: false },
@@ -120,17 +156,29 @@ test('canonical aliases transfer named marker ownership without replacing marker
h.lifecycle.destroy(h.state.viewer);
});
test('the bounded host cohort ranks wide points and polygon titles by area', (t) => {
const h = setup(t);
h.markers.sync(Array.from({ length: 600 }, (_, n) => ({
...h.records[0], id: `site:${n}`, name: `Site ${n}`, areaM2: n,
pointOnly: n % 2 === 0,
})));
h.markers.sync(
Array.from({ length: 600 }, (_, n) => ({
...h.records[0],
id: `site:${n}`,
name: `Site ${n}`,
areaM2: n,
pointOnly: n % 2 === 0,
})),
);
assert.equal(h.labels.length, 512);
assert.equal(h.labels[0].id, 'site:599');
assert.equal(h.labels.at(-1).id, 'site:88');
assert.ok(h.labels.every((entry) => !entry.stateless && entry.horizonCull && entry.collisionGroup === 'ambient-card'));
assert.ok(
h.labels.every(
(entry) =>
!entry.stateless &&
entry.horizonCull &&
entry.collisionGroup === 'ambient-card' &&
entry.interactive === false,
),
);
const first = h.labels[0];
const publications = h.publications();
for (let i = 0; i < 100; i++) {
@@ -143,7 +191,6 @@ test('the bounded host cohort ranks wide points and polygon titles by area', (t)
assert.equal(h.labels.length, 0);
});
test('wide and polygon titles use the Data Centers entry contract and persistent shared domain', (t) => {
const h = setup(t);
h.markers.sync([h.records[0], { ...h.records[1], pointOnly: false }]);
@@ -151,12 +198,43 @@ test('wide and polygon titles use the Data Centers entry contract and persistent
assert.equal(h.options.solveIntervalMs, undefined);
assert.equal(h.options.maxVisible, 24);
for (const entry of h.labels) {
const reference = createLocalInfrastructureOverlayEntry({ id: entry.id, layerId: 'military-installations', position: entry.position, properties: { name: entry.title }, priority: entry.priority, accent: entry.accent });
const reference = createLocalInfrastructureOverlayEntry({
id: entry.id,
layerId: 'military-installations',
position: entry.position,
properties: { name: entry.title },
priority: entry.priority,
accent: entry.accent,
});
// Not interactive: an interactive entry is a card that takes the click
// from an aircraft or vessel drawn under it. A click on the label box
// finds the site through its painted box (labelAt).
assert.deepEqual(entry, { ...reference, selected: false });
}
h.lifecycle.destroy(h.state.viewer);
});
test("labelAt finds the site whose label box was painted at a point, in CSS px", (t) => {
const h = setup(t);
h.markers.sync(h.records);
const [first, second] = h.records.map((record) => record.id);
h.boxes.set(first, { x: 100, y: 100, w: 80, h: 20 });
h.boxes.set(second, { x: 300, y: 100, w: 60, h: 20 });
assert.equal(h.markers.labelAt({ x: 120, y: 110 }), first);
assert.equal(h.markers.labelAt({ x: 360, y: 120 }), second, 'edges count');
assert.equal(h.markers.labelAt({ x: 250, y: 110 }), null, 'between boxes');
assert.equal(h.markers.labelAt(null), null);
assert.equal(h.markers.labelAt({ x: Number.NaN, y: 110 }), null);
// A site no longer marked has no label to find, even with a stale box.
h.markers.sync([h.records[1]]);
assert.equal(h.markers.labelAt({ x: 120, y: 110 }), null);
assert.equal(h.markers.labelAt({ x: 320, y: 110 }), second);
// Nor does a layer that is off.
h.state.enabled = false;
assert.equal(h.markers.labelAt({ x: 320, y: 110 }), null);
h.state.enabled = true;
h.lifecycle.destroy(h.state.viewer);
});
test('selection promotes exactly one entry and deselection restores that same label', (t) => {
const h = setup(t);
@@ -167,7 +245,7 @@ test('selection promotes exactly one entry and deselection restores that same la
assert.equal(h.labels.length, 2);
assert.equal(h.labels[0], original);
assert.equal(original.variant, 'selected');
assert.equal(h.labels.filter(e => e.selected).length, 1);
assert.equal(h.labels.filter((e) => e.selected).length, 1);
assert.equal(h.options.maxVisible, 23);
h.state.selectedId = null;
h.markers.sync(h.records);
@@ -180,14 +258,24 @@ test('selection promotes exactly one entry and deselection restores that same la
test('Contacts can select a point outside the normal title cap or an unnamed polygon', (t) => {
const h = setup(t);
const records = Array.from({ length: 520 }, (_, i) => ({ ...h.records[0], id: `site:${i}`, areaM2: 1000 - i }));
records.push({ ...h.records[0], id: 'unnamed', name: 'Military area', namedArea: false, pointOnly: false });
const records = Array.from({ length: 520 }, (_, i) => ({
...h.records[0],
id: `site:${i}`,
areaM2: 1000 - i,
}));
records.push({
...h.records[0],
id: 'unnamed',
name: 'Military area',
namedArea: false,
pointOnly: false,
});
for (const id of ['site:519', 'unnamed']) {
h.state.selectedId = id;
h.markers.sync(records);
assert.equal(h.labels[0].id, id);
assert.equal(h.labels[0].variant, 'selected');
assert.equal(h.labels.filter(e => e.selected).length, 1);
assert.equal(h.labels.filter((e) => e.selected).length, 1);
assert.equal(h.labels.length, 512);
}
h.lifecycle.destroy(h.state.viewer);
+50 -9
View File
@@ -1,5 +1,10 @@
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import {
clickCard,
isUnderOtherCard,
registerClickClaim,
unregisterClickClaim,
} from '../../data/pickRegistry.js';
import { LAYER_ID } from './policy.js';
export function createSelection({
@@ -37,8 +42,39 @@ export function createSelection({
return layerState.selectedId === id;
}
/** Whether a draw hit is one of this layer's: a dot, outline, fill or named marker. */
function ownsHit(hit) {
return Boolean(
hit &&
(hit.set === parts.namedMarkers?.setId ||
parts.rendering.ownsSet(hit.set)),
);
}
/**
* A site's label box as the card on top of a click, for every layer's
* clickCard (the pick registry's click claim). Only where nothing another
* layer draws is under the click: an aircraft or vessel drawn under a
* base's label keeps its own click, while a label over the map, or over
* this layer's own dots and fills, takes it. Runs only where no card or
* label that takes clicks is painted on top.
* @param {object} event The shared dispatcher click.
* @returns {{sourceId: string, entryId: string}|null}
*/
function labelClickCard(event) {
if (!layerState.enabled || !event) return null;
if (event.topHit && !ownsHit(event.drawHit)) return null;
const id =
parts.namedMarkers?.labelAt?.(event.screenPosition ?? event.position) ??
null;
return id && layerState.recordById.has(id)
? { sourceId: LAYER_ID, entryId: id }
: null;
}
function installInteraction(viewer) {
if (layerState.clickSubscription) return;
registerClickClaim(LAYER_ID, labelClickCard);
const events = [
'gev:entity-selected',
'gev:entity-selection-cleared',
@@ -54,16 +90,20 @@ export function createSelection({
layerState.clickSubscription = input.onClick((event) => {
if (!layerState.enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
// A site's dot, outline or fill, or a named marker: each draw item
// names its installation in its `meta`.
// under it does not act, and the click is not empty space either. A
// site's own label box is this layer's.
if (isUnderOtherCard(event, [LAYER_ID])) return;
// The site whose label box is at the click takes it where nothing
// another layer draws is under it (labelClickCard): from far out the
// click lands on the label, not the 7 px dot. Else a site's dot,
// outline or fill, or a named marker: each draw item names its
// installation in its `meta`.
const card = clickCard(event);
const hit = event.drawHit;
const id =
hit?.set === parts.namedMarkers?.setId ||
parts.rendering.ownsSet(hit?.set)
? hit.meta?.installationId
: null;
(card?.sourceId === LAYER_ID ? card.entryId : null) ??
(ownsHit(hit) ? hit.meta?.installationId : null) ??
null;
if (id && layerState.recordById.has(id) && id !== layerState.selectedId) {
selectRecord(id);
} else if (layerState.selectedId) {
@@ -82,6 +122,7 @@ export function createSelection({
destroy() {
removeContextListeners?.();
removeContextListeners = null;
unregisterClickClaim(LAYER_ID);
},
};
}
+69 -1
View File
@@ -7,7 +7,8 @@ import { createRendering } from './rendering.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
import { clickCard, setClickCardHitTest } from '../../data/pickRegistry.js';
import { LAYER_ID } from './policy.js';
function harness(t) {
const previousWindow = globalThis.window;
@@ -60,6 +61,8 @@ function harness(t) {
() => new Cesium.Cartesian2(640, 400),
);
let labels = [];
// The boxes the overlay painted last frame for this layer's labels.
const boxes = new Map();
const services = {
context,
anchors: {},
@@ -82,6 +85,9 @@ function harness(t) {
},
clearSource() {},
setVisible() {},
paintRect(_id, entryId) {
return boxes.get(entryId) ?? null;
},
},
};
parts.rendering = createRendering(ctx);
@@ -116,6 +122,7 @@ function harness(t) {
draw,
input,
parts,
boxes,
/** Click on what `pick` names, as the scene would pick it. */
click(value) {
picked = value;
@@ -258,3 +265,64 @@ test('a click on a site dot or its outline selects the site; another set does no
h.click({ id: { set: 'other:1', id: outline.id, meta: outline.meta } });
assert.equal(selectedNow(), false);
});
test("a click on a site's label box selects it where nothing else is drawn under it", (t) => {
const h = harness(t);
h.state.selectedId = null;
context.clearSelectedEntityContextForLayer('military-installations');
h.parts.rendering.renderRecords();
// The card every layer reads for each click, as Context's bridge reads it.
const cards = [];
const offCards = h.input.input.onClick((event) =>
cards.push(clickCard(event)),
);
t.after(offCards);
// No label at the click and nothing picked: nothing is selected.
h.click(undefined);
h.assertSelected(false);
assert.equal(cards.at(-1), null);
// The site's label box at the click (CSS px) selects it; again releases it.
h.boxes.set('base', { x: 600, y: 390, w: 80, h: 20 });
h.click(undefined);
h.assertSelected(true);
assert.deepEqual(cards.at(-1), { sourceId: LAYER_ID, entryId: 'base' });
h.click(undefined);
h.assertSelected(false);
// Over the site's own named marker, the label still takes the click.
const setId = h.parts.namedMarkers.setId;
const item = h.draw.set(setId).items.get(namedPointId('base'));
h.click({ id: { set: setId, id: item.id, meta: item.meta } });
h.assertSelected(true);
assert.deepEqual(cards.at(-1), { sourceId: LAYER_ID, entryId: 'base' });
// An aircraft drawn under the label keeps its click: the label is no card
// there, so its own layer and Context can select it, and the site lets go.
h.click({ id: 'flight:abc123' });
h.assertSelected(false);
assert.equal(cards.at(-1), null);
// Another layer's card painted over the label takes the click.
setClickCardHitTest(() => ({ sourceId: 'earthquake-card', entryId: 'ak1' }));
t.after(() => setClickCardHitTest(null));
h.click(undefined);
h.assertSelected(false);
setClickCardHitTest(null);
// A layer that is off claims nothing.
h.state.enabled = false;
h.click(undefined);
assert.equal(cards.at(-1), null);
h.state.enabled = true;
});
test('destroy withdraws the label claim', (t) => {
const h = harness(t);
h.boxes.set('base', { x: 600, y: 390, w: 80, h: 20 });
const cards = [];
const offCards = h.input.input.onClick((event) =>
cards.push(clickCard(event)),
);
t.after(offCards);
h.click(undefined);
assert.deepEqual(cards.at(-1), { sourceId: LAYER_ID, entryId: 'base' });
h.selection.destroy();
h.click(undefined);
assert.equal(cards.at(-1), null);
});
+50 -4
View File
@@ -19,6 +19,7 @@ import {
followsClock,
} from './policy.js';
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
import { locateOnTrack } from '../../data/locate.js';
export function createQueries({
flightState,
@@ -193,9 +194,12 @@ export function createQueries({
lon: num(info?.rawLon),
// altitudeFt is the sticky barometric/MSL aviation field — converted to
// meters here for shape parity with the flights layer.
altitudeM: Number.isFinite(info?.altitudeFt)
? info.altitudeFt * 0.3048
: null,
// A grounded contact reports only an altitude it gave on the ground.
altitudeM: info?.onGround
? (info.groundAltitudeM ?? null)
: Number.isFinite(info?.altitudeFt)
? info.altitudeFt * 0.3048
: null,
speedMps: num(info?.speedMps),
heading: num(info?.track),
verticalRateMps: num(info?.verticalRateMps),
@@ -509,7 +513,9 @@ export function createQueries({
// TR-3B, not the airframe underneath it.
const klass = tr3bTypeLabel(icao24, info?.type || 'MIL');
if (object.klass !== klass) object.klass = klass;
const altitudeFt = info?.altitudeFt ?? 0;
// A grounded contact shows no flight level, like the civil layer; its
// sticky altitudeFt may still be the approach height.
const altitudeFt = info?.onGround ? 0 : (info?.altitudeFt ?? 0);
if (object._altitudeFt !== altitudeFt) {
object._altitudeFt = altitudeFt;
// military metadata stores altitudeFt (feet); the helper takes metres
@@ -651,6 +657,46 @@ export function createQueries({
return result;
},
/**
* The track reference of a loaded aircraft, so it can be looked up again
* once it has left the feed (see locate).
* @param {string} icao24
* @returns {string|null}
*/
referenceOf(icao24) {
const id = String(icao24 ?? '')
.trim()
.toLowerCase();
if (!id) return null;
return flightState.records.data.get(id)?.sourceReference ?? id;
},
/**
* Where an aircraft is at the layer's time (the world clock's while the
* layer follows it, else now), from its own track: for an aircraft that
* has left the feed, so it can be found again.
* @param {string} icao24
* @param {{reference?: string, signal?: AbortSignal}} [options]
* @returns {Promise<{status: 'found', lat: number, lon: number,
* altitudeM: ?number, observedAtMs: number}|{status: 'none'}>}
*/
locate(icao24, { reference, signal } = {}) {
const atMs = followsClock(flightState) ? flightState.now() : undefined;
return locateOnTrack(
flightState.feed._source,
reference ??
flightState.records.data.get(
String(icao24 ?? '')
.trim()
.toLowerCase(),
)?.sourceReference ??
String(icao24 ?? '')
.trim()
.toLowerCase(),
{ atMs, signal },
);
},
/**
* Start camera-tracking an aircraft by ICAO hex identifier.
* @param {string} icao24 - ICAO hex identifier of the aircraft.
+16 -9
View File
@@ -70,19 +70,25 @@ export class MilitaryFlightRecords {
this.missingPolls.delete(icao24);
const prevMeta = this.data.get(icao24);
// adsb.lol/readsb reports GROUND traffic as alt_baro === "ground" (no
// separate boolean). Grounded planes fall back to their last known
// altitude (field elevation is unknowable here), else 0 m — never the
// 3 km airborne default (a parked plane must not float).
// separate boolean). Grounded planes fall back to an altitude they
// reported while on the ground (field elevation is unknowable here),
// else 0 m — never the 3 km airborne default, and never the last
// AIRBORNE altitude: `altitudeFt` is sticky across the landing, so it
// still holds the approach height, and the icon would hang there while
// the ground-snapped model sits on the field (a parked plane must not
// float). `groundAltitudeM` is that ground-only altitude: set by a
// grounded report that carries one, held while grounded, dropped on
// takeoff.
const onGround = aircraft.onGround;
const altitudeFt =
aircraft.baroAltitudeM == null ? null : aircraft.baroAltitudeM / 0.3048;
const groundAltitudeM = onGround
? (aircraft.baroAltitudeM ??
(prevMeta?.onGround === true ? prevMeta.groundAltitudeM : null) ??
null)
: null;
const altitudeM =
aircraft.baroAltitudeM ??
(onGround
? Number.isFinite(prevMeta?.altitudeFt)
? prevMeta.altitudeFt * 0.3048
: 0
: 3048);
aircraft.baroAltitudeM ?? (onGround ? (groundAltitudeM ?? 0) : 3048);
const verticalRateMps = aircraft.verticalRateMps;
const callsign = aircraft.callsign;
const type = aircraft.typeCode;
@@ -198,6 +204,7 @@ export class MilitaryFlightRecords {
registration: stickyText(registration, prevMeta?.registration),
operator: stickyText(operator, prevMeta?.operator),
altitudeFt: stickyNumber(altitudeFt, prevMeta?.altitudeFt, null),
groundAltitudeM,
// geoAltitudeM/renderAltitudeM are ADDITIVE fields alongside the
// untouched aviation `altitudeFt` — never rename/replace it (labels,
// the FL readout, and the landed-fast-cull heuristic all still read
+46
View File
@@ -65,6 +65,52 @@ test('military ground records leave model-owned placement alone and warm the sam
assert.deepEqual(unowned.floorWarmPoints, owned.floorWarmPoints);
});
test('a military contact that lands with no altitude sits on the ground, not at its last airborne height', () => {
for (const [modelOwnsVisual, expected] of [
[false, 201.5],
[true, 0],
]) {
const records = store();
records.receive(
observation({ baroAltitudeM: 1539 }),
context({ modelOwnsVisual }),
);
// Every grounded report, not just the first after the landing.
for (let poll = 0; poll < 3; poll += 1) {
const landed = records.receive(
observation({ onGround: true, baroAltitudeM: null, speedMps: 4.6 }),
context({ modelOwnsVisual }),
);
assert.equal(landed.meta.renderAltitudeM, expected);
// The aviation readout keeps the last reported altitude, as before.
assert.equal(landed.meta.altitudeFt, 1539 / 0.3048);
}
}
});
test('a grounded military contact holds a ground altitude it reported earlier', () => {
const records = store();
records.receive(
observation({ onGround: true, baroAltitudeM: 320 }),
context({ modelOwnsVisual: true }),
);
for (let poll = 0; poll < 2; poll += 1) {
const next = records.receive(
observation({ onGround: true, baroAltitudeM: null }),
context({ modelOwnsVisual: true }),
);
assert.equal(next.meta.renderAltitudeM, 320);
}
// Airborne again: that ground altitude is forgotten, so the next landing
// without an altitude starts from the ground, not from it.
records.receive(observation({ baroAltitudeM: 900 }), context());
const relanded = records.receive(
observation({ onGround: true, baroAltitudeM: null }),
context({ modelOwnsVisual: true }),
);
assert.equal(relanded.meta.renderAltitudeM, 0);
});
test('military records keep bounded partial retention and release metadata only after removal admission', () => {
const first = store();
const second = store();
+8 -2
View File
@@ -365,7 +365,9 @@ export function createTracking({
parts.queries._toCleanText(info?.registration) || t('Reg unknown');
const operator =
parts.queries._toCleanText(info?.operator) || t('Operator unknown');
const altitude = parts.queries._formatAltitude(info?.altitudeFt);
const altitude = info?.onGround
? t('On the ground')
: parts.queries._formatAltitude(info?.altitudeFt);
const speedKt = info?.speedMps ? Math.round(info.speedMps * 1.944) : null;
const tail = speedKt ? `${altitude} · ${speedKt} kt` : altitude;
return [
@@ -1124,7 +1126,11 @@ export function createTracking({
// renderer's default follow distance is far too tight. It gets a calibrated
// viewFrom — behind + above, distance scaled to altitude — for a readable
// initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.)
const altM = info?.altitudeFt ? info.altitudeFt * 0.3048 : 1500;
const altM = info?.onGround
? 0
: info?.altitudeFt
? info.altitudeFt * 0.3048
: 1500;
const followRange = Math.min(Math.max(altM * 1.1 + 2500, 3000), 30000);
const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55);
+24
View File
@@ -9,6 +9,7 @@ import {
tleEpochMs,
} from './classes.js';
import { ISS_NORAD } from './policy.js';
import { trackedStation } from './stationModels.js';
/** The layer id a satellite subject carries through Cockpit events and state. */
export const SATELLITE_COCKPIT_LAYER_ID = 'satellites';
@@ -261,6 +262,29 @@ export function createCockpitSubject({ state: layerState, parts }) {
return out;
},
/**
* Where the Cockpit camera sits and looks when the subject is the
* station: a view from a point on the ISS model (issMounts.js) in place
* of the straight-down picture. The station offers several (from Nauka,
* from Zarya, from a docked vehicle), whichever of its entries is ridden.
* @param {string|null} [key] The view asked for; the first on offer when
* it is not given or not on offer.
* @returns {{position: object, direction: object, up: object,
* right: object, key: string, label: string,
* views: Array<{key: string, label: string}>}|null} Earth-fixed
* `{x, y, z}` vectors, the view shown and the views on offer; null for
* any other satellite, outside the Cockpit, or until the model has
* loaded.
*/
getCockpitMount(key = null) {
if (!_cockpitHeld()) return null;
// The station the subject belongs to; a station without views on its
// model (Tiangong) answers null, and the Cockpit keeps the nadir picture.
return (
trackedStation(layerState, parts)?.model?._cockpitMount?.(key) ?? null
);
},
/**
* Mark the satellite whose position the Cockpit camera occupies, or
* release it. The hold applies while that satellite is tracked.
@@ -631,3 +631,70 @@ test('the subject says whether its class may be ridden', () => {
])
assert.equal(subject(satelliteClass).enterable, true, satelliteClass);
});
test('the station offers its mount only while the Cockpit rides it', async (t) => {
const f = await fixture(t);
const mount = { label: 'ZARYA' };
// The ISS model part works the mount out (issModel.js, stationModel.js);
// this layer only decides when the Cockpit may have it, asking the part
// whose station the subject is (stationModels.js).
const modelPart = (offered) => ({
key: 'iss',
norad: ISS_NORAD,
_updateStationModel() {},
_destroyStationModel() {},
_standsInFor: () => false,
_cockpitMount: () => offered,
});
f.parts.stationModels = [modelPart(mount)];
assert.equal(f.methods.getCockpitMount(), null, 'nothing tracked');
f.track(ISS_NORAD);
f.nextFrame();
assert.equal(f.methods.getCockpitMount(), null, 'tracked, not ridden');
f.methods.setCockpitSubject(String(ISS_NORAD));
assert.equal(f.methods.getCockpitMount(), mount);
// The view asked for is passed on; none asks for the first on offer.
const asked = [];
f.parts.stationModels = [
{
...modelPart(mount),
_cockpitMount(key) {
asked.push(key);
return mount;
},
},
];
f.methods.getCockpitMount('zarya');
f.methods.getCockpitMount();
assert.deepEqual(asked, ['zarya', null]);
// The model has nothing to offer: not loaded, or not the station.
f.parts.stationModels = [modelPart(null)];
assert.equal(f.methods.getCockpitMount(), null);
delete f.parts.stationModels;
assert.equal(f.methods.getCockpitMount(), null);
// Another station's part is not asked for the ISS.
f.parts.stationModels = [{ ...modelPart(mount), norad: 48274 }];
assert.equal(f.methods.getCockpitMount(), null);
f.parts.stationModels = [modelPart(mount)];
f.methods.setCockpitSubject(null);
assert.equal(f.methods.getCockpitMount(), null, 'released');
});
test('a satellite docked to the ISS draws no ring of its own: the ISS’s shows', async (t) => {
const f = await fixture(t);
f.track(COMPANION);
f.nextFrame();
assert.equal(f.state._trackedDockedToIss, true);
assert.equal(f.ring(COMPANION), undefined, 'no second ring');
assert.equal(f.ring(ISS_NORAD).show, true);
// The ISS's ring stands for it even with the stations class hidden.
f.methods.setParams({ classes: { stations: false } });
assert.equal(f.ring(ISS_NORAD).show, true);
// Another satellite keeps its own ring; the ISS's goes with its class.
f.track(GPS);
f.nextFrame();
assert.equal(f.state._trackedDockedToIss, false);
assert.ok(f.ring(GPS));
assert.equal(f.ring(GPS).show, true);
assert.equal(f.ring(ISS_NORAD).show, false);
});
+21 -2
View File
@@ -9,6 +9,7 @@ import {
mergeClassVisibility,
} from './classes.js';
import { ISS_NORAD, POINT_STYLES, classPointStyle } from './policy.js';
import { modelFor, trackedStation } from './stationModels.js';
export function createControls({ state: layerState, services, parts, source }) {
const { isExplicitLayerStateOrigin } = services.layerState;
@@ -64,7 +65,8 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Whether the ISS's ring shows: orbits on, the layer drawing, and its
* class on or the ISS tracked (a tracked satellite keeps its ring).
* class on or the ISS tracked (a tracked satellite keeps its ring), also
* as an object docked to it, which draws no ring of its own.
*/
function _issOrbitVisible() {
return (
@@ -72,7 +74,9 @@ export function createControls({ state: layerState, services, parts, source }) {
layerState._enabled,
layerState._params.showOrbits,
) &&
(_classVisible(ISS_NORAD) || layerState._trackedNorad === ISS_NORAD)
(_classVisible(ISS_NORAD) ||
layerState._trackedNorad === ISS_NORAD ||
Boolean(layerState._trackedDockedToIss))
);
}
@@ -253,6 +257,9 @@ export function createControls({ state: layerState, services, parts, source }) {
// that card instead. Only members of the tracked cluster are affected —
// unrelated nearby satellites are never suppressed.
if (!isTracked && layerState._dockedCompanions.has(noradId)) continue;
// Up close a station is its 3D model: no mark on it, nor on what is
// docked to it.
if (modelFor(parts, noradId)?._visualPosition?.()) continue;
// The Cockpit camera rides a held subject; a bracket on it would sit
// on the lens.
if (isTracked && parts.cockpit?._cockpitHeld()) continue;
@@ -433,6 +440,18 @@ export function createControls({ state: layerState, services, parts, source }) {
return result;
},
/**
* The keys the LIVE section matches streams by for the tracked
* satellite: a station is `station:<key>` (`station:iss`,
* `station:tiangong`) whichever of its entries is tracked (the station,
* a module, a docked vehicle).
* @returns {string[]}
*/
getLiveSubjectKeys() {
const station = trackedStation(layerState, parts);
return station ? [`station:${station.key}`] : [];
},
/**
* Track a satellite by NORAD id (camera follow + orbit path + highlight),
* same path as clicking its point.
+23 -1
View File
@@ -7,13 +7,22 @@ import { createRendering } from './rendering.js';
import { createTracking } from './tracking.js';
import { createTesting } from './testing.js';
import { createInteraction } from './interaction.js';
import { issStationDescription } from './issStation.js';
import { createStationPanel } from './stationPanel.js';
import { createIssModel } from './issModel.js';
import { createTiangongModel } from './tiangongModel.js';
import { tiangongStationDescription } from './tiangongStation.js';
import { createLifecycle } from './lifecycle.js';
import { createIngestion } from './ingestion.js';
import { createRecords } from './records.js';
import { createState } from './state.js';
/** Construct one layer with its own scene state and supplied application services. */
export function createSatellitesLayer({ services, source }) {
export function createSatellitesLayer({
services,
source,
resolveAsset = (url) => url,
}) {
if (typeof source?.readGroup !== 'function')
throw new TypeError('A satellites source is required');
const state = createState({ services });
@@ -25,6 +34,18 @@ export function createSatellitesLayer({ services, source }) {
parts.orbits = createOrbits(context);
parts.records = createRecords(context);
parts.rendering = createRendering(context);
// The stations drawn as models up close; the other parts ask
// stationModels.js which station an entry belongs to.
parts.issModel = createIssModel({ ...context, resolveAsset });
parts.tiangongModel = createTiangongModel({ ...context, resolveAsset });
parts.stationModels = [parts.issModel, parts.tiangongModel];
parts.stationPanel = createStationPanel({
...context,
stations: [
issStationDescription(context),
tiangongStationDescription(context),
],
});
parts.tracking = createTracking(context);
parts.testing = createTesting(context);
parts.interaction = createInteraction(context);
@@ -35,6 +56,7 @@ export function createSatellitesLayer({ services, source }) {
{},
parts.controls.methods,
parts.cockpit.methods,
parts.stationPanel.methods,
parts.lifecycle.methods,
parts.ingestion.methods,
{
+13
View File
@@ -1,4 +1,5 @@
import { inputFor } from '../../input/dispatcher.js';
import { modelHitNorad } from './stationModels.js';
import { onFollowChanged } from '../../data/followed.js';
export function createInteraction({
@@ -67,6 +68,18 @@ export function createInteraction({
parts.tracking._trackSatellite(noradId, { origin: 'user' });
return;
}
// A station's 3D model (stationModel.js) names its station. A click
// on the tracked station's own model is already tracked; on another
// station's model it tracks that one.
const modelNorad = modelHitNorad(parts, hit);
if (modelNorad !== null) {
if (modelNorad === layerState._trackedNorad) return;
if (layerState._catalog.has(modelNorad)) {
parts.tracking._cancelPendingTrackingRestore();
parts.tracking._trackSatellite(modelNorad, { origin: 'user' });
return;
}
}
// A pick that belongs to a sibling layer (plane, vessel, station, CCTV
// camera…) is not "empty space" — leave OUR tracking (and crucially
+834
View File
@@ -0,0 +1,834 @@
import { sunPositionFixed } from '../../geo/celestial.js';
/**
* The ISS model's moving parts. NASA's file names its joints; the build keeps
* each one as a node of its own, with the parts it carries beneath it, all in
* the model's rest frame (glTF axes, meters: X port, Y zenith, Z forward), so
* a joint turns by rotating its node about `pivot`.
*
* By default the angles are computed from where the Sun is: the two alpha
* joints turn the outboard truss about the truss axis, each array's beta
* joint turns it about its mast, and the two radiator joints keep the
* radiators edge-on to the Sun. In the Earth's shadow the arrays feather:
* masts along the flight direction, edge into it.
*
* Where the server relays NASA's public telemetry (issTelemetry.js), the
* arrays, the radiators and one dish take their real angles from it instead,
* and fall back to the computed ones whenever it has nothing to say.
*/
/** Alpha joints (SARJ): rotate about the truss, glTF X. */
export const ISS_ALPHA_JOINTS = Object.freeze([
Object.freeze({ node: 'PORT_ALPHA_ROT', pivot: [19.533, 0, 0] }),
Object.freeze({ node: 'STBD_ALPHA_ROT', pivot: [-19.533, 0, 0] }),
]);
/**
* Beta joints (BGA): rotate about the mast, glTF Z at rest. `face` is the
* sign of the cell side's normal along X at rest (the roll-out arrays sit on
* that side).
*/
export const ISS_BETA_JOINTS = Object.freeze([
Object.freeze({
node: 'PORT_BETA_ROT_2A',
pivot: [36.7319, 0.7256, -3.0077],
face: -1,
}),
Object.freeze({
node: 'PORT_BETA_ROT_4A',
pivot: [36.7319, -0.7258, 2.2332],
face: -1,
}),
Object.freeze({
node: 'PORT_BETA_ROT_2B',
pivot: [53.223, -0.7196, 2.2335],
face: -1,
}),
Object.freeze({
node: 'PORT_BETA_ROT_4B',
pivot: [53.2219, 0.7294, -3.0076],
face: -1,
}),
Object.freeze({
node: 'STBD_BETA_ROT_1A',
pivot: [-36.6608, 0.7257, 3.0224],
face: 1,
}),
Object.freeze({
node: 'STBD_BETA_ROT_3A',
pivot: [-36.6608, -0.7257, -2.2408],
face: 1,
}),
Object.freeze({
node: 'STBD_BETA_ROT_1B',
pivot: [-53.2219, -0.7294, -2.2408],
face: 1,
}),
Object.freeze({
node: 'STBD_BETA_ROT_3B',
pivot: [-53.2232, 0.722, 3.0223],
face: 1,
}),
]);
/** Radiator joints (TRRJ): rotate about glTF Z; the panels face Y at rest. */
export const ISS_RADIATOR_JOINTS = Object.freeze([
Object.freeze({ node: 'PORT_TRRJ_GAMMA_ROT', pivot: [16.1287, 0, -7.4432] }),
Object.freeze({ node: 'STBD_TRRJ_GAMMA_ROT', pivot: [-16.1287, 0, -7.4432] }),
]);
/** How fast a joint may turn on screen, radians per second of wall time. */
export const ISS_JOINT_RATE = (12 * Math.PI) / 180;
/** Below this the Sun is too close to a joint's axis to steer by it. */
const MIN_STEER = 0.05;
const EARTH_RADIUS_M = 6_371_000;
/** The signed difference b - a, wrapped to (-π, π]. */
function wrap(delta) {
let d = delta % (2 * Math.PI);
if (d > Math.PI) d -= 2 * Math.PI;
if (d <= -Math.PI) d += 2 * Math.PI;
return d;
}
/** Of `angle` and `angle + π`, the one nearer to `previous`. */
function nearestHalfTurn(angle, previous) {
const flipped = angle + Math.PI;
return Math.abs(wrap(angle - previous)) <= Math.abs(wrap(flipped - previous))
? angle
: flipped;
}
/**
* Whether a point is in the Earth's shadow, taken as a cylinder.
* @param {number[]} positionEcef Meters.
* @param {number[]} sunEcef Unit vector toward the Sun.
* @returns {boolean}
*/
export function issInShadow(positionEcef, sunEcef) {
const along =
positionEcef[0] * sunEcef[0] +
positionEcef[1] * sunEcef[1] +
positionEcef[2] * sunEcef[2];
if (along >= 0) return false;
const off = Math.hypot(
positionEcef[0] - along * sunEcef[0],
positionEcef[1] - along * sunEcef[1],
positionEcef[2] - along * sunEcef[2],
);
return off < EARTH_RADIUS_M;
}
/**
* The Sun's direction on the model's glTF axes, from the flight axes the
* model is oriented by (x along-track, y orbit normal, z zenith).
* @param {number[]} sunEcef Unit vector toward the Sun, Earth-fixed.
* @param {{x:number[], y:number[], z:number[]}} axes
* @returns {number[]} [port, zenith, forward].
*/
export function issSunInModelFrame(sunEcef, axes) {
const dot = (a) => a[0] * sunEcef[0] + a[1] * sunEcef[1] + a[2] * sunEcef[2];
return [dot(axes.y), dot(axes.z), dot(axes.x)];
}
/**
* The joint angles that point the arrays at the Sun.
* @param {number[]} sun Unit vector toward the Sun on the model's glTF axes.
* @param {boolean} sunlit False in the Earth's shadow: the arrays feather.
* @param {{alpha:number, gamma:number}} [previous] The last targets, so a
* joint with two equivalent answers keeps the nearer one.
* @returns {{alpha:number, beta:number[], gamma:number}} Radians: `alpha`
* about +X for both alpha joints, `beta` about +Z per ISS_BETA_JOINTS entry,
* `gamma` about +Z for both radiator joints.
*/
export function issJointTargets(
sun,
sunlit,
previous = { alpha: 0, gamma: 0 },
) {
const [sx, sy, sz] = sun;
// Radiators: the panel normal, Y at rest, perpendicular to the Sun.
const gamma =
Math.hypot(sx, sy) < MIN_STEER
? previous.gamma
: nearestHalfTurn(Math.atan2(sy, sx), previous.gamma);
if (!sunlit) {
return {
alpha: nearestHalfTurn(0, previous.alpha),
beta: ISS_BETA_JOINTS.map(() => 0),
gamma,
};
}
// Alpha: the masts, ±Z at rest, perpendicular to the Sun.
const alpha =
Math.hypot(sy, sz) < MIN_STEER
? previous.alpha
: nearestHalfTurn(Math.atan2(sz, sy), previous.alpha);
// The Sun as the arrays see it before the alpha turn.
const c = Math.cos(alpha);
const s = Math.sin(alpha);
const lx = sx;
const ly = c * sy + s * sz;
// Beta: the cell side's normal, ±X at rest, onto the Sun.
const beta = ISS_BETA_JOINTS.map(({ face }) =>
Math.atan2(face * ly, face * lx),
);
return { alpha, beta, gamma };
}
/**
* Step `current` toward `target` the short way round, by at most `maxStep`.
* @returns {number}
*/
export function issStepAngle(current, target, maxStep) {
const delta = wrap(target - current);
if (Math.abs(delta) <= maxStep) return current + delta;
return current + Math.sign(delta) * maxStep;
}
/**
* A node's matrix for a turn of `angle` about `axis` ('x' or 'z') through
* `pivot`, column-major.
* @param {'x'|'z'} axis
* @param {number[]} pivot
* @param {number} angle Radians.
* @param {ArrayLike<number>} result Any 16-slot array, column-major.
* @returns {ArrayLike<number>} `result`.
*/
export function issJointMatrix(axis, pivot, angle, result) {
const c = Math.cos(angle);
const s = Math.sin(angle);
const [px, py, pz] = pivot;
// Row-major arguments.
if (axis === 'x')
return set(result, [
1,
0,
0,
0,
0,
c,
-s,
py - (c * py - s * pz),
0,
s,
c,
pz - (s * py + c * pz),
0,
0,
0,
1,
]);
return set(result, [
c,
-s,
0,
px - (c * px - s * py),
s,
c,
0,
py - (s * px + c * py),
0,
0,
1,
0,
0,
0,
0,
1,
]);
}
/**
* Write a row-major 4×4 into `result`, column-major (a renderer's matrix
* layout; `result` is any 16-slot array).
* @param {ArrayLike<number> & {[i: number]: number}} [result] A new one when not given.
* @param {number[]} rowMajor
*/
function set(result, rowMajor) {
result ??= new Float64Array(16);
for (let row = 0; row < 4; row++)
for (let column = 0; column < 4; column++)
result[column * 4 + row] = rowMajor[row * 4 + column];
return result;
}
/**
* Canadarm2's seven joints as NASA's file names them, base to tip: each
* node's pivot and its local Z axis on the model's axes. Where the real arm
* is at any moment is not public, so its motion here is ILLUSTRATIVE: a slow
* sway of `sway` radians about the pose in NASA's file, over `period`
* seconds. Joints with no sway stay as filed.
*/
export const ISS_ARM_JOINTS = Object.freeze(
[
['SHR', [0.6732, -9.3793, 8.3367], [-0.0942, -0.0136, 0.9955], 0, 0],
['SHY', [0.6004, -9.3899, 9.105], [-0.2949, 0.9554, -0.0148], 8, 97],
['SHP_PRIME', [0.7848, -9.9873, 9.1143], [-0.2949, 0.9554, -0.0148], 6, 71],
[
'ELP_PRIME',
[-2.9987, -11.8039, 2.5061],
[-0.2949, 0.9554, -0.0148],
12,
53,
],
['WRP', [-3.8898, -12.6132, 10.249], [-0.2949, 0.9554, -0.0148], 10, 41],
['WRY', [-3.9961, -12.6341, 11.0132], [-0.2949, 0.9554, -0.0148], 0, 0],
['WRR', [-4.2995, -12.7285, 10.9684], [0.2874, -0.5533, -0.7818], 0, 0],
].map(([node, pivot, axis, swayDeg, period]) =>
Object.freeze({
node,
pivot,
axis,
sway: (swayDeg * Math.PI) / 180,
period,
}),
),
);
/**
* The station's smaller arms, swayed the same illustrative way: Dextre's two
* arms (shoulder and elbow pitch each) and the Japanese arm on Kibo
* (shoulder, elbow and wrist pitch). The European arm on Nauka has no joints
* in NASA's file, so it stays as filed.
*/
export const ISS_SMALL_ARM_JOINTS = Object.freeze(
[
[
'SPDM_Arm1_SHP',
[4.3019, -8.7313, 2.9551],
[-0.5183, -0.8218, -0.2366],
5,
61,
],
[
'SPDM_Arm1_ELP',
[4.763, -7.9839, 3.1897],
[0.2256, 0.4303, -0.874],
7,
43,
],
[
'SPDM_Arm2_SHP',
[1.8182, -9.8753, 5.2105],
[-0.27, -0.522, -0.8091],
5,
67,
],
[
'SPDM_Arm2_ELP',
[1.8575, -9.4898, 6.0546],
[-0.3202, -0.5495, -0.7717],
7,
47,
],
['JEM_SP_ROT', [14.2188, -3.6716, 13.394], [-0.001, 0, -1], 5, 83],
['JEM_EP_ROT', [14.2223, 0.6479, 13.394], [-0.0011, 0, -1], 8, 59],
['JEM_WP_ROT', [16.4495, -3.0694, 13.3917], [-0.001, 0, -1], 8, 37],
].map(([node, pivot, axis, swayDeg, period]) =>
Object.freeze({
node,
pivot,
axis,
sway: (swayDeg * Math.PI) / 180,
period,
}),
),
);
/** Every joint that sways. */
const ISS_SWAY_JOINTS = [...ISS_ARM_JOINTS, ...ISS_SMALL_ARM_JOINTS];
/** The arm joints the sway moves; the rest hold NASA's filed pose. */
const ISS_SWAYING_NODES = new Set(
ISS_SWAY_JOINTS.filter((joint) => joint.sway).map((joint) => joint.node),
);
/**
* The arm's illustrative joint angles at a wall-clock time.
* @param {number} seconds
* @returns {number[]} Radians, one per ISS_ARM_JOINTS entry.
*/
export function issArmAngles(seconds, joints = ISS_ARM_JOINTS) {
return joints.map(({ sway, period }) =>
sway ? sway * Math.sin((2 * Math.PI * seconds) / period) : 0,
);
}
/**
* The two Ku-band dishes on the Z1 truss. NASA's file has them welded into
* the truss; the build cuts out everything above each gimbal. At rest a dish
* looks along +Y (zenith).
*/
export const ISS_DISH_JOINTS = Object.freeze([
Object.freeze({ node: 'SGANT_ROT_1', pivot: [-1.105, 4.5, -4.885] }),
Object.freeze({ node: 'SGANT_ROT_2', pivot: [4.56, 4.64, -5.235] }),
]);
/**
* The relay satellites the dishes talk to (NASA's TDRS) sit over the equator
* at fixed longitudes, so each is a fixed point in the Earth-fixed frame.
* These are the fleet's nominal slots (Atlantic, Pacific, Indian Ocean), not
* a live roster: which satellite the station uses at a given moment is not
* public in real time.
*/
export const ISS_RELAY_LONGITUDES_DEG = Object.freeze([-41, -171, 85]);
const GEOSTATIONARY_RADIUS_M = 42_164_000;
/** A dish does not look below this much above the station's horizon plane. */
const DISH_MIN_UP = 0.15;
/**
* Where the relay satellites are from the station, on the model's axes, the
* highest above the station first.
* @param {number[]} positionEcef Meters.
* @param {{x:number[], y:number[], z:number[]}} axes Flight axes.
* @param {readonly number[]} [longitudes] The relays' slots, degrees east;
* NASA's for the ISS, another station passes its own.
* @returns {number[][]} Unit vectors [port, zenith, forward].
*/
export function issRelayDirections(
positionEcef,
axes,
longitudes = ISS_RELAY_LONGITUDES_DEG,
) {
return longitudes
.map((longitude) => {
const lon = (longitude * Math.PI) / 180;
const to = [
GEOSTATIONARY_RADIUS_M * Math.cos(lon) - positionEcef[0],
GEOSTATIONARY_RADIUS_M * Math.sin(lon) - positionEcef[1],
-positionEcef[2],
];
const length = Math.hypot(to[0], to[1], to[2]);
return issSunInModelFrame(
to.map((c) => c / length),
axes,
);
})
.sort((a, b) => b[1] - a[1]);
}
/**
* Turn the unit vector `current` toward `target` by at most `maxStep` radians.
* @returns {number[]}
*/
export function issStepDirection(current, target, maxStep) {
const cos = Math.min(
1,
Math.max(
-1,
current[0] * target[0] + current[1] * target[1] + current[2] * target[2],
),
);
const angle = Math.acos(cos);
if (angle <= maxStep || angle < 1e-6) return target;
const sin = Math.sin(angle);
// Opposite vectors have no single arc between them: nudge off the line.
if (sin < 1e-6)
return issStepDirection(
[current[2], current[0], current[1]],
target,
maxStep,
);
const t = maxStep / angle;
const a = Math.sin((1 - t) * angle) / sin;
const b = Math.sin(t * angle) / sin;
return [0, 1, 2].map((i) => a * current[i] + b * target[i]);
}
/**
* A node's matrix for a turn of `angle` about the unit vector `axis` through
* `pivot`.
* @param {number[]} pivot
* @param {number[]} axis Unit vector.
* @param {number} angle Radians.
* @param {ArrayLike<number>} result Any 16-slot array, column-major.
* @returns {ArrayLike<number>} `result`.
*/
export function issAxisMatrix(pivot, axis, angle, result) {
const [x, y, z] = axis;
const c = Math.cos(angle);
const s = Math.sin(angle);
const t = 1 - c;
const r = [
[t * x * x + c, t * x * y - s * z, t * x * z + s * y],
[t * x * y + s * z, t * y * y + c, t * y * z - s * x],
[t * x * z - s * y, t * y * z + s * x, t * z * z + c],
];
const rows = r.map((row, i) => [
...row,
pivot[i] - (row[0] * pivot[0] + row[1] * pivot[1] + row[2] * pivot[2]),
]);
return set(result, [...rows[0], ...rows[1], ...rows[2], 0, 0, 0, 1]);
}
/**
* A dish node's matrix that turns its rest boresight (+Y) onto `direction`.
* @param {number[]} pivot
* @param {number[]} direction Unit vector on the model's axes.
* @param {ArrayLike<number>} result Any 16-slot array, column-major.
* @returns {ArrayLike<number>} `result`.
*/
export function issAimMatrix(pivot, direction, result) {
// Y × direction
const kx = direction[2];
const kz = -direction[0];
const length = Math.hypot(kx, kz);
if (length < 1e-9)
return issAxisMatrix(
pivot,
[1, 0, 0],
direction[1] > 0 ? 0 : Math.PI,
result,
);
const angle = Math.acos(Math.min(1, Math.max(-1, direction[1])));
return issAxisMatrix(pivot, [kx / length, 0, kz / length], angle, result);
}
/**
* Drives the loaded model's joints. Stateless about the model: `update` looks
* the nodes up once per model and only writes a node whose angle moved.
*/
export function createIssArticulation() {
let boundModel = null;
let nodes = null;
let angles = null;
let targets = { alpha: 0, gamma: 0 };
let lastMs = 0;
let override = null;
let dishOverride = null;
/** Gives the joint angles from telemetry, or null: see setTelemetry. */
let telemetry = null;
/** Command panel state: Manual takes the joints, so telemetry is off. */
let telemetryAllowed = true;
/** Whether the last update took its angles from telemetry; null before one. */
let lastLive = null;
/** Whether the last update had the station in sunlight; null before one. */
let lastSunlit = null;
/** Command panel state: the arm is being posed by hand, so the sway is off. */
/** The arm joints posed by hand (command panel); the rest keep swaying. */
const manualJoints = new Set();
let armNodes = null;
/** Command panel state: how far the arrays are rolled out, 0.05 to 1. */
let deploy = 1;
let deployTarget = 1;
let radiatorDeploy = 1;
let radiatorTarget = 1;
/** The truss face the radiators fold back to, on the model's Z axis. */
const RADIATOR_ROOT_Z = -1.9;
/** The power modules' radiators, cut out by the build, and their root. */
const SMALL_RADIATOR_NODES = [
'PVR_FOLD_P4',
'PVR_FOLD_P6',
'PVR_FOLD_S4',
'PVR_FOLD_S6',
];
const SMALL_RADIATOR_ROOT_Y = -1.6;
/** Where each dish looks now, on the model's axes. */
let dishes = null;
const scratchMatrix = new Float64Array(16);
function bind(model) {
boundModel = model;
const get = (joint) => model.getNode(joint.node) ?? null;
nodes = {
alpha: ISS_ALPHA_JOINTS.map(get),
beta: ISS_BETA_JOINTS.map(get),
gamma: ISS_RADIATOR_JOINTS.map(get),
dish: ISS_DISH_JOINTS.map(get),
};
angles = null;
dishes = null;
armNodes = null;
}
function sunEcef(date) {
const sun = sunPositionFixed(date.getTime());
const length = Math.hypot(sun.x, sun.y, sun.z) || 1;
return [sun.x / length, sun.y / length, sun.z / length];
}
function write(node, axis, pivot, angle) {
if (!node) return;
node.matrix = issJointMatrix(axis, pivot, angle, scratchMatrix);
}
/**
* @param {{ready: boolean, getNode: (name: string) => object|undefined}} model
* A ready model, or any holder of nodes that take a `matrix`.
* @param {Date} date The instant the model is placed at.
* @param {{x:number,y:number,z:number}} position Earth-fixed station position.
* @param {{x:number[], y:number[], z:number[]}} axes Its flight axes.
* @param {number} [nowMs] Wall clock, for the turn rate.
*/
function update(model, date, position, axes, nowMs = Date.now()) {
if (!model.ready) return;
if (model !== boundModel) bind(model);
const forced = override?.(nowMs) ?? null;
if (forced) {
lastSunlit = Boolean(forced.sunlit);
targets = issJointTargets(forced.sun, forced.sunlit, targets);
} else {
const sun = sunEcef(date);
const sunlit = !issInShadow([position.x, position.y, position.z], sun);
lastSunlit = sunlit;
targets = issJointTargets(issSunInModelFrame(sun, axes), sunlit, targets);
}
// Telemetry, when it has a pose, replaces the computed targets; a Sun
// chosen by hand in the command panel is always computed.
const pose = telemetryAllowed && !forced ? (telemetry?.() ?? null) : null;
lastLive = Boolean(pose);
const alphaTargets = pose?.alpha ?? [targets.alpha, targets.alpha];
const betaTargets = pose?.beta ?? targets.beta;
const gammaTargets = pose?.gamma ?? [targets.gamma, targets.gamma];
// A first frame, or one after a pause, goes straight to the pose.
const elapsed = (nowMs - lastMs) / 1000;
lastMs = nowMs;
const maxStep =
!angles || !(elapsed >= 0) || elapsed > 2
? Number.POSITIVE_INFINITY
: ISS_JOINT_RATE * elapsed;
const next = {
alpha: alphaTargets.map((target, i) =>
issStepAngle(angles?.alpha[i] ?? 0, target, maxStep),
),
beta: betaTargets.map((target, i) =>
issStepAngle(angles?.beta[i] ?? 0, target, maxStep),
),
gamma: gammaTargets.map((target, i) =>
issStepAngle(angles?.gamma[i] ?? 0, target, maxStep),
),
};
ISS_ALPHA_JOINTS.forEach((joint, i) => {
if (!angles || next.alpha[i] !== angles.alpha[i])
write(nodes.alpha[i], 'x', joint.pivot, next.alpha[i]);
});
// Command panel: squash the arrays along their masts (see setDeploy).
const deployStep = Number.isFinite(maxStep) ? elapsed / 8 : 1;
const nextDeploy =
deploy +
Math.sign(deployTarget - deploy) *
Math.min(Math.abs(deployTarget - deploy), deployStep);
ISS_BETA_JOINTS.forEach((joint, i) => {
if (
!angles ||
next.beta[i] !== angles.beta[i] ||
nextDeploy !== deploy ||
nextDeploy !== 1
) {
const node = nodes.beta[i];
if (!node) return;
const m = issJointMatrix('z', joint.pivot, next.beta[i], scratchMatrix);
m[10] = nextDeploy;
m[14] = joint.pivot[2] * (1 - nextDeploy);
node.matrix = m;
}
});
deploy = nextDeploy;
// Command panel: fold the radiators toward the truss.
const nextRadiator =
radiatorDeploy +
Math.sign(radiatorTarget - radiatorDeploy) *
Math.min(Math.abs(radiatorTarget - radiatorDeploy), deployStep);
ISS_RADIATOR_JOINTS.forEach((joint, i) => {
if (
angles &&
next.gamma[i] === angles.gamma[i] &&
nextRadiator === radiatorDeploy
)
return;
const node = nodes.gamma[i];
if (!node) return;
const m = issJointMatrix('z', joint.pivot, next.gamma[i], scratchMatrix);
m[10] = nextRadiator;
m[14] = RADIATOR_ROOT_Z * (1 - nextRadiator);
node.matrix = m;
});
// The four small radiators fold up to the truss, along Y.
if (nextRadiator !== radiatorDeploy)
for (const name of SMALL_RADIATOR_NODES) {
const node = model.getNode(name);
if (!node) continue;
node.matrix = set(scratchMatrix, [
1,
0,
0,
0,
0,
nextRadiator,
0,
SMALL_RADIATOR_ROOT_Y * (1 - nextRadiator),
0,
0,
1,
0,
0,
0,
0,
1,
]);
}
radiatorDeploy = nextRadiator;
angles = next;
// Dishes: the highest relay satellite for the first, the next for the
// second; one below the station's horizon plane keeps its last aim.
// Telemetry reports one dish (the station uses one at a time, and does
// not say which): the first takes its real aim, wherever that is, and
// the second holds still.
const liveDish = !dishOverride && pose?.dish ? pose.dish : null;
const relays = dishOverride
? [dishOverride, dishOverride]
: liveDish
? [liveDish, null]
: issRelayDirections([position.x, position.y, position.z], axes);
const nextDishes = ISS_DISH_JOINTS.map((joint, i) => {
const current = dishes?.[i] ?? [0, 1, 0];
const wanted = relays[i];
const target =
wanted && (liveDish || wanted[1] >= DISH_MIN_UP) ? wanted : current;
const stepped = issStepDirection(current, target, maxStep);
const moved =
!dishes || stepped.some((c, k) => Math.abs(c - current[k]) > 1e-9);
if (moved)
if (nodes.dish[i])
nodes.dish[i].matrix = issAimMatrix(
joint.pivot,
stepped,
scratchMatrix,
);
return stepped;
});
dishes = nextDishes;
// Arm: an illustrative sway (see ISS_ARM_JOINTS).
{
const arm = issArmAngles(nowMs / 1000, ISS_SWAY_JOINTS);
ISS_SWAY_JOINTS.forEach((joint, i) => {
if (!joint.sway || manualJoints.has(joint.node)) return;
const node = (armNodes ??= ISS_SWAY_JOINTS.map(
(entry) => model.getNode(entry.node) ?? null,
))[i];
if (node)
node.matrix = issAxisMatrix(
joint.pivot,
joint.axis,
arm[i],
scratchMatrix,
);
});
}
}
/**
* Command panel: turn any named node about an axis through a pivot.
* @param {string} name
* @param {number[]} pivot
* @param {number[]} axis Unit vector.
* @param {number} angle Radians.
*/
function setJoint(name, pivot, axis, angle) {
manualJoints.add(name);
const node = boundModel?.getNode(name);
if (node) node.matrix = issAxisMatrix(pivot, axis, angle, scratchMatrix);
}
/** Forget the model and every manual choice: the next update starts clean. */
function reset() {
boundModel = null;
nodes = null;
angles = null;
dishes = null;
armNodes = null;
targets = { alpha: 0, gamma: 0 };
override = null;
dishOverride = null;
telemetryAllowed = true;
manualJoints.clear();
}
/**
* Command panel: a function giving the Sun on the model's axes (and whether the
* station is lit) in place of the real one, or null for the real one.
* @param {((nowMs:number)=>{sun:number[], sunlit:boolean}|null)|null} fn
*/
function setOverride(fn) {
override = fn;
}
/** Whether the station is in sunlight, as of the last update. */
function isSunlit() {
return lastSunlit;
}
/**
* Where the joint angles come from when telemetry has them: a function
* giving `{alpha, beta, gamma, dish}` (issTelemetryPose) or null.
* @param {(() => {alpha:number[], beta:number[], gamma:number[],
* dish:number[]|null}|null)|null} fn
*/
function setTelemetry(fn) {
telemetry = fn;
}
/** Command panel: Manual switches telemetry off, Automatic back on. */
function setTelemetryAllowed(allowed) {
telemetryAllowed = Boolean(allowed);
}
/** Whether the last update took its angles from telemetry; null before one. */
function isLive() {
return lastLive;
}
/** Command panel: aim both dishes along a unit vector, or null for the relays. */
function setDishOverride(direction) {
dishOverride = direction;
}
/**
* Command panel: squash the arrays toward their bases, or let them
* out again. The real arrays do not retract in service.
* @param {boolean} out
*/
function setDeploy(out) {
deployTarget = out ? 1 : 0.05;
}
/**
* Command panel: fold the radiators toward the truss, or let them
* out. The real ones are accordion panels that can do this, but stay out
* in service.
* @param {boolean} out
*/
function setRadiatorDeploy(out) {
radiatorTarget = out ? 1 : 0.08;
}
/** Command panel: hand the arm back to its sway. */
function resumeArm() {
// A joint the sway does not move would keep its manual angle: it goes
// back to its filed pose. The swaying ones are posed again next update.
for (const name of manualJoints) {
if (ISS_SWAYING_NODES.has(name)) continue;
const node = boundModel?.getNode(name);
if (node) node.matrix = undefined;
}
manualJoints.clear();
}
return {
update,
reset,
setOverride,
setDishOverride,
setJoint,
resumeArm,
setDeploy,
setRadiatorDeploy,
isSunlit,
setTelemetry,
setTelemetryAllowed,
isLive,
};
}
@@ -0,0 +1,231 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import test from 'node:test';
import {
ISS_ALPHA_JOINTS,
ISS_BETA_JOINTS,
ISS_RADIATOR_JOINTS,
issInShadow,
issJointMatrix,
issJointTargets,
issStepAngle,
issSunInModelFrame,
} from './issArticulation.js';
const rotX = (a, [x, y, z]) => [
x,
Math.cos(a) * y - Math.sin(a) * z,
Math.sin(a) * y + Math.cos(a) * z,
];
const rotZ = (a, [x, y, z]) => [
Math.cos(a) * x - Math.sin(a) * y,
Math.sin(a) * x + Math.cos(a) * y,
z,
];
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const unit = (v) => v.map((c) => c / Math.hypot(...v));
const SUNS = [
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0.5, 0.5, 0.7],
[-0.6, 0.2, -0.77],
[0.3, -0.9, 0.3],
[0.9, 0.1, -0.4],
].map(unit);
test('in sunlight every array faces the Sun, masts across it', () => {
for (const sun of SUNS) {
const { alpha, beta } = issJointTargets(sun, true);
assert.ok(Math.abs(dot(rotX(alpha, [0, 0, 1]), sun)) < 1e-9);
ISS_BETA_JOINTS.forEach(({ face }, i) => {
// The beta joint hangs from the alpha joint: beta turns first.
const normal = rotX(alpha, rotZ(beta[i], [face, 0, 0]));
assert.ok(dot(normal, sun) > 1 - 1e-9, `${sun} array ${i}`);
});
}
});
test('the radiators stay edge-on to the Sun', () => {
for (const sun of SUNS) {
const { gamma } = issJointTargets(sun, true);
assert.ok(Math.abs(dot(rotZ(gamma, [0, 1, 0]), sun)) < 1e-9);
}
});
test('in the shadow the arrays feather along the flight direction', () => {
const { alpha, beta } = issJointTargets(unit([0.2, -0.9, 0.3]), false, {
alpha: 3,
gamma: 0,
});
assert.ok(Math.abs(Math.sin(alpha)) < 1e-9); // masts back along ±Z
assert.ok(Math.abs(alpha - Math.PI) < 1e-9); // the nearer half turn
assert.deepEqual(
beta,
ISS_BETA_JOINTS.map(() => 0),
);
});
test('a joint keeps the answer nearer its last one, and holds near its axis', () => {
const first = issJointTargets(unit([0, 1, 0.01]), true);
const next = issJointTargets(unit([0, 1, -0.01]), true, first);
assert.ok(Math.abs(next.alpha - first.alpha) < 0.05);
// Sun along the truss: nothing to steer the alpha joint by.
const held = issJointTargets([1, 0, 0], true, { alpha: 1.2, gamma: 0.4 });
assert.equal(held.alpha, 1.2);
});
test('angles step the short way round, capped', () => {
assert.equal(issStepAngle(0, 1, 0.25), 0.25);
assert.ok(issStepAngle(3, -3, 0.1) > 3); // through π, not back through 0
assert.equal(issStepAngle(0.2, 0.3, 1), 0.3);
});
test('a joint matrix leaves its pivot in place', () => {
for (const axis of ['x', 'z']) {
const pivot = [3, -2, 5];
const m = issJointMatrix(axis, pivot, 0.7, undefined);
const moved = [0, 1, 2].map(
(r) =>
m[r] * pivot[0] + m[4 + r] * pivot[1] + m[8 + r] * pivot[2] + m[12 + r],
);
moved.forEach((v, i) => assert.ok(Math.abs(v - pivot[i]) < 1e-12));
}
});
test('the shadow is the cylinder behind the Earth', () => {
const sun = [1, 0, 0];
assert.equal(issInShadow([6_790_000, 0, 0], sun), false);
assert.equal(issInShadow([-6_790_000, 0, 0], sun), true);
assert.equal(issInShadow([-1_000_000, 6_700_000, 0], sun), false);
});
test('the Sun lands on the model axes: port, zenith, forward', () => {
const axes = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };
assert.deepEqual(issSunInModelFrame([0.1, 0.2, 0.3], axes), [0.2, 0.3, 0.1]);
});
test('the model file has every joint node, beta joints under their alpha', () => {
const buf = fs.readFileSync(
new URL('../../../public/models/iss.glb', import.meta.url),
);
const json = JSON.parse(
buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8'),
);
const byName = new Map(json.nodes.map((n) => [n.name, n]));
for (const { node } of [
...ISS_ALPHA_JOINTS,
...ISS_BETA_JOINTS,
...ISS_RADIATOR_JOINTS,
]) {
const n = byName.get(node);
assert.ok(n, node);
// Joints rest at identity: the pivots above are in the model's own frame.
assert.equal(n.rotation, undefined);
assert.equal(n.translation, undefined);
assert.equal(n.matrix, undefined);
}
for (const side of ['PORT', 'STBD']) {
const kids = byName
.get(`${side}_ALPHA_ROT`)
.children.map((i) => json.nodes[i].name);
for (const { node } of ISS_BETA_JOINTS)
if (node.startsWith(side)) assert.ok(kids.includes(node), node);
}
});
test('a dish aims its rest boresight (+Y) at the direction, pivot in place', async () => {
const { issAimMatrix, ISS_DISH_JOINTS } =
await import('./issArticulation.js');
for (const direction of SUNS) {
const m = issAimMatrix(ISS_DISH_JOINTS[0].pivot, direction, undefined);
// Column 1 is where +Y goes.
[m[4], m[5], m[6]].forEach((v, i) =>
assert.ok(Math.abs(v - direction[i]) < 1e-9),
);
const p = ISS_DISH_JOINTS[0].pivot;
[0, 1, 2].forEach((r) =>
assert.ok(
Math.abs(
m[r] * p[0] + m[4 + r] * p[1] + m[8 + r] * p[2] + m[12 + r] - p[r],
) < 1e-9,
),
);
}
});
test('relay directions are unit vectors, highest above the station first', async () => {
const { issRelayDirections } = await import('./issArticulation.js');
// Over the equator at 41°W, flying east: the Atlantic relay is overhead.
const lon = (-41 * Math.PI) / 180;
const r = 6_790_000;
const position = [r * Math.cos(lon), r * Math.sin(lon), 0];
const zenith = [Math.cos(lon), Math.sin(lon), 0];
const east = [-Math.sin(lon), Math.cos(lon), 0];
const axes = { x: east, y: [0, 0, 1], z: zenith };
const relays = issRelayDirections(position, axes);
assert.equal(relays.length, 3);
relays.forEach((d) => assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-9));
assert.ok(relays[0][1] > 0.999);
assert.ok(relays[0][1] >= relays[1][1] && relays[1][1] >= relays[2][1]);
});
test('a direction steps along the arc, capped, and lands on the target', async () => {
const { issStepDirection } = await import('./issArticulation.js');
const stepped = issStepDirection([0, 1, 0], [1, 0, 0], 0.1);
assert.ok(Math.abs(Math.hypot(...stepped) - 1) < 1e-9);
assert.ok(Math.abs(Math.acos(stepped[1]) - 0.1) < 1e-9);
assert.deepEqual(issStepDirection([0, 1, 0], [1, 0, 0], 2), [1, 0, 0]);
});
test('the model file has both dish nodes', async () => {
const { ISS_DISH_JOINTS } = await import('./issArticulation.js');
const buf = fs.readFileSync(
new URL('../../../public/models/iss.glb', import.meta.url),
);
const json = JSON.parse(
buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8'),
);
for (const { node } of ISS_DISH_JOINTS) {
const n = json.nodes.find((candidate) => candidate.name === node);
assert.ok(n?.children?.length, node);
}
});
test('the arm sways gently about the filed pose, and only where it is set to', async () => {
const { ISS_ARM_JOINTS, issArmAngles } = await import('./issArticulation.js');
assert.equal(ISS_ARM_JOINTS.length, 7);
for (let seconds = 0; seconds < 400; seconds += 7) {
issArmAngles(seconds).forEach((angle, i) => {
assert.ok(Math.abs(angle) <= ISS_ARM_JOINTS[i].sway + 1e-12);
// Illustrative, so kept small.
assert.ok(Math.abs(angle) <= (12 * Math.PI) / 180 + 1e-12);
});
}
assert.deepEqual(issArmAngles(0), [0, 0, 0, 0, 0, 0, 0]);
});
test('the smaller arms sway too, and their joints are in the model file', async () => {
const { ISS_SMALL_ARM_JOINTS, ISS_ARM_JOINTS, issArmAngles } =
await import('./issArticulation.js');
const buf = fs.readFileSync(
new URL('../../../public/models/iss.glb', import.meta.url),
);
const json = JSON.parse(
buf.subarray(20, 20 + buf.readUInt32LE(12)).toString('utf8'),
);
const names = new Set(json.nodes.map((n) => n.name));
for (const { node, sway, axis } of [
...ISS_ARM_JOINTS,
...ISS_SMALL_ARM_JOINTS,
]) {
assert.ok(names.has(node), node);
assert.ok(sway <= (12 * Math.PI) / 180 + 1e-12);
assert.ok(Math.abs(Math.hypot(...axis) - 1) < 1e-3);
}
assert.equal(
issArmAngles(10, ISS_SMALL_ARM_JOINTS).length,
ISS_SMALL_ARM_JOINTS.length,
);
});
+105
View File
@@ -0,0 +1,105 @@
const unit = (v) => {
const n = Math.hypot(...v);
return v.map((c) => c / n);
};
/** Where "Zoom to the ISS" stops: the whole 109 m station fills the view. */
export const ISS_COMMAND_ZOOM_RANGE_M = 260;
/** Beyond this the camera counts as far, and the zoom button is offered. */
export const ISS_COMMAND_FAR_M = 1000;
/**
* Whether "Zoom to the ISS" is offered: only from far away, so it goes once
* the camera is in close (by the button or by hand) and returns on zooming
* back out.
* @param {number} distance Meters from the camera to the station.
* @returns {boolean}
*/
export function issCommandOffersZoom(distance) {
return distance > ISS_COMMAND_FAR_M;
}
/**
* One step of the zoom: how far to move in from `distance`, easing out as
* the target range nears, never past it.
* @param {number} distance Meters from the camera to the station.
* @returns {number} Meters to move in; 0 once close enough.
*/
export function issCommandZoomStep(distance) {
const left = distance - ISS_COMMAND_ZOOM_RANGE_M;
if (!(left > ISS_COMMAND_ZOOM_RANGE_M * 0.02)) return 0;
return left * 0.14;
}
/**
* The follow camera's range after one step of the zoom: the step nearer,
* never past the target range, and unchanged once there. The camera is moved
* by scaling its follow offset from the station (the camera port's
* `followOffset`, the eye in the follow's frame) by
* `issCommandZoomRange(range) / range`, which can only bring it in; a move
* along the view direction is not used, since it ran away when the camera
* was not looking at the station.
* @param {number} range Meters from the camera to the station.
* @returns {number} The range to set; `range` itself when there is no step.
*/
export function issCommandZoomRange(range) {
if (!(range > 0) || !Number.isFinite(range)) return range;
const step = issCommandZoomStep(range);
return step > 0 ? Math.max(ISS_COMMAND_ZOOM_RANGE_M, range - step) : range;
}
/**
* One step of the zoom on the follow offset: the same offset, shortened to
* `issCommandZoomRange` of its length, so the eye keeps its bearing on the
* station and only comes in.
* @param {{x: number, y: number, z: number}|null|undefined} offset The
* eye's offset from the station, metres in the follow's frame.
* @returns {{x: number, y: number, z: number}|null} The offset to set; null
* when there is no step (close enough, or no offset to shorten).
*/
export function issCommandZoomOffset(offset) {
if (!offset) return null;
const range = Math.hypot(offset.x, offset.y, offset.z);
const next = issCommandZoomRange(range);
if (!(next < range)) return null;
const k = next / range;
return { x: offset.x * k, y: offset.y * k, z: offset.z * k };
}
/**
* Whether the zoom may run: only while the camera follows the station's
* follow target and has framed it, so that its follow offset is the eye's
* offset from the station and shortening it brings the camera in. From any
* other camera (still flying to the station, following something else, or
* a follow not yet framed) there is no such offset to shorten.
* @param {{followed?: object|null, followFramed?: boolean}|null|undefined}
* camera What the camera port reports (`cameraOf(viewer)`).
* @param {object|null|undefined} target The layer's follow target for the
* station (`layerState._followTarget`).
* @returns {boolean}
*/
export function issCommandCameraOnStation(camera, target) {
return (
Boolean(target) &&
camera?.followed === target &&
camera.followFramed === true
);
}
/** How long one lap of the "fast orbit" takes, and its share in shadow. */
const FAST_ORBIT_MS = 40_000;
/**
* The Sun over one accelerated orbit: it circles the truss, a third of the
* lap in the Earth's shadow.
* @param {number} elapsedMs
* @returns {{sun: number[], sunlit: boolean}}
*/
export function issCommandFastOrbit(elapsedMs) {
const angle = (elapsedMs / FAST_ORBIT_MS) * 2 * Math.PI;
return {
sun: unit([0.35, Math.cos(angle), Math.sin(angle)]),
sunlit: Math.cos(angle) > -0.5,
};
}
+141
View File
@@ -0,0 +1,141 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
issCommandCameraOnStation,
issCommandZoomOffset,
issCommandZoomRange,
ISS_COMMAND_ZOOM_RANGE_M,
issCommandFastOrbit,
issCommandZoomStep,
} from './issCommand.js';
import { ISS_NORAD } from './policy.js';
test('the zoom eases in to its range and stops there, never past it', () => {
let distance = 726_000;
let steps = 0;
for (; steps < 400; steps++) {
const step = issCommandZoomStep(distance);
if (!step) break;
assert.ok(step > 0 && step < distance - ISS_COMMAND_ZOOM_RANGE_M);
distance -= step;
}
assert.ok(steps < 120); // under two seconds at 60 frames a second
assert.ok(distance >= ISS_COMMAND_ZOOM_RANGE_M);
assert.ok(distance <= ISS_COMMAND_ZOOM_RANGE_M * 1.02 + 1e-6);
// Already closer: nothing to do, and it never pushes the camera back out.
assert.equal(issCommandZoomStep(180), 0);
});
test('the fast orbit turns the Sun once per lap, part of it in shadow', () => {
const start = issCommandFastOrbit(0);
assert.ok(Math.abs(Math.hypot(...start.sun) - 1) < 1e-9);
assert.equal(start.sunlit, true);
assert.equal(issCommandFastOrbit(20_000).sunlit, false); // half a lap: below
const lap = issCommandFastOrbit(40_000);
lap.sun.forEach((v, i) => assert.ok(Math.abs(v - start.sun[i]) < 1e-9));
});
test('the zoom is offered only from far away', async () => {
const { ISS_COMMAND_FAR_M, issCommandOffersZoom } =
await import('./issCommand.js');
assert.equal(issCommandOffersZoom(726_000), true);
assert.equal(issCommandOffersZoom(ISS_COMMAND_FAR_M + 1), true);
// Where the zoom itself stops, and anywhere closer, it is gone.
assert.equal(issCommandOffersZoom(ISS_COMMAND_ZOOM_RANGE_M * 1.02), false);
assert.equal(issCommandOffersZoom(150), false);
});
test('an object docked to the ISS is the station too', async () => {
const { issTrackedOnStation } = await import('./policy.js');
const NAUKA = 49044;
// Tracking Nauka, the ISS shares its position; tracking the ISS needs nothing.
assert.equal(issTrackedOnStation(ISS_NORAD, new Set()), true);
assert.equal(issTrackedOnStation(ISS_NORAD, null), true);
assert.equal(issTrackedOnStation(NAUKA, new Set([ISS_NORAD, 68837])), true);
// Another satellite, with or without neighbours, is not.
assert.equal(issTrackedOnStation(20580, new Set()), false);
assert.equal(issTrackedOnStation(20580, new Set([20581])), false);
assert.equal(issTrackedOnStation(null, new Set([ISS_NORAD])), false);
assert.equal(issTrackedOnStation(undefined, undefined), false);
});
test('the zoom range only ever shortens, settles at the target range and never runs away', () => {
let range = 1e9;
let steps = 0;
while (steps < 400) {
const next = issCommandZoomRange(range);
assert.ok(next <= range, `step ${steps} moved out: ${range} -> ${next}`);
assert.ok(next >= ISS_COMMAND_ZOOM_RANGE_M, 'never past the target');
if (next === range) break;
range = next;
steps += 1;
}
assert.ok(steps < 400, "settles within the loop's budget");
assert.ok(range <= ISS_COMMAND_ZOOM_RANGE_M * 1.02);
assert.equal(
issCommandZoomRange(ISS_COMMAND_ZOOM_RANGE_M),
ISS_COMMAND_ZOOM_RANGE_M,
);
assert.equal(
issCommandZoomRange(100),
100,
'closer than the range: left alone',
);
for (const bad of [0, -5, NaN, Infinity])
assert.ok(
Object.is(issCommandZoomRange(bad), bad),
`${bad} passes through`,
);
});
test('one zoom step shortens the follow offset on its own bearing, and stops at the range', () => {
const next = issCommandZoomOffset({ x: 3000, y: 4000, z: 0 });
const range = Math.hypot(next.x, next.y, next.z);
assert.ok(Math.abs(range - issCommandZoomRange(5000)) < 1e-9);
assert.ok(Math.abs(next.x / next.y - 3 / 4) < 1e-12, 'the bearing is kept');
assert.equal(next.z, 0);
// Already at the range, or closer: no step.
assert.equal(
issCommandZoomOffset({ x: ISS_COMMAND_ZOOM_RANGE_M, y: 0, z: 0 }),
null,
);
assert.equal(issCommandZoomOffset({ x: 0, y: 100, z: 0 }), null);
// Nothing to shorten: no follow offset yet (the follow has not framed).
assert.equal(issCommandZoomOffset(null), null);
assert.equal(issCommandZoomOffset(undefined), null);
assert.equal(issCommandZoomOffset({ x: 0, y: 0, z: 0 }), null);
});
test("the zoom needs the camera following the station's target, framed", () => {
const target = { key: 'satellites:25544' };
const on = { followed: target, followFramed: true };
assert.equal(issCommandCameraOnStation(on, target), true);
assert.equal(
issCommandCameraOnStation(
{ followed: target, followFramed: false },
target,
),
false,
'not before the follow has framed the eye',
);
assert.equal(
issCommandCameraOnStation({ followed: null, followFramed: false }, target),
false,
);
assert.equal(
issCommandCameraOnStation(
{ followed: { key: 'flights:a' }, followFramed: true },
target,
),
false,
'following something else',
);
assert.equal(issCommandCameraOnStation(null, target), false);
assert.equal(issCommandCameraOnStation(undefined, target), false);
assert.equal(issCommandCameraOnStation(on, null), false);
assert.equal(
issCommandCameraOnStation({ followed: null, followFramed: true }, null),
false,
'nothing followed and no target is not a match',
);
});
+144
View File
@@ -0,0 +1,144 @@
import { createIssArticulation } from './issArticulation.js';
import {
ISS_MOUNTS,
ISS_NAUKA_NORAD,
ISS_POISK_NORAD,
issMountView,
issMountViews,
issMountWorld,
} from './issMounts.js';
import { createIssTelemetryFeed } from './issTelemetry.js';
import {
ISS_COMPANION_COARSE_M,
ISS_COMPANION_RADIUS_M,
ISS_COMPANION_SCAN_MS,
ISS_CARD_CLEAR_M,
ISS_MODEL_LOCAL_AXES,
ISS_MODEL_MAX_DISTANCE_M,
ISS_MODEL_MIN_PX,
ISS_MODEL_NATIVE_SPAN,
ISS_MODEL_URL,
ISS_NORAD,
ISS_ORBIT_HIDE_M,
ISS_SPAN_M,
} from './policy.js';
import {
createStationModel,
stationFlightAxes,
stationModelShouldShow,
temeToEcefAxes,
} from './stationModel.js';
/** The model's scale for the real 109 m truss. */
export const ISS_MODEL_SCALE = ISS_SPAN_M / ISS_MODEL_NATIVE_SPAN;
// The station-independent rules live in stationModel.js; these names are
// kept for the code and tests written against the ISS-only model.
export { temeToEcefAxes };
export const issFlightAxes = stationFlightAxes;
/**
* Whether the ISS model may be drawn (stationModelShouldShow with the ISS's
* `hasIss` wording).
* @param {{enabled: boolean, showPoints: boolean, hasIss: boolean,
* classVisible: boolean, tracked: boolean, cockpitHidden: boolean}} input
* @returns {boolean}
*/
export function issModelShouldShow({ hasIss, ...rest }) {
return stationModelShouldShow({ hasStation: hasIss, ...rest });
}
/**
* Whether a catalog entry at the ISS is one of the station's own modules
* (Zarya, Nauka, Poisk, or any other the catalog lists as "ISS (…)") rather
* than a visiting vehicle. A missing entry counts as a module.
* @param {number} noradId
* @param {{name?: string}|undefined} entry
* @returns {boolean}
*/
export function issIsModule(noradId, entry) {
return (
noradId === ISS_NORAD ||
noradId === ISS_NAUKA_NORAD ||
noradId === ISS_POISK_NORAD ||
/^ISS\s*\(/i.test(entry?.name ?? 'ISS (')
);
}
/**
* The ISS as the station model factory describes it: NASA's model at the
* real 109 m span, its joints on the Sun or NASA's telemetry, the Cockpit's
* views from mounts on the model (so the model stays drawn in the Cockpit),
* and its orbit ring, which has rules of its own (`_syncIssOrbit`).
* @param {{parts: object}} context
* @returns {import('./stationModel.js').StationModelSpec}
*/
export function issModelSpec({ parts }) {
return {
key: 'iss',
label: 'ISS', // i18n-ignore: the station's name, for log lines
norad: ISS_NORAD,
modelUrl: ISS_MODEL_URL,
scale: ISS_MODEL_SCALE,
minPx: ISS_MODEL_MIN_PX,
maxDistanceM: ISS_MODEL_MAX_DISTANCE_M,
orbitHideM: ISS_ORBIT_HIDE_M,
cardClearM: ISS_CARD_CLEAR_M,
companionRadiusM: ISS_COMPANION_RADIUS_M,
companionCoarseM: ISS_COMPANION_COARSE_M,
companionScanMs: ISS_COMPANION_SCAN_MS,
localAxes: ISS_MODEL_LOCAL_AXES,
isModule: issIsModule,
createArticulation: createIssArticulation,
createTelemetry: createIssTelemetryFeed,
/**
* One of the views on the model (issMounts.js), in the world.
* `noradId` on the result is the catalog entry the view belongs to.
*/
cockpitMount: ({ key, centre, axes, name, entry, dockedVehicle }) => {
const views = issMountViews({
naukaName: name(ISS_NAUKA_NORAD),
zaryaName: name(ISS_NORAD),
poiskName: name(ISS_POISK_NORAD),
dockedName: name(dockedVehicle),
naukaNorad: entry(ISS_NAUKA_NORAD),
zaryaNorad: entry(ISS_NORAD),
poiskNorad: entry(ISS_POISK_NORAD),
dockedNorad: entry(dockedVehicle),
});
const view = issMountView(views, key);
return {
...issMountWorld(ISS_MOUNTS[view.key], centre, axes),
key: view.key,
label: view.label,
noradId: view.noradId,
card: view.card,
views,
};
},
// The Cockpit rides the station from a mount on the model, so the model
// stays while it does.
hideInCockpit: false,
syncOrbit: () => parts.controls._syncIssOrbit?.(),
};
}
/**
* The ISS as a 3D model when the camera is close (stationModel.js), with the
* part's methods also under their former ISS-only names.
* @param {{state: object, parts: object, resolveAsset?: (url: string) => string}} context
*/
export function createIssModel(context) {
const model = createStationModel(issModelSpec(context), context);
return {
...model,
_updateIssModel: model._updateStationModel,
_destroyIssModel: model._destroyStationModel,
_issVisualPosition: model._visualPosition,
_issCardClearPx: model._cardClearPx,
_issStandsInFor: model._standsInFor,
_issCockpitMount: model._cockpitMount,
_issTelemetryStatus: model._telemetryStatus,
_issArticulation: model._articulation,
};
}
+153
View File
@@ -0,0 +1,153 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { gstime, propagate, twoline2satrec } from 'satellite.js';
import {
ISS_MODEL_SCALE,
issFlightAxes,
issModelShouldShow,
temeToEcefAxes,
} from './issModel.js';
import {
ISS_MODEL_CENTER_NATIVE,
ISS_MODEL_LOCAL_AXES,
ISS_MODEL_NATIVE_SPAN,
ISS_MODEL_URL,
ISS_NORAD,
ISS_SPAN_M,
} from './policy.js';
const ISS_TLE = [
'1 25544U 98067A 24001.50000000 .00016717 00000-0 10270-3 0 9002',
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.50377579 1234',
];
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const norm = (a) => Math.hypot(a[0], a[1], a[2]);
const shown = {
enabled: true,
showPoints: true,
hasIss: true,
classVisible: true,
tracked: false,
cockpitHidden: false,
};
test('the ISS model shows on the same terms as its dot', () => {
assert.equal(issModelShouldShow(shown), true);
assert.equal(issModelShouldShow({ ...shown, enabled: false }), false);
assert.equal(issModelShouldShow({ ...shown, showPoints: false }), false);
assert.equal(issModelShouldShow({ ...shown, hasIss: false }), false);
assert.equal(issModelShouldShow({ ...shown, classVisible: false }), false);
});
test('a tracked ISS keeps its model with its class hidden', () => {
assert.equal(
issModelShouldShow({ ...shown, classVisible: false, tracked: true }),
true,
);
});
test('the Cockpit hold hides the model', () => {
assert.equal(
issModelShouldShow({ ...shown, tracked: true, cockpitHidden: true }),
false,
);
});
test('the model is the ISS by NORAD number, at its real 109 m span', () => {
assert.equal(ISS_NORAD, 25544);
assert.ok(
Math.abs(ISS_MODEL_SCALE * ISS_MODEL_NATIVE_SPAN - ISS_SPAN_M) < 1e-9,
);
});
test('the native span and centre match the shipped asset', () => {
const glb = readFileSync(
new URL(`../../../public${ISS_MODEL_URL}`, import.meta.url),
);
const jsonLength = glb.readUInt32LE(12);
const gltf = JSON.parse(glb.subarray(20, 20 + jsonLength).toString('utf8'));
const root = gltf.nodes[gltf.scenes[0].nodes[0]];
const min = [Infinity, Infinity, Infinity];
const max = [-Infinity, -Infinity, -Infinity];
// Every node below the root rests untransformed (joint nodes included), so
// each mesh's bounds are already in the root's frame.
const visit = (index) => {
const node = gltf.nodes[index];
assert.equal(node.rotation ?? null, null);
assert.equal(node.scale ?? null, null);
assert.equal(node.translation ?? null, null);
for (const primitive of gltf.meshes[node.mesh]?.primitives ?? []) {
const accessor = gltf.accessors[primitive.attributes.POSITION];
for (let i = 0; i < 3; i++) {
min[i] = Math.min(min[i], accessor.min[i]);
max[i] = Math.max(max[i], accessor.max[i]);
}
}
(node.children ?? []).forEach(visit);
};
root.children.forEach(visit);
// The truss is the longest axis, glTF X.
assert.ok(Math.abs(max[0] - min[0] - ISS_MODEL_NATIVE_SPAN) < 0.01);
assert.ok(max[0] - min[0] > max[1] - min[1]);
assert.ok(max[0] - min[0] > max[2] - min[2]);
ISS_MODEL_CENTER_NATIVE.forEach((value, i) =>
assert.ok(Math.abs((min[i] + max[i]) / 2 - value) < 0.01),
);
// The scene root moves that centre to the origin: minimumPixelSize scales
// the model about its origin, so the far-range model stays centred.
assert.deepEqual(
root.translation.map((value, i) => value + ISS_MODEL_CENTER_NATIVE[i]),
[0, 0, 0],
);
// NASA's own textures ship with it.
assert.ok(gltf.textures.length > 0);
});
test('the model axes are a proper rotation of the flight axes', () => {
// A cyclic order of x, y, z keeps the frame right-handed (no mirroring).
const order = ISS_MODEL_LOCAL_AXES.join('');
assert.ok(['xyz', 'yzx', 'zxy'].includes(order));
});
test('flight axes: orthonormal, z away from the Earth, x along the motion', () => {
const satrec = twoline2satrec(ISS_TLE[0], ISS_TLE[1]);
for (const minutes of [0, 17, 46, 80]) {
const date = new Date(Date.UTC(2024, 0, 1, 12, minutes));
const { position, velocity } = propagate(satrec, date);
const gmst = gstime(date);
const r = temeToEcefAxes(position, gmst);
const v = temeToEcefAxes(velocity, gmst);
const axes = issFlightAxes(r, v);
for (const key of ['x', 'y', 'z'])
assert.ok(Math.abs(norm(axes[key]) - 1) < 1e-9);
assert.ok(Math.abs(dot(axes.x, axes.y)) < 1e-9);
assert.ok(Math.abs(dot(axes.y, axes.z)) < 1e-9);
assert.ok(Math.abs(dot(axes.x, axes.z)) < 1e-9);
const rUnit = [r.x, r.y, r.z].map((c) => c / norm([r.x, r.y, r.z]));
assert.ok(dot(axes.z, rUnit) > 0.999999);
// A near-circular orbit: the along-track axis is almost the velocity.
const vUnit = [v.x, v.y, v.z].map((c) => c / norm([v.x, v.y, v.z]));
assert.ok(dot(axes.x, vUnit) > 0.999);
// Right-handed: x × y = z.
const cross = [
axes.x[1] * axes.y[2] - axes.x[2] * axes.y[1],
axes.x[2] * axes.y[0] - axes.x[0] * axes.y[2],
axes.x[0] * axes.y[1] - axes.x[1] * axes.y[0],
];
assert.ok(dot(cross, axes.z) > 0.999999);
}
});
test('flight axes refuse a degenerate state', () => {
assert.equal(issFlightAxes({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }), null);
assert.equal(issFlightAxes({ x: 1, y: 0, z: 0 }, { x: 2, y: 0, z: 0 }), null);
});
test('TEME to Earth-fixed axes keeps the position eciToGeodetic uses', () => {
const v = temeToEcefAxes({ x: 1, y: 0, z: 0 }, Math.PI / 2);
assert.ok(Math.abs(v.x) < 1e-12);
assert.ok(Math.abs(v.y + 1) < 1e-12);
});
+257
View File
@@ -0,0 +1,257 @@
import { msg } from '../../i18n/index.js';
/**
* Where the Cockpit camera sits when it rides the station. The ISS has
* several catalog entries that are one body (the ISS itself, listed under
* Zarya, its first module; Nauka; whatever vehicle is docked). Riding any of
* them looks out from a point on its 3D model, away from the station, in
* place of the straight-down picture every other satellite has, and the
* Cockpit steps between the views: from Nauka, from Zarya, from Poisk, from
* the Cupola, from Kibo, from a docked vehicle. Each looks outward, in a direction of its own, and the
* arrows turn the view from there. From this height the Earth's limb is 20°
* below level: a view 30° down has it across its upper part.
*
* The points were chosen by casting rays across the view against the model
* at rest: each is over a meter clear of every surface, and at most a tenth
* of its frame meets the station, none of it nearer than 12 m.
*
* Points and directions are on the model's axes in meters (X port, Y zenith,
* Z forward), from the model's origin: the frame the file's nodes sit in.
*/
/**
* The station's modules that have catalog entries of their own, beside the
* ISS's (ISS_NORAD in policy.js, listed as "ISS (ZARYA)"): Nauka and Poisk.
*/
export const ISS_NAUKA_NORAD = 49044;
export const ISS_POISK_NORAD = 36086;
const mount = (eye, forward, up) =>
Object.freeze({
eye: Object.freeze(eye),
forward: Object.freeze(forward),
up: Object.freeze(up),
});
export const ISS_MOUNTS = Object.freeze({
/**
* Nauka hangs below Zvezda, pointing at the Earth: from the port side of
* its lower end, looking out ahead of the station to port and down.
*/
nauka: mount([3.03, -12, -24.25], [0.75, -0.5, 0.43], [0, 1, 0]),
/**
* Zarya lies along the station's long axis, docked at both ends, so it
* looks out sideways: from its port side, out across the track and down.
*/
zarya: mount([3.38, 2.96, -22], [0.87, -0.5, 0], [0, 1, 0]),
/**
* Poisk stands on top of Zvezda, pointing away from the Earth: from the
* top of it, looking out behind the station to starboard, the limb across
* the middle of the frame.
*/
poisk: mount([-1.27, 12, -27.27], [-0.66, -0.34, -0.66], [0, 1, 0]),
/**
* A docked vehicle (a Progress, a Soyuz, a Dragon): the catalog does not
* say which port it is on, so it takes the place of one on Zvezda's aft
* port, the most used: looking out behind the station and down, the Earth
* falling away.
*/
docked: mount([0, 2.05, -41.5], [0, -0.5, -0.87], [0, 1, 0]),
/**
* The Cupola, on Tranquility's Earth-facing port: from just below it,
* looking aft along the station and down, the Russian segment (Zvezda,
* Nauka, the docked vehicles) in the corner and the Earth beyond.
*/
cupola: mount([8.3, -3.2, -4.9], [0, -0.5, -0.87], [0, 1, 0]),
/**
* Kibo, on Harmony's port side: its two windows are on its port end, above
* the airlock. From just outside them, looking out to port and down over
* the Exposed Facility, the Earth beyond it. The port solar arrays turn
* through this view as they follow the Sun, as they do past the windows.
*/
kibo: mount([15.4, 4.2, 11], [0.81, -0.5, -0.3], [0, 1, 0]),
});
/**
* The card a view shows in place of its catalog entry's, for a module the
* catalog has no entry for. Its texts are marked for translation; the name
* is the module's, as catalog names are.
*/
export const ISS_MOUNT_CARDS = Object.freeze({
cupola: Object.freeze({
name: 'CUPOLA',
classLabel: msg('OBSERVATION MODULE · ISS'),
operator: msg('European Space Agency (ESA)'),
facts: Object.freeze([
msg('7 WINDOWS'),
msg('LAUNCHED 8 FEB 2010 · STS-130'),
msg('TRANQUILITY · EARTH-FACING PORT'),
]),
}),
kibo: Object.freeze({
name: 'KIBO',
classLabel: msg('LABORATORY MODULE · ISS'),
operator: msg('Japan Aerospace Exploration Agency (JAXA)'),
facts: Object.freeze([
msg('2 WINDOWS'),
msg('LAUNCHED 31 MAY 2008 · STS-124'),
msg('HARMONY · PORT SIDE'),
]),
}),
});
/**
* The views in the order the Cockpit steps through them. The first is the
* one it opens on, whichever of the station's entries was selected.
*/
export const ISS_MOUNT_ORDER = Object.freeze([
'nauka',
'zarya',
'poisk',
'cupola',
'kibo',
'docked',
]);
/**
* The views the station offers now, in ISS_MOUNT_ORDER. Nauka, Zarya and
* Poisk are part of the model, so they are always there; the docked-vehicle
* view is offered only while a vehicle is docked, under that vehicle's name.
* Each view names the catalog entry it belongs to (the ISS itself for
* Zarya), so the Cockpit can ride that entry and its card describe it; null
* when the catalog has no entry for it. The Cupola and Kibo have none: they
* ride the ISS's and carry cards of their own (ISS_MOUNT_CARDS).
* @param {{naukaName?: string|null, zaryaName?: string|null,
* poiskName?: string|null, dockedName?: string|null,
* naukaNorad?: number|null, zaryaNorad?: number|null,
* poiskNorad?: number|null, dockedNorad?: number|null}} [entries]
* Catalog names (e.g. "ISS (NAUKA)") and numbers.
* @returns {Array<{key: 'nauka'|'zarya'|'poisk'|'cupola'|'kibo'|'docked',
* label: string, noradId: number|null, card: object|null}>}
*/
export function issMountViews({
naukaName,
zaryaName,
poiskName,
dockedName,
naukaNorad = null,
zaryaNorad = null,
poiskNorad = null,
dockedNorad = null,
} = {}) {
const labels = {
nauka: issMountLabel(naukaName) || 'NAUKA',
zarya: issMountLabel(zaryaName) || 'ZARYA',
poisk: issMountLabel(poiskName) || 'POISK',
cupola: ISS_MOUNT_CARDS.cupola.name,
kibo: ISS_MOUNT_CARDS.kibo.name,
docked: issMountLabel(dockedName),
};
const entries = {
nauka: naukaNorad,
zarya: zaryaNorad,
poisk: poiskNorad,
cupola: zaryaNorad,
kibo: zaryaNorad,
docked: dockedNorad,
};
return ISS_MOUNT_ORDER.filter((key) => labels[key]).map((key) => ({
key,
label: labels[key],
noradId: Number.isFinite(entries[key]) ? entries[key] : null,
card: ISS_MOUNT_CARDS[key] ?? null,
}));
}
/**
* The view to show: the one asked for while it is on offer, else the first.
* @param {Array<{key: string, label: string}>} views From issMountViews.
* @param {string|null|undefined} key
* @returns {{key: string, label: string}}
*/
export function issMountView(views, key) {
return views.find((view) => view.key === key) ?? views[0];
}
/**
* The view after the current one, wrapping round; null with fewer than two.
* @param {Array<{key: string, label: string}>} views
* @param {string|null|undefined} key The current view.
* @returns {{key: string, label: string}|null}
*/
export function issNextMountView(views, key) {
if (!Array.isArray(views) || views.length < 2) return null;
const index = views.findIndex((view) => view.key === key);
return views[(index + 1) % views.length];
}
/**
* The view before the current one, wrapping round; null with fewer than two.
* An unknown current view steps back to the last.
* @param {Array<{key: string, label: string}>} views
* @param {string|null|undefined} key The current view.
* @returns {{key: string, label: string}|null}
*/
export function issPreviousMountView(views, key) {
if (!Array.isArray(views) || views.length < 2) return null;
const index = views.findIndex((view) => view.key === key);
return views[(Math.max(index, 0) - 1 + views.length) % views.length];
}
/**
* The name the Cockpit shows for the view: the entry's own, without the
* "ISS (…)" the catalog wraps the station's modules in.
* @param {string|null|undefined} name Catalog name, e.g. "ISS (ZARYA)".
* @returns {string}
*/
export function issMountLabel(name) {
const text = String(name ?? '').trim();
const inner = /^ISS\s*\((.+)\)$/i.exec(text);
return (inner ? inner[1] : text).trim();
}
const add = (a, b, k) => [a[0] + b[0] * k, a[1] + b[1] * k, a[2] + b[2] * k];
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const unit = (v) => {
const length = Math.hypot(v[0], v[1], v[2]);
return [v[0] / length, v[1] / length, v[2] / length];
};
const cross = (a, b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
const point = (v) => ({ x: v[0], y: v[1], z: v[2] });
/**
* A mount in the world: the eye point and the view's frame, Earth-fixed.
* The model is placed with its forward axis along the flight direction, its
* port axis along the orbit normal and its zenith axis away from the Earth
* (issFlightAxes), so a model vector [port, zenith, forward] is
* port × axes.y + zenith × axes.z + forward × axes.x.
* @param {{eye: number[], forward: number[], up: number[]}} mount
* @param {{x: number, y: number, z: number}} centre The model's origin.
* @param {{x: number[], y: number[], z: number[]}} axes Flight axes.
* @returns {{position: object, direction: object, up: object, right: object}}
* `{x, y, z}` vectors; direction, up and right are unit and perpendicular,
* right = direction × up.
*/
export function issMountWorld(mount, centre, axes) {
const toWorld = ([port, zenith, forward]) =>
add(add(add([0, 0, 0], axes.y, port), axes.z, zenith), axes.x, forward);
const direction = unit(toWorld(mount.forward));
// Up, squared to the direction: the mount's own need not be exact.
const rough = toWorld(mount.up);
const up = unit(add(rough, direction, -dot(rough, direction)));
const offset = toWorld(mount.eye);
return {
position: {
x: centre.x + offset[0],
y: centre.y + offset[1],
z: centre.z + offset[2],
},
direction: point(direction),
up: point(up),
right: point(cross(direction, up)),
};
}
+183
View File
@@ -0,0 +1,183 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
ISS_MOUNTS,
ISS_MOUNT_CARDS,
ISS_MOUNT_ORDER,
ISS_NAUKA_NORAD,
ISS_POISK_NORAD,
issMountLabel,
issMountView,
issMountViews,
issMountWorld,
issNextMountView,
issPreviousMountView,
} from './issMounts.js';
import { ISS_MODEL_NATIVE_SPAN, ISS_NORAD } from './policy.js';
const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const length = (a) => Math.hypot(a.x, a.y, a.z);
/** Key, label and entry of each view: what the Cockpit steps through. */
const summary = (views) =>
views.map(({ key, label, noradId }) => ({ key, label, noradId }));
test('the station offers its views in order, Nauka first', () => {
assert.deepEqual(
[...ISS_MOUNT_ORDER],
['nauka', 'zarya', 'poisk', 'cupola', 'kibo', 'docked'],
);
for (const key of ISS_MOUNT_ORDER) assert.ok(ISS_MOUNTS[key]);
assert.equal(new Set([ISS_NORAD, ISS_NAUKA_NORAD, ISS_POISK_NORAD]).size, 3);
// Each view names the entry it belongs to, for the Cockpit to ride. The
// Cupola and Kibo have no entries of their own: they ride the ISS's.
const views = issMountViews({
naukaName: 'ISS (NAUKA)',
zaryaName: 'ISS (ZARYA)',
poiskName: 'POISK',
dockedName: 'PROGRESS-MS 34',
naukaNorad: ISS_NAUKA_NORAD,
zaryaNorad: ISS_NORAD,
poiskNorad: ISS_POISK_NORAD,
dockedNorad: 68837,
});
assert.deepEqual(summary(views), [
{ key: 'nauka', label: 'NAUKA', noradId: ISS_NAUKA_NORAD },
{ key: 'zarya', label: 'ZARYA', noradId: ISS_NORAD },
{ key: 'poisk', label: 'POISK', noradId: ISS_POISK_NORAD },
{ key: 'cupola', label: 'CUPOLA', noradId: ISS_NORAD },
{ key: 'kibo', label: 'KIBO', noradId: ISS_NORAD },
{ key: 'docked', label: 'PROGRESS-MS 34', noradId: 68837 },
]);
// Only the modules without an entry carry cards of their own.
assert.deepEqual(
views.filter((view) => view.card).map((view) => view.key),
['cupola', 'kibo'],
);
// No vehicle docked: no view from one. The modules are part of the model,
// so they are offered even when the catalog has no entry for them; such a
// view has no entry to ride.
assert.deepEqual(summary(issMountViews({ zaryaName: 'ISS (ZARYA)' })), [
{ key: 'nauka', label: 'NAUKA', noradId: null },
{ key: 'zarya', label: 'ZARYA', noradId: null },
{ key: 'poisk', label: 'POISK', noradId: null },
{ key: 'cupola', label: 'CUPOLA', noradId: null },
{ key: 'kibo', label: 'KIBO', noradId: null },
]);
assert.deepEqual(
issMountViews().map(({ key }) => key),
['nauka', 'zarya', 'poisk', 'cupola', 'kibo'],
);
});
test('the Cupola’s card names it and gives its facts, marked for translation', () => {
const card = ISS_MOUNT_CARDS.cupola;
assert.equal(card.name, 'CUPOLA');
assert.equal(card.classLabel, 'OBSERVATION MODULE · ISS');
assert.equal(card.operator, 'European Space Agency (ESA)');
assert.deepEqual(
[...card.facts],
[
'7 WINDOWS',
'LAUNCHED 8 FEB 2010 · STS-130',
'TRANQUILITY · EARTH-FACING PORT',
],
);
});
test('Kibo’s card names it and gives its facts, marked for translation', () => {
const card = ISS_MOUNT_CARDS.kibo;
assert.equal(card.name, 'KIBO');
assert.equal(card.classLabel, 'LABORATORY MODULE · ISS');
assert.equal(card.operator, 'Japan Aerospace Exploration Agency (JAXA)');
assert.deepEqual(
[...card.facts],
['2 WINDOWS', 'LAUNCHED 31 MAY 2008 · STS-124', 'HARMONY · PORT SIDE'],
);
});
test('the view shown is the one asked for, else the first; the next wraps round', () => {
const views = issMountViews({ dockedName: 'SOYUZ-MS 28' });
assert.equal(issMountView(views, null).key, 'nauka');
assert.equal(issMountView(views, undefined).key, 'nauka');
assert.equal(issMountView(views, 'zarya').key, 'zarya');
assert.equal(issMountView(views, 'docked').label, 'SOYUZ-MS 28');
// A view no longer on offer (the vehicle undocked) falls back to the first.
assert.equal(issMountView(issMountViews(), 'docked').key, 'nauka');
assert.equal(issNextMountView(views, 'nauka').key, 'zarya');
assert.equal(issNextMountView(views, 'zarya').key, 'poisk');
assert.equal(issNextMountView(views, 'poisk').key, 'cupola');
assert.equal(issNextMountView(views, 'cupola').key, 'kibo');
assert.equal(issNextMountView(views, 'kibo').key, 'docked');
assert.equal(issNextMountView(views, 'docked').key, 'nauka');
assert.equal(issNextMountView(views, 'unknown').key, 'nauka');
assert.equal(issNextMountView(views.slice(0, 1), 'nauka'), null);
assert.equal(issNextMountView(null, 'nauka'), null);
assert.equal(issPreviousMountView(views, 'nauka').key, 'docked');
assert.equal(issPreviousMountView(views, 'docked').key, 'kibo');
assert.equal(issPreviousMountView(views, 'zarya').key, 'nauka');
assert.equal(issPreviousMountView(views, 'unknown').key, 'docked');
assert.equal(issPreviousMountView(views.slice(0, 1), 'nauka'), null);
assert.equal(issPreviousMountView(null, 'nauka'), null);
});
test('the view is named after the entry, without the catalog’s "ISS (…)"', () => {
assert.equal(issMountLabel('ISS (ZARYA)'), 'ZARYA');
assert.equal(issMountLabel(' ISS (NAUKA) '), 'NAUKA');
assert.equal(issMountLabel('PROGRESS-MS 34'), 'PROGRESS-MS 34');
assert.equal(issMountLabel(null), '');
});
test('every mount is on or beside the model, with a usable view frame', () => {
for (const [key, { eye, forward, up }] of Object.entries(ISS_MOUNTS)) {
// Within the station's own size of its centre: on it or just off its end.
assert.ok(Math.hypot(...eye) < ISS_MODEL_NATIVE_SPAN / 2, key);
assert.ok(Math.hypot(...forward) > 0.5, key);
// Up is not along the view, so the frame can be squared.
const cos =
(forward[0] * up[0] + forward[1] * up[1] + forward[2] * up[2]) /
(Math.hypot(...forward) * Math.hypot(...up));
assert.ok(Math.abs(cos) < 0.9, key);
}
});
test('a mount goes to the world on the axes the model is placed with', () => {
// Flight axes: x along-track, y the orbit normal, z zenith.
const axes = { x: [0, 1, 0], y: [0, 0, 1], z: [1, 0, 0] };
const centre = { x: 6_800_000, y: 0, z: 0 };
// Model axes are [port, zenith, forward]: forward is along-track, zenith
// is away from the Earth, port is the orbit normal.
const world = issMountWorld(
{ eye: [3, 5, -7], forward: [0, 0, 1], up: [0, 1, 0] },
centre,
axes,
);
assert.deepEqual(world.position, { x: 6_800_005, y: -7, z: 3 });
assert.deepEqual(world.direction, { x: 0, y: 1, z: 0 });
assert.deepEqual(world.up, { x: 1, y: 0, z: 0 });
// right = direction × up.
assert.deepEqual(world.right, { x: 0, y: 0, z: -1 });
});
test('the view frame is unit and square whatever the mount says', () => {
const axes = { x: [0, 1, 0], y: [0, 0, 1], z: [1, 0, 0] };
const centre = { x: 1, y: 2, z: 3 };
for (const mount of [
...Object.values(ISS_MOUNTS),
// Lengths off, and an up that leans into the view.
{ eye: [0, 0, 0], forward: [0, -3, 4], up: [0, 2, 1] },
]) {
const { direction, up, right } = issMountWorld(mount, centre, axes);
for (const v of [direction, up, right])
assert.ok(Math.abs(length(v) - 1) < 1e-12);
assert.ok(Math.abs(dot(direction, up)) < 1e-12);
assert.ok(Math.abs(dot(direction, right)) < 1e-12);
assert.ok(Math.abs(dot(up, right)) < 1e-12);
}
// The eye is the mount's distance from the centre.
const { position } = issMountWorld(ISS_MOUNTS.docked, centre, axes);
const offset = Math.hypot(position.x - 1, position.y - 2, position.z - 3);
assert.ok(Math.abs(offset - Math.hypot(...ISS_MOUNTS.docked.eye)) < 1e-9);
});
+227
View File
@@ -0,0 +1,227 @@
import { msg } from '../../i18n/index.js';
import { ISS_ARM_JOINTS } from './issArticulation.js';
import { issCommandFastOrbit } from './issCommand.js';
import { ISS_NORAD } from './policy.js';
import { trackedStation } from './stationModels.js';
const unit = (v) => {
const n = Math.hypot(...v);
return v.map((c) => c / n);
};
/**
* The Sun positions Manual offers, on the model's axes (port, zenith,
* forward), and whether the station is lit there.
*/
export const ISS_SUN_POSES = Object.freeze([
{ id: 'overhead', label: msg('Overhead'), sun: [0, 1, 0], sunlit: true },
{ id: 'ahead', label: msg('Ahead'), sun: unit([0, 0.05, 1]), sunlit: true },
{
id: 'behind',
label: msg('Behind'),
sun: unit([0, 0.05, -1]),
sunlit: true,
},
{
id: 'below',
label: msg('Underneath'),
sun: unit([0, -1, 0.05]),
sunlit: true,
},
{
id: 'port',
label: msg('Port side'),
sun: unit([0.8, 0.5, 0.3]),
sunlit: true,
},
{
id: 'starboard',
label: msg('Starboard side'),
sun: unit([-0.8, 0.5, 0.3]),
sunlit: true,
},
{ id: 'night', label: msg('Night (shadow)'), sun: [0, -1, 0], sunlit: false },
]);
/** A seven-joint arm's slider labels, base to tip (Tiangong's arms share them). */
export const ISS_ARM_LABELS = Object.freeze([
msg('Shoulder roll'),
msg('Shoulder yaw'),
msg('Shoulder pitch'),
msg('Elbow'),
msg('Wrist pitch'),
msg('Wrist yaw'),
msg('Wrist roll'),
]);
/**
* The ISS as the STATION section describes it (stationPanel.js): its joint
* driver and telemetry from the model part, and the Manual controls the
* command panel offered: the Sun's position or a fast orbit, folding the
* arrays and radiators as a demonstration, aiming the dishes, posing
* Canadarm2 by joint.
* @param {{state: object, parts: object}} context
* @returns {import('./stationPanel.js').StationDescription}
*/
export function issStationDescription({ state: layerState, parts }) {
return {
key: 'iss',
title: 'ISS', // i18n-ignore: the station's name
// stationModels.js says which station the tracked entry belongs to.
selected: () => trackedStation(layerState, parts)?.norad === ISS_NORAD,
subjectName: () =>
layerState._catalog.get(layerState._trackedNorad)?.name?.trim() ||
`ISS · NORAD ${ISS_NORAD}`,
articulation: () => parts.issModel?._articulation ?? null,
telemetry: () => {
// The feed is read only while the model is drawn; away from it there
// is no signal to report, and a stale answer would read as lost.
if ((parts.issModel?._visualPosition?.() ?? null) === null)
return { state: 'idle', poseAgeMs: null, liveUntilMs: null };
return parts.issModel?._telemetryStatus?.() ?? null;
},
// The model's centre, else this frame's tracked sample, else the dot as
// the rendering part draws it.
position: () =>
parts.issModel?._visualPosition?.() ??
layerState._trackedFrameCartesian ??
parts.rendering?._pointPosition?.(ISS_NORAD) ??
null,
zoomLabel: msg('Zoom to the ISS'),
notes: {
live: msg(
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.",
),
computed: msg(
'Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.',
),
},
groups: [
{
id: 'sun',
label: msg('Sun position'),
kind: 'choices',
choices: [
{
id: 'follow',
label: msg('Follow the Sun'),
isDefault: true,
apply: (a) => a.setOverride(null),
},
...ISS_SUN_POSES.map(({ id, label, sun, sunlit }) => ({
id,
label,
apply: (a) => {
const fixed = { sun, sunlit };
a.setOverride(() => fixed);
},
})),
{
id: 'orbit',
label: msg('Fast orbit (40 s)'),
apply: (a) => {
const start = Date.now();
a.setOverride((nowMs) => issCommandFastOrbit(nowMs - start));
},
},
],
},
{
id: 'arrays',
label: msg('Solar arrays'),
note: msg('Demonstration: the real arrays stay extended.'),
kind: 'choices',
choices: [
{
id: 'retract',
label: msg('Retract'),
apply: (a) => a.setDeploy(false),
},
{
id: 'extend',
label: msg('Extend'),
isDefault: true,
apply: (a) => a.setDeploy(true),
},
],
},
{
id: 'radiators',
label: msg('Radiators'),
note: msg(
'Demonstration: the real radiators can fold but stay extended.',
),
kind: 'choices',
choices: [
{
id: 'retract',
label: msg('Retract'),
apply: (a) => a.setRadiatorDeploy(false),
},
{
id: 'extend',
label: msg('Extend'),
isDefault: true,
apply: (a) => a.setRadiatorDeploy(true),
},
],
},
{
id: 'dishes',
label: msg('Dishes'),
kind: 'choices',
choices: [
{
id: 'relays',
label: msg('Relay satellites'),
isDefault: true,
apply: (a) => a.setDishOverride(null),
},
{
id: 'up',
label: msg('Up'),
apply: (a) => a.setDishOverride([0, 1, 0]),
},
{
id: 'forward',
label: msg('Forward'),
apply: (a) => a.setDishOverride(unit([0, 0.35, 0.94])),
},
{
id: 'sideways',
label: msg('Sideways'),
apply: (a) => a.setDishOverride(unit([0.94, 0.35, 0])),
},
],
},
{
id: 'arm',
label: msg('Canadarm2 (degrees)'),
kind: 'sliders',
resume: msg('Resume sway'),
sliders: ISS_ARM_JOINTS.map((joint, i) => ({
id: joint.node,
label: ISS_ARM_LABELS[i],
min: -120,
max: 120,
apply: (a, value) =>
a.setJoint(
joint.node,
joint.pivot,
joint.axis,
(value * Math.PI) / 180,
),
})),
resumeApply: (a) => a.resumeArm(),
},
],
automatic: (a) => {
a.setTelemetryAllowed?.(true);
a.setOverride(null);
a.setDishOverride(null);
a.setDeploy(true);
a.setRadiatorDeploy(true);
a.resumeArm();
},
};
}
+301
View File
@@ -0,0 +1,301 @@
/**
* The ISS model's joints from NASA's public telemetry, when the server relays
* it (`/api/iss-telemetry`, off unless the operator sets
* `ISS_TELEMETRY_ENABLED=1`). Without it, or while the station has no signal,
* the joints keep the computed rules in issArticulation.js.
*
* How each telemetry angle maps onto a model joint was fitted against a
* recording of the feed, using the station's own attitude and position from
* the same feed:
* - the dish's two angles give a direction that stayed within 0.3° of a TDRS
* relay satellite across a hand-over between two of them;
* - the alpha joints' sign and zero put the arrays' masts square to the Sun;
* - each beta joint's sign is the one that turns its cell side toward the Sun
* (the other sign faces it about 45° away). The arrays then sat 5° to 9°
* off the Sun, which is where the real station held them.
* The radiator joints did not move during the recording, so their sign is the
* better of the two candidates on a parked joint, not a fit.
*/
/** The route the server relays the feed at. */
export const ISS_TELEMETRY_URL = '/api/iss-telemetry';
const DEG = Math.PI / 180;
/** Alpha joints (SARJ), in ISS_ALPHA_JOINTS order: port, starboard. */
export const ISS_TELEMETRY_ALPHA = Object.freeze([
Object.freeze({ item: 'S0000004', sign: 1 }),
Object.freeze({ item: 'S0000003', sign: -1 }),
]);
/**
* Beta joints (BGA), in ISS_BETA_JOINTS order: 2A, 4A, 2B, 4B, 1A, 3A, 1B,
* 3B. The model's angle is `sign × telemetry + 90°`: at 0° or 180° an array
* stands square to the truss, which is the model's ±90°.
*/
export const ISS_TELEMETRY_BETA = Object.freeze([
Object.freeze({ item: 'P4000007', sign: 1 }),
Object.freeze({ item: 'P4000008', sign: -1 }),
Object.freeze({ item: 'P6000008', sign: -1 }),
Object.freeze({ item: 'P6000007', sign: 1 }),
Object.freeze({ item: 'S4000007', sign: -1 }),
Object.freeze({ item: 'S4000008', sign: 1 }),
Object.freeze({ item: 'S6000008', sign: 1 }),
Object.freeze({ item: 'S6000007', sign: -1 }),
]);
/** Radiator joints (TRRJ), in ISS_RADIATOR_JOINTS order: port, starboard. */
export const ISS_TELEMETRY_GAMMA = Object.freeze([
Object.freeze({ item: 'S0000002', sign: 1 }),
Object.freeze({ item: 'S0000001', sign: 1 }),
]);
/** The Ku-band dish: elevation and cross-elevation. */
export const ISS_TELEMETRY_DISH = Object.freeze({
elevation: 'Z1000014',
crossElevation: 'Z1000015',
});
/**
* Where the dish points, on the model's axes (port, zenith, forward), from
* its two gimbal angles: zenith at rest, cross-elevation leans it to port,
* elevation then tips it aft.
* @param {number} elevationDeg
* @param {number} crossElevationDeg
* @returns {number[]} Unit vector.
*/
export function issTelemetryDishDirection(elevationDeg, crossElevationDeg) {
const el = elevationDeg * DEG;
const xel = crossElevationDeg * DEG;
return [
Math.sin(xel),
Math.cos(el) * Math.cos(xel),
-Math.sin(el) * Math.cos(xel),
];
}
/**
* The joint angles a telemetry snapshot gives, as the model turns them.
* @param {Record<string, [number, number|null]>|null|undefined} items The
* relay's `items`: each item's value and the time it was true at.
* @returns {{alpha: number[], beta: number[], gamma: number[],
* dish: number[]|null}|null} Radians, in the joint lists' order; null
* unless every array and radiator joint is present. `dish` is null when
* its angles are missing.
*/
export function issTelemetryPose(items) {
if (!items) return null;
const read = (item) => {
const value = items[item]?.[0];
return Number.isFinite(value) ? value : null;
};
const turn = (list, offsetDeg) =>
list.map(({ item, sign }) => {
const value = read(item);
return value === null ? null : (sign * value + offsetDeg) * DEG;
});
const alpha = turn(ISS_TELEMETRY_ALPHA, 0);
const beta = turn(ISS_TELEMETRY_BETA, 90);
const gamma = turn(ISS_TELEMETRY_GAMMA, 0);
if ([...alpha, ...beta, ...gamma].includes(null)) return null;
const el = read(ISS_TELEMETRY_DISH.elevation);
const xel = read(ISS_TELEMETRY_DISH.crossElevation);
return {
alpha,
beta,
gamma,
dish:
el === null || xel === null ? null : issTelemetryDishDirection(el, xel),
};
}
/** How often the relay is asked while the model is on screen. */
export const ISS_TELEMETRY_POLL_MS = 5_000;
/** A snapshot older than this is not used: the joints go back to their rules. */
export const ISS_TELEMETRY_FRESH_MS = 20_000;
/**
* The newest moment any of the relay's items was true at: when the feed
* last had data, as far as this answer tells.
* @param {Record<string, [number, number]>|null|undefined} items
* @returns {number|null} Epoch ms, or null without a dated item.
*/
export function issTelemetryLatestEpoch(items) {
let latest = null;
for (const entry of Object.values(items ?? {})) {
const epoch = Array.isArray(entry) ? Number(entry[1]) : NaN;
// An item with no time has 0 there, which is no date.
if (
epoch > 0 &&
Number.isFinite(epoch) &&
(latest === null || epoch > latest)
)
latest = epoch;
}
return latest;
}
/** The feed stops asking this long after the model was last drawn. */
const WANTED_MS = 10_000;
const REQUEST_TIMEOUT_MS = 5_000;
/** After a failed request the next one waits this long. */
const FAILURE_WAIT_MS = 30_000;
/**
* Polls the relay while the model is drawn. `touch()` each frame the model
* shows keeps it asking; it stops by itself when the touches stop, and for
* good once the server says the relay is not switched on.
* @param {{fetchImpl?: typeof fetch, now?: () => number,
* setTimer?: (fn: () => void, ms: number) => unknown,
* clearTimer?: (id: unknown) => void}} [options]
*/
export function createIssTelemetryFeed({
fetchImpl = (...args) => globalThis.fetch(...args),
now = Date.now,
setTimer = (fn, ms) => setTimeout(fn, ms),
clearTimer = (id) => clearTimeout(id),
} = {}) {
/** False once the server answered that the relay is off. */
let configured = null;
let lastTouchAt = null;
let timer = null;
let requesting = false;
/** Bumped by destroy, so a request in flight cannot write after it. */
let generation = 0;
let pose = null;
let poseAt = null;
/** What the relay last said and when, for the station panel's status line. */
let relayStatus = null;
let answeredAt = null;
let failures = 0;
/** When the relay last reported signal; the "no signal since" time. */
let liveUntil = null;
async function request() {
const mine = generation;
requesting = true;
const controller = new AbortController();
const deadline = setTimer(() => controller.abort(), REQUEST_TIMEOUT_MS);
let wait = ISS_TELEMETRY_POLL_MS;
try {
const response = await fetchImpl(ISS_TELEMETRY_URL, {
signal: controller.signal,
cache: 'no-store',
});
if (!response.ok) throw new Error('unavailable');
const body = await response.json();
if (mine !== generation) return;
if (body?.configured !== true) {
configured = false;
pose = null;
return;
}
configured = true;
answeredAt = now();
failures = 0;
relayStatus = typeof body.status === 'string' ? body.status : null;
const next = body.status === 'live' ? issTelemetryPose(body.items) : null;
pose = next;
poseAt = next ? now() : null;
if (next) liveUntil = poseAt;
// A page that opens during a loss of signal still learns when the
// feed last had data: the newest value the relay holds was true then.
else if (body.status === 'no-signal' && liveUntil === null)
liveUntil = issTelemetryLatestEpoch(body.items);
} catch {
if (mine !== generation) return;
failures += 1;
wait = FAILURE_WAIT_MS;
} finally {
clearTimer(deadline);
if (mine === generation) {
requesting = false;
schedule(wait);
}
}
}
function wanted() {
return (
configured !== false &&
lastTouchAt !== null &&
now() - lastTouchAt < WANTED_MS
);
}
function schedule(ms) {
if (timer !== null || requesting || !wanted()) return;
timer = setTimer(() => {
timer = null;
if (wanted()) request();
}, ms);
}
return {
/** The model is on screen: keep the feed asking. */
touch() {
lastTouchAt = now();
schedule(0);
},
/**
* The joint angles to use now, or null: no relay, no signal, or the last
* answer is too old.
* @returns {{alpha: number[], beta: number[], gamma: number[],
* dish: number[]|null}|null}
*/
pose() {
if (!pose || poseAt === null) return null;
return now() - poseAt < ISS_TELEMETRY_FRESH_MS ? pose : null;
},
/** Whether the server relays the feed: null until it has answered. */
configured() {
return configured;
},
/**
* Where the joints' angles stand, for the station panel: `live` with a
* fresh pose; `no-signal` while the relay is up but the station is out
* of contact; `unavailable` when the relay cannot be reached or is not
* connected; `disabled` when this server does not relay the feed;
* `pending` before the first answer. `poseAgeMs` is how old the last
* pose is, `liveUntilMs` when signal was last had (epoch ms), both null
* when there was none.
* @returns {{state: 'live'|'no-signal'|'unavailable'|'disabled'|'pending',
* poseAgeMs: number|null, liveUntilMs: number|null}}
*/
status() {
const at = now();
const poseAgeMs = poseAt === null ? null : at - poseAt;
let state;
if (configured === false) state = 'disabled';
// Never answered: still asking, or the route is not there (a 404, an
// HTML fallback page), which is unavailable rather than pending.
else if (configured === null)
state = failures > 0 ? 'unavailable' : 'pending';
else if (pose && poseAgeMs < ISS_TELEMETRY_FRESH_MS) state = 'live';
else if (failures === 0 && relayStatus === 'no-signal')
state = 'no-signal';
else if (
failures === 0 &&
(relayStatus === 'connecting' || relayStatus === 'reconnecting') &&
answeredAt !== null &&
at - answeredAt < ISS_TELEMETRY_FRESH_MS
)
state = 'pending';
else state = 'unavailable';
return { state, poseAgeMs, liveUntilMs: liveUntil };
},
destroy() {
generation += 1;
if (timer !== null) clearTimer(timer);
timer = null;
requesting = false;
lastTouchAt = null;
pose = null;
poseAt = null;
configured = null;
relayStatus = null;
answeredAt = null;
failures = 0;
liveUntil = null;
},
};
}
+511
View File
@@ -0,0 +1,511 @@
import assert from 'node:assert/strict';
import test, { after, before } from 'node:test';
import * as Cesium from 'cesium';
import {
ISS_ALPHA_JOINTS,
ISS_BETA_JOINTS,
ISS_DISH_JOINTS,
ISS_RADIATOR_JOINTS,
createIssArticulation,
} from './issArticulation.js';
import {
issTelemetryLatestEpoch,
ISS_TELEMETRY_ALPHA,
ISS_TELEMETRY_BETA,
ISS_TELEMETRY_FRESH_MS,
ISS_TELEMETRY_GAMMA,
ISS_TELEMETRY_POLL_MS,
ISS_TELEMETRY_URL,
createIssTelemetryFeed,
issTelemetryDishDirection,
issTelemetryPose,
} from './issTelemetry.js';
// The joint driver asks Cesium for the Earth's orientation, which loads data
// over the network; without it Cesium's own fallback is used, as in the app
// before that data arrives.
const realIcrf = Cesium.Transforms.computeIcrfToFixedMatrix;
before(() => {
Cesium.Transforms.computeIcrfToFixedMatrix = () => undefined;
});
after(() => {
Cesium.Transforms.computeIcrfToFixedMatrix = realIcrf;
});
const DEG = Math.PI / 180;
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const angleDeg = (a, b) =>
Math.acos(Math.min(1, Math.max(-1, dot(a, b)))) / DEG;
/**
* Two moments recorded from the feed on 13 November 2026, eleven minutes
* apart. `sun` and `relayDirection` are on the model's axes (port, zenith,
* forward), worked out from the station's own position and attitude in the
* same feed; the relay is the TDRS satellite the dish was aimed at.
*/
const RECORDED = [
{
items: {
S0000004: [306.2512, 0],
S0000003: [53.7878, 0],
P4000007: [161.5045, 0],
P4000008: [198.4406, 0],
P6000008: [202.9449, 0],
P6000007: [161.0541, 0],
S4000007: [18.7427, 0],
S4000008: [341.3068, 0],
S6000008: [341.7682, 0],
S6000007: [18.8361, 0],
S0000002: [15.1868, 0],
S0000001: [24.8383, 0],
Z1000014: [-8.4924, 0],
Z1000015: [-31.6077, 0],
},
sun: [0.45411, 0.5286, -0.7172],
relayDirection: [-0.5264, 0.84041, 0.12893],
},
{
items: {
S0000004: [262.0807, 0],
S0000003: [97.9968, 0],
P4000007: [161.8451, 0],
P4000008: [198.2867, 0],
P6000008: [202.8131, 0],
P6000007: [161.4166, 0],
S4000007: [18.6932, 0],
S4000008: [341.7902, 0],
S6000008: [341.6089, 0],
S6000007: [18.4076, 0],
S0000002: [15.1923, 0],
S0000001: [24.8383, 0],
Z1000014: [39.5837, 0],
Z1000015: [-30.1135, 0],
},
sun: [0.45807, -0.12024, -0.88075],
relayDirection: [-0.50436, 0.66714, -0.54822],
},
];
/**
* An array's cell-side normal on the model's axes: ±X at rest, turned about
* the mast (Z) by beta, then about the truss (X) by alpha.
*/
function cellNormal(face, alpha, beta) {
const x = face * Math.cos(beta);
const y = face * Math.sin(beta);
return [x, Math.cos(alpha) * y, Math.sin(alpha) * y];
}
test('the joint lists line up with the model joints they drive', () => {
assert.equal(ISS_TELEMETRY_ALPHA.length, ISS_ALPHA_JOINTS.length);
assert.equal(ISS_TELEMETRY_BETA.length, ISS_BETA_JOINTS.length);
assert.equal(ISS_TELEMETRY_GAMMA.length, ISS_RADIATOR_JOINTS.length);
const items = [
...ISS_TELEMETRY_ALPHA,
...ISS_TELEMETRY_BETA,
...ISS_TELEMETRY_GAMMA,
].map(({ item }) => item);
assert.equal(new Set(items).size, items.length, 'no item drives two joints');
});
test('recorded telemetry turns every array toward where the Sun was', () => {
for (const { items, sun } of RECORDED) {
const pose = issTelemetryPose(items);
ISS_BETA_JOINTS.forEach(({ node, face }, i) => {
const alpha = pose.alpha[node.startsWith('PORT') ? 0 : 1];
const off = angleDeg(cellNormal(face, alpha, pose.beta[i]), sun);
// The real arrays were held 5° to 9° off the Sun.
assert.ok(off < 11, `${node} is ${off.toFixed(1)}° off the Sun`);
});
}
});
test('the other sign on any joint turns its arrays away from the Sun', () => {
const { items, sun } = RECORDED[0];
const pose = issTelemetryPose(items);
ISS_BETA_JOINTS.forEach(({ node, face }, i) => {
const alpha = pose.alpha[node.startsWith('PORT') ? 0 : 1];
// Beta with the opposite sign about its 90° zero.
const flipped = Math.PI - pose.beta[i];
assert.ok(angleDeg(cellNormal(face, alpha, flipped), sun) > 35, node);
// Alpha with the opposite sign.
assert.ok(angleDeg(cellNormal(face, -alpha, pose.beta[i]), sun) > 35, node);
});
});
test('the recorded dish angles point at the relay satellite', () => {
for (const { items, relayDirection } of RECORDED) {
const { dish } = issTelemetryPose(items);
assert.ok(Math.abs(Math.hypot(...dish) - 1) < 1e-9);
assert.ok(angleDeg(dish, relayDirection) < 0.5);
}
// At rest it looks at the zenith; cross-elevation leans to port,
// elevation tips aft.
assert.ok(angleDeg(issTelemetryDishDirection(0, 0), [0, 1, 0]) < 1e-6);
assert.ok(issTelemetryDishDirection(0, 30)[0] > 0);
assert.ok(issTelemetryDishDirection(30, 0)[2] < 0);
});
test('a snapshot missing a joint gives no pose; missing dish angles give no dish', () => {
const { items } = RECORDED[0];
assert.equal(issTelemetryPose(null), null);
assert.equal(issTelemetryPose({}), null);
for (const item of ['S0000004', 'P6000007', 'S0000001']) {
const partial = { ...items };
delete partial[item];
assert.equal(issTelemetryPose(partial), null, item);
}
assert.equal(
issTelemetryPose({ ...items, S0000003: ['x', 0] }),
null,
'a value that is not a number',
);
const noDish = { ...items };
delete noDish.Z1000015;
const pose = issTelemetryPose(noDish);
assert.equal(pose.dish, null);
assert.equal(pose.beta.length, 8);
});
/** A hand-moved clock with the timers set on it. */
function fakeTime() {
const time = { ms: 1_000_000 };
let timers = [];
let nextId = 1;
return {
now: () => time.ms,
setTimer(fn, ms) {
const id = nextId++;
timers.push({ id, at: time.ms + ms, fn });
return id;
},
clearTimer(id) {
timers = timers.filter((timer) => timer.id !== id);
},
/** Move the clock on, running timers as they fall due. */
async advance(ms) {
const end = time.ms + ms;
for (;;) {
// Let a finished request schedule its next timer first.
await new Promise((resolve) => setImmediate(resolve));
const due = timers
.filter((timer) => timer.at <= end)
.sort((a, b) => a.at - b.at)[0];
if (!due) break;
timers = timers.filter((timer) => timer !== due);
time.ms = Math.max(time.ms, due.at);
due.fn();
}
time.ms = end;
await new Promise((resolve) => setImmediate(resolve));
},
};
}
/** A fetch that answers from a queue of bodies (or throws for an Error). */
function fakeFetch(answers) {
const calls = [];
const fetchImpl = async (url, init) => {
calls.push({ url, init });
const answer = answers.length > 1 ? answers.shift() : answers[0];
if (answer instanceof Error) throw answer;
return { ok: true, json: async () => answer };
};
return { fetchImpl, calls };
}
const LIVE = { configured: true, status: 'live', items: RECORDED[0].items };
test('the feed asks only while the model is drawn, every five seconds', async () => {
const time = fakeTime();
const { fetchImpl, calls } = fakeFetch([LIVE]);
const feed = createIssTelemetryFeed({ fetchImpl, ...time });
await time.advance(60_000);
assert.equal(calls.length, 0, 'nothing is asked before the model shows');
feed.touch();
await time.advance(0);
assert.equal(calls.length, 1);
assert.equal(calls[0].url, ISS_TELEMETRY_URL);
assert.equal(calls[0].init.cache, 'no-store');
assert.equal(feed.configured(), true);
assert.deepEqual(feed.pose(), issTelemetryPose(RECORDED[0].items));
// Drawn for another 12 s: two more requests.
for (let i = 0; i < 12; i++) {
feed.touch();
await time.advance(1000);
}
assert.equal(calls.length, 1 + Math.floor(12_000 / ISS_TELEMETRY_POLL_MS));
// Not drawn any more: it stops by itself, and the pose goes stale.
const drawn = calls.length;
await time.advance(60_000);
assert.ok(calls.length <= drawn + 2);
assert.equal(feed.pose(), null);
const settled = calls.length;
await time.advance(60_000);
assert.equal(calls.length, settled);
});
test('a relay that is switched off is asked once and never again', async () => {
const time = fakeTime();
const { fetchImpl, calls } = fakeFetch([{ configured: false }]);
const feed = createIssTelemetryFeed({ fetchImpl, ...time });
for (let i = 0; i < 30; i++) {
feed.touch();
await time.advance(1000);
}
assert.equal(calls.length, 1);
assert.equal(feed.configured(), false);
assert.equal(feed.pose(), null);
});
test('no signal, a failed request or an old answer all give no pose', async () => {
const time = fakeTime();
const { fetchImpl, calls } = fakeFetch([
LIVE,
{ configured: true, status: 'no-signal', items: RECORDED[0].items },
LIVE,
new Error('offline'),
]);
const feed = createIssTelemetryFeed({ fetchImpl, ...time });
const drawFor = async (ms) => {
for (let t = 0; t < ms; t += 1000) {
feed.touch();
await time.advance(1000);
}
};
await drawFor(1000);
assert.ok(feed.pose());
await drawFor(ISS_TELEMETRY_POLL_MS);
assert.equal(feed.pose(), null, 'no signal');
await drawFor(ISS_TELEMETRY_POLL_MS);
assert.ok(feed.pose(), 'signal back');
// Requests now fail: the last pose is used until it is 20 s old, and the
// feed asks less often.
const failingFrom = calls.length;
await drawFor(ISS_TELEMETRY_FRESH_MS - ISS_TELEMETRY_POLL_MS - 1000);
assert.ok(feed.pose());
await drawFor(ISS_TELEMETRY_POLL_MS + 2000);
assert.equal(feed.pose(), null, 'too old');
await drawFor(60_000);
assert.ok(calls.length - failingFrom <= 4, 'failures are retried slowly');
});
test('destroy stops the feed, even with a request in flight', async () => {
const time = fakeTime();
let release;
const calls = [];
const fetchImpl = (url) => {
calls.push(url);
return new Promise((resolve) => {
release = () => resolve({ ok: true, json: async () => LIVE });
});
};
const feed = createIssTelemetryFeed({ fetchImpl, ...time });
feed.touch();
await time.advance(0);
assert.equal(calls.length, 1);
feed.destroy();
release();
await time.advance(60_000);
assert.equal(feed.pose(), null);
assert.equal(calls.length, 1);
});
/**
* A stand-in for the loaded model: named nodes that keep a copy of the
* matrix written to them, as a Cesium node does.
*/
function fakeModel() {
const nodes = new Map();
return {
ready: true,
getNode(name) {
if (!nodes.has(name)) {
let copy = null;
nodes.set(name, {
name,
get matrix() {
return copy;
},
set matrix(value) {
copy = Array.from(value);
},
});
}
return nodes.get(name);
},
matrixOf(name) {
return nodes.get(name)?.matrix ?? null;
},
};
}
const AXES = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };
const POSITION = { x: 6_800_000, y: 0, z: 0 };
test('with a telemetry pose the joints take its angles, each side its own', () => {
const articulation = createIssArticulation();
const model = fakeModel();
const pose = issTelemetryPose(RECORDED[0].items);
articulation.setTelemetry(() => pose);
articulation.update(
model,
new Date(Date.UTC(2026, 10, 13, 11, 8)),
POSITION,
AXES,
1000,
);
assert.equal(articulation.isLive(), true);
// The alpha joints turn about X by the pose's angle: port and starboard differ.
ISS_ALPHA_JOINTS.forEach(({ node }, i) => {
const m = model.matrixOf(node);
assert.ok(Math.abs(m[5] - Math.cos(pose.alpha[i])) < 1e-9, node);
assert.ok(Math.abs(m[6] - Math.sin(pose.alpha[i])) < 1e-9, node);
});
assert.notDeepEqual(
model.matrixOf(ISS_ALPHA_JOINTS[0].node),
model.matrixOf(ISS_ALPHA_JOINTS[1].node),
);
ISS_BETA_JOINTS.forEach(({ node }, i) => {
const m = model.matrixOf(node);
assert.ok(Math.abs(m[0] - Math.cos(pose.beta[i])) < 1e-9, node);
assert.ok(Math.abs(m[1] - Math.sin(pose.beta[i])) < 1e-9, node);
});
ISS_RADIATOR_JOINTS.forEach(({ node }, i) => {
const m = model.matrixOf(node);
assert.ok(Math.abs(m[0] - Math.cos(pose.gamma[i])) < 1e-9, node);
});
// The first dish takes the reported aim (its rest boresight, +Y, turned
// onto it); the second is left where it was.
const dish = model.matrixOf(ISS_DISH_JOINTS[0].node);
assert.ok(angleDeg([dish[4], dish[5], dish[6]], pose.dish) < 1e-4);
const second = model.matrixOf(ISS_DISH_JOINTS[1].node);
assert.ok(angleDeg([second[4], second[5], second[6]], [0, 1, 0]) < 1e-4);
});
test('without a pose, or in Manual, the joints keep their computed rules', () => {
const date = new Date(Date.UTC(2026, 10, 13, 11, 8));
const computed = fakeModel();
createIssArticulation().update(computed, date, POSITION, AXES, 1000);
// Telemetry with nothing to say.
const silent = createIssArticulation();
silent.setTelemetry(() => null);
const silentModel = fakeModel();
silent.update(silentModel, date, POSITION, AXES, 1000);
assert.equal(silent.isLive(), false);
// Telemetry with a pose, but the command panel is on Manual.
const manual = createIssArticulation();
manual.setTelemetry(() => issTelemetryPose(RECORDED[0].items));
manual.setTelemetryAllowed(false);
const manualModel = fakeModel();
manual.update(manualModel, date, POSITION, AXES, 1000);
assert.equal(manual.isLive(), false);
// A Sun chosen by hand is computed too.
const forced = createIssArticulation();
forced.setTelemetry(() => issTelemetryPose(RECORDED[0].items));
forced.setOverride(() => ({ sun: [0, 1, 0], sunlit: true }));
forced.update(fakeModel(), date, POSITION, AXES, 1000);
assert.equal(forced.isLive(), false);
for (const { node } of [
...ISS_ALPHA_JOINTS,
...ISS_BETA_JOINTS,
...ISS_RADIATOR_JOINTS,
]) {
assert.deepEqual(silentModel.matrixOf(node), computed.matrixOf(node), node);
assert.deepEqual(manualModel.matrixOf(node), computed.matrixOf(node), node);
}
// Back to Automatic: the pose is used again, gliding at the joint rate.
manual.setTelemetryAllowed(true);
manual.update(manualModel, date, POSITION, AXES, 1100);
assert.equal(manual.isLive(), true);
});
test('a page that opens during a loss of signal learns when the feed last had data', async () => {
const time = fakeTime();
// The recording carries no times; date every item the same.
const dated = Object.fromEntries(
Object.entries(RECORDED[0].items).map(([key, [value]]) => [
key,
[value, 1_700_000_000_000],
]),
);
const noSignal = {
configured: true,
status: 'no-signal',
items: dated,
};
const { fetchImpl } = fakeFetch([noSignal, noSignal]);
const feed = createIssTelemetryFeed({ fetchImpl, ...time });
feed.touch();
await time.advance(1000);
const status = feed.status();
assert.equal(status.state, 'no-signal');
assert.equal(status.poseAgeMs, null);
const latest = issTelemetryLatestEpoch(dated);
assert.ok(Number.isFinite(latest) && latest > 0);
assert.equal(status.liveUntilMs, latest);
feed.destroy();
});
test('the latest epoch is the newest dated item, and nothing without one', () => {
assert.equal(
issTelemetryLatestEpoch({ a: [1, 100], b: [2, 300], c: [3, 200] }),
300,
);
assert.equal(issTelemetryLatestEpoch({ a: [1, 'x'], b: 5, c: [2, 0] }), null);
assert.equal(issTelemetryLatestEpoch({}), null);
assert.equal(issTelemetryLatestEpoch(null), null);
});
test('the status says where the angles stand: pending, live, disabled', async () => {
const time = fakeTime();
const { fetchImpl } = fakeFetch([LIVE]);
const feed = createIssTelemetryFeed({ fetchImpl, ...time });
assert.equal(feed.status().state, 'pending', 'before the first answer');
feed.touch();
await time.advance(0);
const live = feed.status();
assert.equal(live.state, 'live');
assert.ok(live.poseAgeMs >= 0 && live.poseAgeMs < ISS_TELEMETRY_FRESH_MS);
const off = fakeFetch([{ configured: false }]);
const offFeed = createIssTelemetryFeed({ fetchImpl: off.fetchImpl, ...time });
offFeed.touch();
await time.advance(0);
assert.equal(offFeed.status().state, 'disabled');
});
test('a relay route that is not there reads as unavailable, not as connecting forever', async () => {
const time = fakeTime();
// A 404, or a deploy's HTML fallback page: never a relay answer.
const answers = [
{ ok: false, status: 404, json: async () => ({}) },
{
ok: true,
json: async () => {
throw new SyntaxError('Unexpected token <');
},
},
];
let call = 0;
const fetchImpl = async () => answers[Math.min(call++, answers.length - 1)];
const feed = createIssTelemetryFeed({ fetchImpl, ...time });
feed.touch();
await time.advance(0);
assert.equal(feed.configured(), null, 'never answered');
assert.equal(feed.status().state, 'unavailable');
for (let i = 0; i < 30; i++) {
feed.touch();
await time.advance(1000);
}
assert.equal(feed.status().state, 'unavailable');
});
+8
View File
@@ -47,6 +47,8 @@ export function createLifecycle({
const frame = frameOf(viewer);
parts.catalog._abortActiveUpdates();
clearFocusTarget('satellites');
for (const model of parts.stationModels ?? [])
model._destroyStationModel();
layerState._viewer = viewer;
layerState._catalog = new Map();
layerState._points = new Map();
@@ -138,7 +140,10 @@ export function createLifecycle({
releaseContinuousRender('satellites');
parts.rendering._setPointsShown(false);
parts.rendering._setOrbitPathsShown(false);
for (const model of parts.stationModels ?? [])
model._updateStationModel(); // off: releases the model
parts.tracking._clearTracking();
parts.stationPanel?._syncStationPanel(); // off: takes the panel down
parts.labels._syncIssOverlay();
// Remove click handler + keydown listener + preRender propagation while disabled
layerState._clickSubscription?.();
@@ -178,6 +183,9 @@ export function createLifecycle({
}
layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID);
layerState._overlayHost.setVisible(ISS_OVERLAY_SOURCE_ID, false);
for (const model of parts.stationModels ?? [])
model._destroyStationModel();
parts.stationPanel?._destroyStationPanel();
// The dots', tracked dot's and rings' sets are disposed of
parts.rendering._detach(viewer);
layerState._points.clear();
+92
View File
@@ -321,6 +321,98 @@ test('the rendering part draws the dots, the tracked dot and the rings through t
}
});
test('a dot handed to a station model draws only beyond its range; the tracked dot too', () => {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
try {
const state = {
now: Date.now,
_points: new Map(),
_orbitPaths: new Map(),
_catalog: new Map(),
_viewer: viewer,
_trackedNorad: null,
_enabled: true,
_params: { showPoints: false, showOrbits: false },
};
const rendering = createRendering({
state,
services: {
focus: {
focusNowMs: (ms) => ms,
getFocusTarget: () => null,
focusPassIsNeeded: () => false,
},
},
parts: { tracking: { _getTrackedFramePosition: () => null } },
});
rendering._attach(viewer);
const points = draw.find('satellites:').spec.id;
const set = draw.set(points);
const range = [1.5e6, Number.MAX_VALUE];
let frame = 0;
const tick = () => rendering._preRenderTick({ frame: ++frame });
rendering._addPoint(25544, { x: 1, y: 2, z: 3 }, POINT_STYLES.iss);
tick();
assert.equal(set.items.get('25544').displayRange, undefined);
assert.equal(rendering._pointDisplayRange(25544), null);
// The range goes to the set with the frame, as the item's own copy.
assert.equal(rendering._setPointDisplayRange(25544, range), true);
assert.equal(rendering._setPointDisplayRange(1, range), false, 'no dot');
let writes = set.writes;
tick();
assert.equal(set.writes, writes + 1, 'sent with the frame');
assert.deepEqual(set.items.get('25544').displayRange, range);
assert.notEqual(set.items.get('25544').displayRange, range);
assert.deepEqual(rendering._pointDisplayRange(25544), range);
assert.equal(set.items.get('25544').show, true, 'shown, within its range');
// The same range again sends nothing (asked every frame).
writes = set.writes;
rendering._setPointDisplayRange(25544, [1.5e6, Number.MAX_VALUE]);
tick();
assert.equal(set.writes, writes);
// None again: every distance.
rendering._setPointDisplayRange(25544, null);
tick();
assert.equal(set.items.get('25544').displayRange, undefined);
assert.equal(rendering._pointDisplayRange(25544), null);
// A dot added again (a catalog rebuild) arrives with no range.
rendering._setPointDisplayRange(25544, range);
rendering._addPoint(25544, { x: 1, y: 2, z: 3 }, POINT_STYLES.iss);
tick();
assert.equal(set.items.get('25544').displayRange, undefined);
// The tracked dot: redrawn at once while drawn, fresh for each tracking.
const tracked = draw.set(points.replace(':points', ':tracked'));
state._trackedNorad = 25544;
assert.equal(rendering._trackedDotDisplayRange(), null, 'no tracked dot');
rendering._setTrackedDotDisplayRange(range); // nothing to put it on
rendering._addTrackedEntity({ position: () => ({ x: 1, y: 2, z: 3 }) });
assert.equal(rendering._trackedDotDisplayRange(), null);
tick();
assert.equal(tracked.items.get('25544').displayRange, undefined);
writes = tracked.writes;
rendering._setTrackedDotDisplayRange(range);
assert.equal(tracked.writes, writes + 1, 'redrawn at once');
assert.deepEqual(tracked.items.get('25544').displayRange, range);
assert.deepEqual(rendering._trackedDotDisplayRange(), range);
rendering._setTrackedDotDisplayRange([1.5e6, Number.MAX_VALUE]);
assert.equal(tracked.writes, writes + 1, 'the same range sends nothing');
rendering._setTrackedDotDisplayRange(null);
assert.equal(tracked.items.get('25544').displayRange, undefined);
assert.equal(rendering._trackedDotDisplayRange(), null);
rendering._setTrackedDotDisplayRange(range);
rendering._removeTrackedEntity();
assert.equal(rendering._trackedDotDisplayRange(), null);
rendering._addTrackedEntity({ position: () => ({ x: 1, y: 2, z: 3 }) });
tick();
assert.equal(tracked.items.get('25544').displayRange, undefined);
rendering._detach(viewer);
} finally {
unbind();
}
});
test('the orbit frame matrix turns ECEF about Z by minus the GMST elapsed', () => {
const rendering = createRendering({
state: {},
+150
View File
@@ -19,6 +19,156 @@ import { SATELLITE_CLASS_DISPLAY, SATELLITE_CLASS_IDS } from './classes.js';
export const ISS_NORAD = 25544;
/**
* Tiangong's catalog entry: CelesTrak lists the core module as "CSS (TIANHE)"
* and the labs as "CSS (WENTIAN)" and "CSS (MENGTIAN)" under entries of their
* own, with the docked Shenzhou and Tianzhou ships beside them.
*/
export const TIANGONG_NORAD = 48274;
/**
* Whether the tracked satellite is a station: the station's own entry, or an
* object docked to it (a module, a cargo ship…), which is the same body under
* a catalog entry of its own. A click on the station's dot lands on any of
* them.
* @param {number} stationNorad The station's entry (ISS_NORAD, TIANGONG_NORAD).
* @param {number|null|undefined} trackedNorad
* @param {{has(noradId: number): boolean}|null|undefined} dockedCompanions
* What shares the tracked satellite's position (`_dockedCompanions`).
* @returns {boolean}
*/
export function stationTrackedOn(stationNorad, trackedNorad, dockedCompanions) {
if (trackedNorad === stationNorad) return true;
return (
trackedNorad !== null &&
trackedNorad !== undefined &&
Boolean(dockedCompanions?.has(stationNorad))
);
}
/** `stationTrackedOn` for the ISS. */
export function issTrackedOnStation(trackedNorad, dockedCompanions) {
return stationTrackedOn(ISS_NORAD, trackedNorad, dockedCompanions);
}
/**
* The ISS drawn as a 3D model up close (issModel.js): NASA's "International
* Space Station (ISS) (D) (IGOAL)" from NASA 3D Resources, the station's
* current configuration (Nauka, Prichal, Bishop, the roll-out solar arrays),
* with NASA's own textures. The shipped file is that model reduced for the
* web and put in one frame, in meters (public/models/README.md says how).
*/
export const ISS_MODEL_URL = '/models/iss.glb';
/** The real station across its main truss, end to end, in meters. */
export const ISS_SPAN_M = 109;
/**
* The asset's span along its truss (glTF X, solar array to solar array) in
* its own units, read from the file's accessors. The file is in meters.
*/
export const ISS_MODEL_NATIVE_SPAN = 109;
/**
* The station's bounding-box centre in the file's coordinates, whose origin is
* NASA's (the middle of the S0 truss). The scene root is translated by minus
* this, so the model's origin is the station's centre. That is what
* minimumPixelSize scales about, so the enlarged far-range model stays
* centred on the orbital position (and on the tracked card's leader).
*/
export const ISS_MODEL_CENTER_NATIVE = Object.freeze([0, -7.38, 0.001]);
/**
* Which flight axis each of the model's local axes (Cesium's, after its glTF
* axis correction: local X = glTF Z, Y = glTF X, Z = glTF Y) points along.
* The file has the U.S. segment at +Z (forward), Kibo at +X (port) and the Z1
* truss at +Y (zenith; the Cupola faces -Y), so: local X → along-track, local
* Y → orbit normal, local Z → zenith.
*/
export const ISS_MODEL_LOCAL_AXES = Object.freeze(['x', 'y', 'z']);
/**
* Within this camera distance the model replaces the dot; farther out the dot
* stays. Covers the tracked view (~726 km back for LEO) with room to spare.
*/
export const ISS_MODEL_MAX_DISTANCE_M = 1_500_000;
/**
* The model is never drawn smaller than this, in pixels. At true size the
* station is under a pixel from the tracked view, so the floor is what makes
* it readable there; within a few kilometres the true size takes over.
*/
export const ISS_MODEL_MIN_PX = 72;
/**
* Objects within this distance of the ISS are docked to it (their element
* sets put them within a few hundred meters); while the model shows, their
* dots give way to it inside its range (issModel.js).
*/
export const ISS_COMPANION_RADIUS_M = 5_000;
/**
* Dots are moved at different moments, so with the clock sped up a docked
* object's dot can trail the ISS's by a long way. Only objects whose dots are
* within this distance are checked orbit against orbit (issModel.js).
*/
export const ISS_COMPANION_COARSE_M = 3_000_000;
/** How often the docked set is rescanned, ms. */
export const ISS_COMPANION_SCAN_MS = 1_000;
/**
* Within this camera distance of the ISS its orbit ring is hidden. The ring is
* drawn as ~230 km chords and turned with the Earth once a second, so up close
* it runs metres to kilometres off the model and jumps; at the tracked view
* (~726 km) and beyond it stays.
*/
export const ISS_ORBIT_HIDE_M = 50_000;
/**
* The tracked card keeps clear of the model: its gap from the anchor is this
* many meters of the station as drawn on screen (about its reach from its
* centre in an oblique view), so up close the card sits beside the station, not on it.
*/
export const ISS_CARD_CLEAR_M = 40;
/**
* Tiangong drawn as a 3D model up close (tiangongModel.js): the project's own
* model of the station's T configuration (Tianhe, Wentian, Mengtian, with a
* Shenzhou forward and nadir and a Tianzhou aft), built from primitives with
* procedural textures, in meters, same frame as the ISS file (glTF +X port,
* +Y zenith, +Z forward), the scene root at the station's bounding-box
* centre (public/models/README.md).
*/
export const TIANGONG_MODEL_URL = '/models/tiangong.glb';
/**
* The tracked card's clearance from Tiangong (ISS_CARD_CLEAR_M for the ISS):
* the station reaches ~29 m from its centre along the lab wings.
*/
export const TIANGONG_CARD_CLEAR_M = 30;
/**
* The stations the layer treats as one body with their docked entries
* (stationModels.js): `key` is the STATION description's and the LIVE
* section's (`station:<key>`); objects within `companionRadiusM` of the
* station, orbit against orbit, are docked to it. Each is also drawn as a 3D
* model up close (issModel.js, tiangongModel.js), but these rules hold
* whether or not a model part exists.
*/
export const STATIONS = Object.freeze([
Object.freeze({
key: 'iss',
norad: ISS_NORAD,
companionRadiusM: ISS_COMPANION_RADIUS_M,
}),
Object.freeze({
key: 'tiangong',
norad: TIANGONG_NORAD,
companionRadiusM: ISS_COMPANION_RADIUS_M,
}),
]);
export const ISS_OVERLAY_SOURCE_ID = 'satellites-iss';
export const ISS_OVERLAY_SOURCE_OPTIONS = Object.freeze({
+60 -1
View File
@@ -54,6 +54,13 @@ const RING_BEHIND_ALPHA = 0.35;
/** An RGBA colour with another alpha. */
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
/** Whether two display ranges are the same: both none, or the same bounds. */
const sameRange = (a, b) =>
a && b ? a[0] === b[0] && a[1] === b[1] : !a && !b;
/** A display range as the item's own copy, or undefined for none. */
const rangeOf = (range) => (range ? [range[0], range[1]] : undefined);
/** Layer instances so far: set ids unique to each. */
let instances = 0;
@@ -206,7 +213,7 @@ export function createRendering({
function _setOrbitPathShown(noradId, show) {
const path = layerState._orbitPaths.get(noradId);
if (!path) return;
if (!path || path.item.show === show) return;
path.item.show = show;
sets?.rings.upsert([path.item]);
}
@@ -258,6 +265,46 @@ export function createRendering({
if (trackedDot.drawn) sets?.tracked.upsert([trackedDot.item]);
}
/**
* Draw one satellite's dot only at eye distances in `range` (`[near, far)`,
* metres), or at every distance for null, apart from whether it is shown:
* a station's model stands in for its dot, and for the dots of the objects
* docked to it, within the model's range (stationModel.js). A dot added
* again (a catalog rebuild) arrives with no range.
* @param {number} noradId
* @param {readonly [number, number]|null} range
* @returns {boolean} Whether the satellite has a dot.
*/
function _setPointDisplayRange(noradId, range) {
const point = layerState._points.get(noradId);
if (!point) return false;
if (sameRange(point.displayRange, range)) return true;
point.displayRange = rangeOf(range);
_markDirty(noradId);
return true;
}
/** The eye distances a dot is drawn at, or null for every distance. */
function _pointDisplayRange(noradId) {
return layerState._points.get(noradId)?.displayRange ?? null;
}
/**
* The tracked satellite's dot likewise; a dot drawn is redrawn at once. A
* new tracked dot (tracking another satellite) arrives with no range.
* @param {readonly [number, number]|null} range
*/
function _setTrackedDotDisplayRange(range) {
if (!trackedDot || sameRange(trackedDot.item.displayRange, range)) return;
trackedDot.item.displayRange = rangeOf(range);
if (trackedDot.drawn) sets?.tracked.upsert([trackedDot.item]);
}
/** The eye distances the tracked dot is drawn at, or null for every distance. */
function _trackedDotDisplayRange() {
return trackedDot?.item.displayRange ?? null;
}
/** Remove every orbit ring. */
function _clearOrbitPaths() {
const ids = [...layerState._orbitPaths.values()].map(
@@ -666,6 +713,11 @@ export function createRendering({
function _tickAfterFrame() {
const now = focusNowMs(Date.now());
// The stations as 3D models up close. First, before the tracked sample
// below is refreshed: the follow camera and the tracked dot were placed
// this frame from the sample still cached, and a model must sit on it too.
for (const model of parts.stationModels ?? []) model._updateStationModel();
const interval = layerState._trackedNorad ? 200 : POSITION_UPDATE_MS;
// Space Missions keeps this layer enabled for TLE lookup while deliberately
// hiding its standalone fleet. Do not rebuild hidden point buffers on the
@@ -700,6 +752,9 @@ export function createRendering({
if (layerState._cockpitSubjectNorad !== null)
parts.cockpit?._syncCockpitSubjectVisuals();
// NASA's live video beside the card while the ISS is selected.
parts.stationPanel?._syncStationPanel();
_updatePointFocus(now);
// Hidden standalone orbit rings do not need turning while Space Missions
@@ -861,6 +916,10 @@ export function createRendering({
_setPointStyle,
_pointShown,
_setTrackedDotShown,
_setPointDisplayRange,
_pointDisplayRange,
_setTrackedDotDisplayRange,
_trackedDotDisplayRange,
_clearOrbitPaths,
_addPoint,
_movePoint,
+7
View File
@@ -80,6 +80,13 @@ export function createState({ services }) {
// Click-to-track state
state._trackedNorad = null;
/**
* The station the tracked satellite is docked to, by both orbits compared
* when tracking began (tracking.js): its NORAD number, or null.
*/
state._trackedDockedToStation = null;
/** Whether that station is the ISS, whose ring stands for the entry's. */
state._trackedDockedToIss = false;
state._pendingTrackingRestore = null;
+850
View File
@@ -0,0 +1,850 @@
import { eciToGeodetic, gstime, propagate } from 'satellite.js';
import { fromRadians } from '../../geo/ellipsoid.js';
import { headingPitchRollOfAxes } from '../../geo/frames.js';
import { copyInto, distance, vec } from '../../geo/vector.js';
import { canvasOf, drawOf, findCamera } from '../../render/rendererOf.js';
import { stationTrackedOn } from './policy.js';
/**
* A space station as a 3D model when the camera is close, driven by a
* description of the station (`StationModelSpec`): the ISS (issModel.js) and
* Tiangong (tiangongModel.js) are two instances of this one factory. Far out
* the dot stays: the model and the dot (ambient and tracked) split the
* distance range, so exactly one of them draws (the model by the display
* range on its draw item, the dots by the display range the rendering part
* puts on theirs). The model is one item of a `models` set on the
* renderer's draw port, asked for on first need and only if the station is
* shown, and posed every frame from its own SGP4 sample (the dot moves once
* a second, which at model range would show as a jump).
*
* The moving parts (the joint driver, `createArticulation`) write node
* matrices into this part's node poses, as they would into a model's nodes;
* those poses are the draw item's `nodes`, which the renderer applies to the
* model's named glTF nodes.
*
* @typedef {object} StationModelSpec
* @property {string} key Short id ('iss', 'tiangong'): the STATION
* description's key and the LIVE section's `station:<key>` subject key.
* @property {string} label The station's name, for log lines.
* @property {number} norad The catalog entry the model stands at.
* @property {string} modelUrl Asset path, resolved with `resolveAsset`.
* @property {number} scale The file's units to meters.
* @property {number} minPx The model is never drawn smaller than this.
* @property {number} maxDistanceM Within this camera distance the model
* replaces the dot.
* @property {number} orbitHideM Within this camera distance the station's
* orbit ring is hidden.
* @property {number} cardClearM How many meters of the station the tracked
* card keeps clear of.
* @property {number} companionRadiusM Objects within this of the station,
* orbit against orbit, are docked to it.
* @property {number} companionCoarseM Only dots within this are checked.
* @property {number} companionScanMs How often the docked set is rescanned.
* @property {readonly string[]} localAxes Which flight axis each of the
* model's local axes points along (see ISS_MODEL_LOCAL_AXES).
* @property {(noradId: number, entry: object|undefined) => boolean} isModule
* Whether a catalog entry at the station is one of its own modules (the
* ISS's Nauka, Tiangong's labs) rather than a visiting vehicle.
* @property {() => object} createArticulation The joint driver
* (`update(nodes, date, position, axes)`, `reset()`, and what the STATION
* section calls). `nodes` has a model's `ready` and `getNode(name)`, each
* node taking a `matrix`.
* @property {(() => {pose: () => object|null, touch: () => void,
* status: () => object, destroy: () => void})|null} createTelemetry A
* telemetry feed for the joints, or null for computed angles only.
* @property {((input: {key: string|null, centre: {x: number, y: number, z: number},
* axes: {x: number[], y: number[], z: number[]},
* name: (noradId: number|null) => string|null,
* entry: (noradId: number|null) => number|null,
* dockedVehicle: number|null}) => object|null)|null} cockpitMount The
* Cockpit camera's views on the model, or null when the station has none.
* @property {boolean} hideInCockpit Hide the model while the Cockpit rides
* the station: true where its camera would sit inside the hull, false
* where it rides a mount on the model.
* @property {(() => void)|null} syncOrbit Puts the station's ring back to
* its own rules on leaving the close-up; null for the layer's orbit toggle
* (a ring that exists only while the station is tracked).
* @property {number} [unloadAfterMs] How long the model may go undrawn (out
* of range, or hidden) before its draw set is released and its GPU memory
* with it; asked for again on the next approach. Default one minute.
* @property {number} [retryAfterMs] How long after a failed load the model
* is released and asked for again. Default 30 s.
*/
/** Default `unloadAfterMs`: a minute undrawn releases the model. */
export const STATION_MODEL_UNLOAD_AFTER_MS = 60_000;
/**
* A model that failed to load is released after this and asked for again
* on the next frame in range (the renderer retries a load only on an
* update, and a model that is not ready is not sent).
*/
export const STATION_MODEL_RETRY_AFTER_MS = 30_000;
/**
* Whether a station model may be drawn: the dot's own rules (layer on, points
* on, the station loaded and its class shown or the station tracked), and
* not while the Cockpit hides it.
* @param {{enabled: boolean, showPoints: boolean, hasStation: boolean,
* classVisible: boolean, tracked: boolean, cockpitHidden: boolean}} input
* @returns {boolean}
*/
export function stationModelShouldShow({
enabled,
showPoints,
hasStation,
classVisible,
tracked,
cockpitHidden,
}) {
return (
Boolean(enabled) &&
Boolean(showPoints) &&
Boolean(hasStation) &&
(Boolean(classVisible) || Boolean(tracked)) &&
!cockpitHidden
);
}
/**
* A station's flight axes in the Earth-fixed frame, from one SGP4 state: a
* station normally flies "+XVV", its modules along the velocity, the truss or
* labs across the orbit plane, the same side always to the Earth. Returned
* as the model's local axes: x along-track, y the orbit normal, z zenith
* (away from the Earth's centre).
* @param {{x:number,y:number,z:number}} positionEcef Earth-fixed position.
* @param {{x:number,y:number,z:number}} velocityEcefAxes Inertial velocity,
* turned onto the Earth-fixed axes (direction only matters).
* @returns {{x:number[], y:number[], z:number[]}|null} Unit vectors, or null
* for a degenerate state (zero position or velocity along it).
*/
export function stationFlightAxes(positionEcef, velocityEcefAxes) {
const r = [positionEcef.x, positionEcef.y, positionEcef.z];
const v = [velocityEcefAxes.x, velocityEcefAxes.y, velocityEcefAxes.z];
const z = unit(r);
const y = unit(cross(r, v));
if (!z || !y) return null;
const x = cross(y, z);
return { x, y, z };
}
/**
* Turn an inertial (TEME) vector onto the Earth-fixed axes at `gmst`: the same
* rotation `eciToGeodetic` applies to the position.
* @param {{x:number,y:number,z:number}} v
* @param {number} gmst Radians.
* @returns {{x:number,y:number,z:number}}
*/
export function temeToEcefAxes(v, gmst) {
const c = Math.cos(gmst);
const s = Math.sin(gmst);
return { x: c * v.x + s * v.y, y: -s * v.x + c * v.y, z: v.z };
}
/**
* The model's orientation for the renderer, `{heading, pitch, roll}` at
* `position`, from the station's flight axes and which of them each model
* axis points along (`localAxes`).
* @param {{x:number,y:number,z:number}} position Earth-fixed.
* @param {{x:number[], y:number[], z:number[]}} axes Flight axes.
* @param {readonly string[]} localAxes
* @returns {{heading: number, pitch: number, roll: number}}
*/
export function stationModelOrientation(position, axes, localAxes) {
const as = (key) => vec(axes[key][0], axes[key][1], axes[key][2]);
return headingPitchRollOfAxes(position, {
x: as(localAxes[0]),
y: as(localAxes[1]),
z: as(localAxes[2]),
});
}
/**
* Node poses as a joint driver writes them: `getNode(name)` hands a node
* whose `matrix` it sets (a column-major 4×4, copied on write, as a model's
* node copies), and `poses` keeps every matrix written, by node name: the
* draw item's `nodes` (`ModelItem.nodes`), one object for the item's life.
* @returns {{ready: boolean, getNode: (name: string) => {matrix: Float64Array},
* poses: Record<string, Float64Array>, clear: () => void}}
*/
export function createNodePoses() {
/** @type {Record<string, Float64Array>} */
const poses = {};
const nodes = new Map();
return {
ready: true,
poses,
getNode(name) {
let node = nodes.get(name);
if (!node) {
node = {
get matrix() {
return poses[name];
},
set matrix(value) {
// None: the node goes back to its authored pose (its name leaves
// the map), as a model's node does.
if (value === undefined || value === null) {
delete poses[name];
return;
}
const kept = (poses[name] ??= new Float64Array(16));
for (let i = 0; i < 16; i++) kept[i] = value[i];
},
};
nodes.set(name, node);
}
return node;
},
/** Every node back to its authored pose (its name leaves the map). */
clear() {
for (const name of Object.keys(poses)) delete poses[name];
},
};
}
function cross(a, b) {
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
}
function unit(a) {
const n = Math.hypot(a[0], a[1], a[2]);
if (!(n > 0)) return null;
return [a[0] / n, a[1] / n, a[2] / n];
}
/**
* One station's model part.
* @param {StationModelSpec} spec
* @param {{state: object, parts: object, resolveAsset?: (url: string) => string}} context
*/
export function createStationModel(
spec,
{ state: layerState, parts, resolveAsset },
) {
const { norad } = spec;
/** The `models` draw set the station is an item of, once asked for. */
let set = null;
let offReady = null;
let offFailed = null;
/** The station's draw item, sent again each frame it is posed. */
const itemId = `station:${spec.key}`;
let item = null;
/** Whether the renderer has the model loaded and posed. */
let ready = false;
let loading = false;
let failed = false;
/** When the renderer said the load failed (wall-clock ms), or null. */
let failedAt = null;
/** Turns the moving parts by where the Sun (and the relays) are. */
const articulation = spec.createArticulation();
/** Where the joint driver writes; kept for a renderer that poses nodes. */
const nodePoses = createNodePoses();
/**
* Telemetry for the same joints, where the station has any: asked for only
* while the model is drawn, and used in place of the computed angles
* whenever it has a pose.
*/
const telemetry = spec.createTelemetry?.() ?? null;
if (telemetry) articulation.setTelemetry?.(() => telemetry.pose());
/** The eye distances the model draws at. */
const nearRange = Object.freeze([0, spec.maxDistanceM]);
/** The eye distances the dots the model stands in for are drawn at. */
const farRange = Object.freeze([spec.maxDistanceM, Number.MAX_VALUE]);
/** Whether the station's own dot is left to the model within its range. */
let dotHanded = false;
/** Whether the tracked dot is, the tracked satellite being the station. */
let trackedDotHanded = false;
/**
* @type {Set<number>} Objects docked to the station, orbit against orbit,
* at the last scan: the same body as the model whether or not it draws.
*/
const dockedByOrbit = new Set();
/** @type {Set<number>} Docked objects whose dots the model stands in for. */
const handedCompanions = new Set();
/** Whether the model draws and the docked dots are left to it. */
let handingOver = false;
/** Wall-clock ms since when the model has not been drawn, or null. */
let undrawnSince = null;
let lastCompanionScanMs = Number.NEGATIVE_INFINITY;
/** Whether the station's orbit ring is hidden for the close-up. */
let orbitHidden = false;
/** The tracked docked object whose ring is hidden for the close-up, or null. */
let companionRingHidden = null;
const scratchPosition = vec();
const scratchMountCentre = vec();
/** The station centre the model last rendered at (for the tracked card). */
const visualPosition = vec();
let visualValid = false;
function _shouldShow() {
const tracked = layerState._trackedNorad === norad;
return stationModelShouldShow({
enabled: layerState._enabled,
showPoints: layerState._params.showPoints,
hasStation: layerState._catalog.has(norad),
classVisible: parts.controls._classVisible(norad),
tracked,
// With no mounts on the model the Cockpit camera would sit inside the
// hull, so the model goes while the Cockpit rides the station.
cockpitHidden:
spec.hideInCockpit &&
Boolean(parts.cockpit?._cockpitHeld?.()) &&
_trackedOnStation(),
});
}
/** The eye, from the camera port, or null without one. */
function _eye() {
return findCamera(layerState._viewer)?.pose?.()?.position ?? null;
}
/**
* Ask the renderer for the model: a `models` set of its own with the
* station as its one item, hidden until posed. On a renderer that draws
* no models the dot keeps drawing at every distance.
* @param {{x:number,y:number,z:number}} at Where the station is now.
*/
function _load(at) {
const draw = drawOf(layerState._viewer);
if (typeof draw?.models !== 'function') {
failed = true;
return;
}
loading = true;
set = draw.models({ id: `satellites:${itemId}`, show: true });
offReady = set.on('ready', (id) => {
if (id !== itemId) return;
ready = true;
loading = false;
failed = false;
});
offFailed = set.on('loadFailed', (id, message) => {
if (id !== itemId) return;
// The dots keep drawing at every distance (the model is never ready);
// after `retryAfterMs` the model is released and asked for again.
failed = true;
failedAt = Date.now();
loading = false;
console.warn(
`[Data:Satellites] ${spec.label} model failed to load:`,
message,
);
});
item = {
id: itemId,
pos: { x: at.x, y: at.y, z: at.z },
url: resolveAsset(spec.modelUrl),
orientation: { heading: 0, pitch: 0, roll: 0 },
scale: spec.scale,
minPixelSize: spec.minPx,
displayRange: nearRange,
// So a click on the model tracks the station, as a click on its dot does.
meta: { norad },
// The joint driver's poses, applied to the model's named nodes.
nodes: nodePoses.poses,
show: false,
};
set.upsert([item]);
}
/** Send the item as it stands. */
function _send() {
if (set && item) set.upsert([item]);
}
/** Hide the model (nothing sent when it is hidden already). */
function _hide() {
if (item && item.show) {
item.show = false;
_send();
}
}
/** An object's inertial position at `date`, km, or null. */
function _temeKm(satrec, date) {
if (!satrec) return null;
try {
const position = propagate(satrec, date)?.position;
return position && typeof position !== 'boolean' ? position : null;
} catch {
return null;
}
}
/**
* Whether the tracked satellite is the station itself: its own entry, or
* an object docked to it (a module, a cargo ship…), which has a catalog
* entry and a dot of its own but is the same body as the model. Read from
* the layer's docked set (dots sharing a position) and from this part's
* own scan (orbit against orbit), which stands whether or not the model
* draws: the answer must not depend on what it decides.
*/
function _trackedOnStation() {
const tracked = layerState._trackedNorad;
return (
stationTrackedOn(norad, tracked, layerState._dockedCompanions) ||
(tracked !== null && dockedByOrbit.has(tracked))
);
}
/**
* Leave the near range to the model: the station's dot, and the tracked
* dot while the tracked satellite is the station, draw only beyond it.
* Asked every frame (the calls cost nothing when nothing changes): a
* catalog rebuild or a change of tracked satellite brings new dots that
* arrive with no range, and a tracked satellite that leaves the station
* (a vehicle undocking) gets its tracked dot back.
*/
function _handOverDots() {
dotHanded = parts.rendering._setPointDisplayRange(norad, farRange);
const trackedHere = _trackedOnStation();
if (trackedHere) parts.rendering._setTrackedDotDisplayRange(farRange);
else if (trackedDotHanded) parts.rendering._setTrackedDotDisplayRange(null);
trackedDotHanded = trackedHere;
}
/** Give the station's dot and the tracked dot back at every distance. */
function _releaseDots() {
if (dotHanded) parts.rendering._setPointDisplayRange(norad, null);
dotHanded = false;
if (trackedDotHanded) parts.rendering._setTrackedDotDisplayRange(null);
trackedDotHanded = false;
}
/**
* Objects docked to the station (a module, a crew or cargo ship) have dots
* of their own at the station's position. Near the model they are part of
* it, and their dots, moved only a few times a second, jump across the
* model at 7.6 km/s. While the model shows, their dots draw only beyond its
* range too. Rescanned once a second: a vehicle that undocks gets its dot
* back, and a catalog rebuild's new dots are picked up.
* @param {number} nowMs
* @param {boolean} handOver Whether the docked dots are left to the model
* (it draws); otherwise the scan only keeps the docked set current.
*/
function _scanCompanions(nowMs, handOver) {
if (nowMs - lastCompanionScanMs < spec.companionScanMs) return;
lastCompanionScanMs = nowMs;
const stationPosition = parts.rendering._pointPosition(norad);
// The dots are placed at different moments (far apart with the clock sped
// up), so their spacing only rules out what is nowhere near. Whether an
// object is docked is read from both orbits at one instant.
const date = new Date(layerState.now());
const stationTeme = _temeKm(layerState._catalog.get(norad)?.satrec, date);
if (!stationPosition || !stationTeme) return;
for (const [noradId, point] of layerState._points) {
if (noradId === norad || !point?.pos) continue;
const entry = layerState._catalog.get(noradId);
if (entry?.group === 'dense') continue;
let docked = false;
if (distance(point.pos, stationPosition) <= spec.companionCoarseM) {
const teme = _temeKm(entry?.satrec, date);
docked =
Boolean(teme) &&
Math.hypot(
teme.x - stationTeme.x,
teme.y - stationTeme.y,
teme.z - stationTeme.z,
) *
1000 <=
spec.companionRadiusM;
}
if (docked) dockedByOrbit.add(noradId);
else dockedByOrbit.delete(noradId);
if (docked && handOver) {
parts.rendering._setPointDisplayRange(noradId, farRange); // no-op when equal
handedCompanions.add(noradId);
} else if (handedCompanions.has(noradId)) {
parts.rendering._setPointDisplayRange(noradId, null);
handedCompanions.delete(noradId);
}
}
for (const noradId of dockedByOrbit)
if (!layerState._points.has(noradId)) dockedByOrbit.delete(noradId);
}
/** Give docked objects their dots back at every distance. */
function _releaseCompanions() {
for (const noradId of handedCompanions)
parts.rendering._setPointDisplayRange(noradId, null);
handedCompanions.clear();
}
/** The station's ring back to its own rules (see `syncOrbit`). */
function _restoreOrbit() {
if (spec.syncOrbit) {
spec.syncOrbit();
return;
}
parts.rendering._setOrbitPathShown(
norad,
parts.controls.satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
),
);
}
/**
* Up close the orbit ring (polyline chords, turned once a second) runs off
* the model and jumps across it, so it is hidden there.
* @param {boolean} near Camera within `orbitHideM` of the station.
*/
function _syncOrbitCloseUp(near) {
if (near) {
// Kept hidden every frame: the ring may be built after this.
parts.rendering._setOrbitPathShown(norad, false);
orbitHidden = true;
} else if (orbitHidden) {
orbitHidden = false;
// Back to the ring's own rules, unless the Cockpit holds it hidden.
if (layerState._cockpitHiddenPath !== norad) _restoreOrbit();
}
// A tracked docked object draws a ring of its own through the model.
const tracked = layerState._trackedNorad;
const companion =
near && tracked !== norad && _trackedOnStation() ? tracked : null;
if (companionRingHidden !== null && companionRingHidden !== companion) {
// A tracked satellite's ring shows; untracking has already hidden it.
if (
tracked === companionRingHidden &&
layerState._cockpitHiddenPath !== companionRingHidden
)
parts.rendering._setOrbitPathShown(companionRingHidden, true);
companionRingHidden = null;
}
if (companion !== null) {
parts.rendering._setOrbitPathShown(companion, false);
companionRingHidden = companion;
}
}
/**
* Where the station is this frame, and how it is turned: its centre and
* its flight axes.
*
* The follow camera and the Cockpit camera sit on the tracked satellite's
* per-frame sample. While the tracked satellite is the station (its own
* entry, or an object docked to it, which has a sample of its own) the
* model sits on that same sample, or it would be drawn a frame of orbital
* motion (over 100 m) away from where the camera looks. Otherwise it is
* placed from the station's own orbit now.
* @param {{x:number,y:number,z:number}} result Receives the centre.
* @returns {{date: Date, axes: {x:number[], y:number[], z:number[]}}|null}
* Null when the orbit cannot be propagated.
*/
function _stationFrame(result) {
const sat = layerState._catalog.get(norad);
if (!sat) return null;
const trackedSample =
_trackedOnStation() && Number.isFinite(layerState._trackedFrameGeo?.atMs)
? layerState._trackedFrameGeo
: null;
const date = new Date(
trackedSample ? trackedSample.atMs : layerState.now(),
);
let posVel;
try {
posVel = propagate(sat.satrec, date);
} catch {
posVel = null;
}
if (
!posVel?.position ||
typeof posVel.position === 'boolean' ||
!posVel.velocity ||
typeof posVel.velocity === 'boolean'
)
return null;
const gmst = gstime(date);
if (trackedSample) {
// The sample the camera and the tracked dot were placed from.
copyInto(layerState._trackedFrameCartesian, result);
} else {
const geo = eciToGeodetic(posVel.position, gmst);
copyInto(
fromRadians(geo.longitude, geo.latitude, geo.height * 1000),
result,
);
}
const axes = stationFlightAxes(
result,
temeToEcefAxes(posVel.velocity, gmst),
);
return axes ? { date, axes } : null;
}
/**
* The Cockpit camera's place on the station: one of the views on the
* model, in the world, worked out from the same sample the model is about
* to be placed on, so the camera stays on the model however fast the orbit
* moves it. The spec's `cockpitMount` chooses the view; null for a station
* without views.
* @param {string|null} [key] The view asked for; the first on offer when
* it is not given or not on offer.
* @returns {object|null} Null unless the tracked satellite is the station
* and the model is loaded and may show.
*/
function _cockpitMount(key = null) {
if (!spec.cockpitMount) return null;
if (!ready || !_trackedOnStation() || !_shouldShow()) return null;
const frame = _stationFrame(scratchMountCentre);
if (!frame) return null;
return spec.cockpitMount({
key,
centre: scratchMountCentre,
axes: frame.axes,
name: (noradId) => layerState._catalog.get(noradId)?.name ?? null,
// An entry is offered to ride only when it has a dot to track.
entry: (noradId) =>
noradId !== null && layerState._points.has(noradId) ? noradId : null,
dockedVehicle: _dockedVehicle(),
});
}
/**
* A vehicle docked to the station (a Progress, a Shenzhou, a Dragon): the
* tracked one when that is what is tracked, else the lowest catalog number
* among those docked. The station's own modules have entries too (Zarya,
* Nauka; Tianhe, Wentian): they are the station, not a vehicle. Null when
* no vehicle is docked.
* @returns {number|null}
*/
function _dockedVehicle() {
const vehicle = (noradId) =>
noradId !== norad &&
!spec.isModule(noradId, layerState._catalog.get(noradId));
const tracked = layerState._trackedNorad;
if (tracked !== null && vehicle(tracked)) return tracked;
let lowest = null;
for (const group of [dockedByOrbit, layerState._dockedCompanions ?? []])
for (const noradId of group)
if (vehicle(noradId) && (lowest === null || noradId < lowest))
lowest = noradId;
return lowest;
}
/**
* Per-frame update from the layer's preRender tick.
* @returns {void}
*/
function _updateStationModel() {
visualValid = false;
// The docked set first: whether the model may show (the Cockpit riding
// the station) is read from it, so it is kept current before that. Once
// a second; the dots are handed over or given back with the scan.
if (item) _scanCompanions(Date.now(), handingOver);
const show = _shouldShow();
if (!show) {
_hide();
// The dots draw at every distance while the model may not.
_releaseDots();
if (handedCompanions.size) _releaseCompanions();
handingOver = false;
_syncOrbitCloseUp(false);
// Off, the layer gives the model's memory back at once; hidden, after
// a while.
if (!layerState._enabled) _unload();
else _undrawn();
return;
}
const dotPosition = parts.rendering._pointPosition(norad);
const eye = _eye();
const cameraDistance =
dotPosition && eye
? distance(eye, dotPosition)
: Number.POSITIVE_INFINITY;
if (!item) {
// The file is fetched only once the camera nears the model's range, so
// a globe-wide view of the layer never downloads it.
if (
!loading &&
!failed &&
dotPosition &&
cameraDistance <= spec.maxDistanceM * 1.5
)
_load(dotPosition);
return;
}
// Until the renderer has the model loaded and posed, the dots stand at
// every distance: the station never goes dark while the file loads, nor
// for good when it fails to.
if (!ready) {
_hide();
_releaseDots();
if (handedCompanions.size) _releaseCompanions();
handingOver = false;
_syncOrbitCloseUp(false);
if (
failedAt !== null &&
Date.now() - failedAt >=
(spec.retryAfterMs ?? STATION_MODEL_RETRY_AFTER_MS)
)
_unload(); // asked for again on the next frame in range
else if (cameraDistance > spec.maxDistanceM * 1.5) _undrawn();
else undrawnSince = null;
return;
}
// The docked dots are the model's within its range: handed over at
// once when the model starts drawing, then with each scan.
if (!handingOver) {
handingOver = true;
lastCompanionScanMs = Number.NEGATIVE_INFINITY;
_scanCompanions(Date.now(), true);
}
_handOverDots();
_syncOrbitCloseUp(cameraDistance < spec.orbitHideM);
// Out of range the model would not draw anyway: skip the SGP4 sample.
if (cameraDistance > spec.maxDistanceM * 1.5) {
_hide();
_undrawn();
return;
}
undrawnSince = null;
const frame = _stationFrame(scratchPosition);
if (!frame) {
// Nowhere to draw the model (the orbit would not propagate): the dots
// draw at every distance rather than nothing at all.
_hide();
_releaseDots();
return;
}
const { date, axes } = frame;
copyInto(scratchPosition, visualPosition);
copyInto(scratchPosition, item.pos);
item.orientation = stationModelOrientation(
scratchPosition,
axes,
spec.localAxes,
);
telemetry?.touch();
articulation.update(nodePoses, date, scratchPosition, axes);
item.show = true;
_send();
visualValid = ready;
}
/**
* Where the tracked card should anchor: the station centre the model is
* rendering at this frame, or null while the model is not drawn (the card
* then keeps the dot's position). Up close the dot's cache can be a frame
* ahead of the rendered model, ~130 m of orbit, which shook the card.
* @returns {{x:number,y:number,z:number}|null}
*/
function _visualPosition() {
if (!visualValid || !item?.show) return null;
const eye = _eye();
if (eye && distance(eye, visualPosition) > spec.maxDistanceM) return null;
return visualPosition;
}
/**
* How far the tracked card must stay from its anchor to clear the model, in
* pixels, or null while the dot shows.
*/
function _cardClearPx() {
const position = _visualPosition();
const pose = findCamera(layerState._viewer)?.pose?.() ?? null;
const height = canvasOf(layerState._viewer)?.clientHeight;
const fovy = pose?.fovy;
if (!position || !height || !fovy) return null;
const cameraDistance = distance(pose.position, position);
if (!(cameraDistance > 0)) return null;
const pixelsPerMeter = height / (2 * Math.tan(fovy / 2)) / cameraDistance;
return Math.min(
height * 0.45,
Math.max(spec.minPx * 0.35, spec.cardClearM * pixelsPerMeter),
);
}
/**
* The model has not been drawn this frame: once that has lasted
* `unloadAfterMs`, release it.
*/
function _undrawn() {
if (!item) return;
const nowMs = Date.now();
undrawnSince ??= nowMs;
if (
nowMs - undrawnSince >=
(spec.unloadAfterMs ?? STATION_MODEL_UNLOAD_AFTER_MS)
)
_unload();
}
/**
* Release the model's draw set, and the renderer's model and GPU memory
* with it; the dots stand at every distance. The next approach loads it
* again (a failed load is tried again then too).
*/
function _unload() {
_releaseDots();
_releaseCompanions();
handingOver = false;
loading = false;
failed = false;
failedAt = null;
ready = false;
visualValid = false;
undrawnSince = null;
offReady?.();
offFailed?.();
offReady = null;
offFailed = null;
set?.dispose();
set = null;
item = null;
}
function _destroyStationModel() {
_unload();
articulation.reset();
nodePoses.clear();
telemetry?.destroy();
dockedByOrbit.clear();
lastCompanionScanMs = Number.NEGATIVE_INFINITY;
_syncOrbitCloseUp(false);
}
/** Whether the model is standing in for this docked object's dot. */
function _standsInFor(noradId) {
return handedCompanions.has(noradId) && _visualPosition() !== null;
}
/**
* The station's NORAD number when a draw hit landed on its model, so a
* click on the model tracks the station as a click on its dot does; null
* for any other hit.
* @param {{set?: string, id?: string}|null|undefined} hit The click's
* `drawHit`.
* @returns {number|null}
*/
function _hitNorad(hit) {
return set && hit?.set === set.id && hit.id === itemId ? norad : null;
}
return {
key: spec.key,
norad,
spec,
_updateStationModel,
_destroyStationModel,
_visualPosition,
_cardClearPx,
_standsInFor,
_hitNorad,
_cockpitMount,
_trackedOnStation,
/** Where the joints' angles come from, or null for a station without telemetry. */
_telemetryStatus: () => telemetry?.status() ?? null,
/** The joint driver, for the STATION section. */
_articulation: articulation,
/** The node matrices the joint driver last wrote, by node name (the item's `nodes`). */
_nodePoses: nodePoses.poses,
};
}
+481
View File
@@ -0,0 +1,481 @@
// src/layers/satellites/stationModel.test.mjs — a station's model over the
// rendering part's draw items: it loads once the camera nears its range,
// stands in for the station's dot, the docked companions' dots and the
// tracked dot within that range (a display range on the dots, the model's
// own display condition the other side of it), hides the ring up close, and
// gives everything back when it may not show or is destroyed.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { eciToGeodetic, gstime, propagate, twoline2satrec } from 'satellite.js';
import { createOrbits } from './orbits.js';
import { createRendering } from './rendering.js';
import { createStationModel } from './stationModel.js';
import {
ISS_MODEL_LOCAL_AXES,
POINT_STYLES,
TRACKED_ORBIT_COLOR,
} from './policy.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
const STATION = 25544;
const COMPANION = 49044;
const STRANGER = 32711;
const ISS = twoline2satrec(
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537',
);
const AT_MS = Date.UTC(2008, 8, 20, 12, 30, 0);
const MAX_M = 1_000_000;
/** The dots the model stands in for draw only beyond the model's range. */
const FAR_RANGE = [MAX_M, Number.MAX_VALUE];
/** A satellite's ECEF position at `atMs`, as a plain `{x, y, z}`. */
function ecef(satrec, atMs) {
const date = new Date(atMs);
const geo = eciToGeodetic(propagate(satrec, date).position, gstime(date));
const c = Cesium.Cartesian3.fromRadians(
geo.longitude,
geo.latitude,
geo.height * 1000,
);
return { x: c.x, y: c.y, z: c.z };
}
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
const MODEL_SET = 'satellites:station:test';
const MODEL_ITEM = 'station:test';
/**
* A station model over the real rendering part, a fake draw port (the
* model is an item of a `models` set on it) and a fake camera port. The
* station and a companion share an orbit (docked); a stranger's dot sits
* 500 km off.
*/
function fixture(t) {
const stationPos = ecef(ISS, AT_MS);
const strangerPos = { ...stationPos, x: stationPos.x + 500_000 };
const camera = fakeCameraPort({
pose: { position: { ...stationPos }, fovy: Math.PI / 3 },
});
const viewer = { canvas: { clientHeight: 1000 } };
const { draw, unbind } = bindFakeDraw(viewer, { camera: camera.port });
const state = {
now: () => AT_MS,
_enabled: true,
_params: { showPoints: true, showOrbits: true },
_points: new Map(),
_orbitPaths: new Map(),
_catalog: new Map([
[STATION, { satrec: ISS, group: 'core', name: 'ISS (ZARYA)' }],
[COMPANION, { satrec: ISS, group: 'core', name: 'ISS (NAUKA)' }],
]),
_viewer: viewer,
_trackedNorad: null,
_trackedFrameGeo: null,
_trackedFrameNumber: -1,
_dockedCompanions: new Set(),
_cockpitHiddenPath: null,
_cockpitSubjectNorad: null,
_lastPropagation: -Infinity,
_lastReckonMs: AT_MS,
_lastRingRotation: -Infinity,
_lastFocusUpdate: -Infinity,
_activeFocusCount: 0,
};
const parts = {
orbits: createOrbits({ state: {}, services: {}, parts: {} }),
tracking: { _getTrackedFramePosition: () => null },
catalog: { _propagateDenseChunk() {} },
controls: {
_classVisible: () => true,
satelliteVisualsVisible: (enabled, requested) =>
Boolean(enabled) && Boolean(requested),
},
};
parts.rendering = createRendering({
state,
services: {
focus: {
focusNowMs: (ms) => ms,
getFocusTarget: () => null,
focusPassIsNeeded: () => false,
},
},
parts,
});
const updates = [];
const spec = {
key: 'test',
label: 'TEST',
norad: STATION,
modelUrl: '/models/test.glb',
scale: 2,
minPx: 64,
maxDistanceM: MAX_M,
orbitHideM: 50_000,
cardClearM: 60,
companionRadiusM: 5_000,
companionCoarseM: 200_000,
companionScanMs: 0,
localAxes: ISS_MODEL_LOCAL_AXES,
isModule: () => true,
createArticulation: () => ({
update: (...args) => updates.push(args),
reset() {},
}),
createTelemetry: null,
cockpitMount: null,
hideInCockpit: true,
syncOrbit: null,
};
const model = createStationModel(spec, {
state,
parts,
resolveAsset: (url) => `/assets${url}`,
});
parts.stationModels = [model];
parts.rendering._attach(viewer);
parts.rendering._addPoint(STATION, stationPos, POINT_STYLES.iss);
parts.rendering._addPoint(COMPANION, stationPos, POINT_STYLES.iss);
parts.rendering._addPoint(STRANGER, strangerPos, POINT_STYLES.iss);
const points = [...draw.sets.keys()].find((id) => id.endsWith(':points'));
const set = (suffix) => draw.set(points.replace(':points', suffix));
let frame = 0;
t.after(() => unbind());
const f = {
state,
parts,
model,
updates,
stationPos,
strangerPos,
/** The model's draw set, while it is live. */
modelSet: () => draw.set(MODEL_SET),
/** The model's draw item, once asked for. */
modelItem: () => draw.set(MODEL_SET)?.items.get(MODEL_ITEM),
cameraAt(metres) {
camera.setPose({
position: { ...stationPos, x: stationPos.x + metres },
});
},
tick() {
parts.rendering._preRenderTick({ frame: ++frame });
},
/** Bring the camera into loading range and let the renderer load it. */
async load() {
f.cameraAt(MAX_M * 1.4);
f.tick();
draw.ready(MODEL_SET, MODEL_ITEM);
await settle();
},
/** The renderer reports the model loaded, or failed to. */
readyModel: () => draw.ready(MODEL_SET, MODEL_ITEM),
failModel: () => draw.loadFailed(MODEL_SET, MODEL_ITEM),
/** Track `noradId`, placing the tracked sample on the station. */
track(noradId, at) {
state._trackedNorad = noradId;
state._trackedFrameGeo = { atMs: AT_MS };
Object.assign(state._trackedFrameCartesian, at);
parts.rendering._removeTrackedEntity();
parts.rendering._addTrackedEntity({ position: () => at });
},
drawn: (id) => set(':points').items.get(String(id)),
trackedDot: () => set(':tracked').items.get(String(state._trackedNorad)),
ring: (id) => set(':rings').items.get(String(id)),
};
return f;
}
test('the model loads once the camera nears its range, measured from the dot as drawn', async (t) => {
const f = fixture(t);
f.cameraAt(MAX_M * 5);
f.tick();
assert.equal(f.modelSet(), undefined, 'a globe-wide view never asks for it');
f.cameraAt(MAX_M * 1.4);
f.tick();
const item = f.modelItem();
assert.ok(item, 'one item of a models set of its own');
assert.equal(item.url, '/assets/models/test.glb');
assert.deepEqual(
item.meta,
{ norad: STATION },
'a click on the model tracks the station',
);
assert.equal(item.scale, 2);
assert.equal(item.minPixelSize, 64);
assert.deepEqual(item.displayRange, [0, MAX_M], 'drawn within its range');
assert.equal(item.show, false, 'hidden until posed');
const writes = f.modelSet().writes;
f.cameraAt(MAX_M * 5);
f.tick();
assert.equal(f.modelSet().writes, writes, 'out of range nothing is sent');
assert.equal(f.model._hitNorad({ set: MODEL_SET, id: MODEL_ITEM }), STATION);
assert.equal(f.model._hitNorad({ set: 'other', id: MODEL_ITEM }), null);
assert.equal(f.model._hitNorad(null), null);
assert.equal(
f.model._visualPosition(),
null,
'the card keeps the dot until the renderer has the model',
);
});
test('posed, the model sits on the station with its flight axes as heading, pitch and roll', async (t) => {
const f = fixture(t);
await f.load();
f.cameraAt(20_000);
f.tick();
const item = f.modelItem();
assert.equal(item.show, true);
assert.ok(Math.abs(item.pos.x - f.stationPos.x) < 1, 'on the station');
// The renderer places a model by heading, pitch and roll at its position
// (Cesium's headingPitchRollToFixedFrame): the frame that gives must have
// the model's local axes where ISS_MODEL_LOCAL_AXES says, zenith away from
// the Earth and along-track horizontal.
const { heading, pitch, roll } = item.orientation;
const at = new Cesium.Cartesian3(item.pos.x, item.pos.y, item.pos.z);
const m = Cesium.Transforms.headingPitchRollToFixedFrame(
at,
new Cesium.HeadingPitchRoll(heading, pitch, roll),
);
const column = (c) => [m[c * 4], m[c * 4 + 1], m[c * 4 + 2]];
const up = Cesium.Cartesian3.normalize(at, new Cesium.Cartesian3());
const along = (v) => v[0] * up.x + v[1] * up.y + v[2] * up.z;
const zenith = column(ISS_MODEL_LOCAL_AXES.indexOf('z'));
assert.ok(
Math.abs(along(zenith) - 1) < 1e-6,
'the zenith axis points away from the Earth',
);
const track = column(ISS_MODEL_LOCAL_AXES.indexOf('x'));
assert.ok(Math.abs(along(track)) < 1e-6, 'the along-track axis is level');
assert.equal(f.updates.length, 1, 'the joints are driven');
const nodes = f.updates[0][0];
assert.equal(nodes.ready, true, 'into node poses');
// What the driver writes to a node is the item's `nodes`, by name, as a
// column-major matrix the renderer applies to the model's glTF node.
const turned = new Float64Array(16);
turned[0] = turned[5] = turned[10] = turned[15] = 1;
turned[14] = 2.5;
nodes.getNode('SOLAR_JOINT').matrix = turned;
f.tick();
assert.equal(item.nodes, f.model._nodePoses, 'one object for the item');
assert.deepEqual(Array.from(item.nodes.SOLAR_JOINT), Array.from(turned));
f.model._destroyStationModel();
assert.equal(
Object.keys(f.model._nodePoses).length,
0,
'destroyed, every node goes back to its authored pose',
);
});
test('a station without views on its model hides it while the Cockpit rides the station, its own entry or a docked one', async (t) => {
const f = fixture(t);
let held = false;
f.parts.cockpit = { _cockpitHeld: () => held };
await f.load();
f.cameraAt(20);
// Riding a docked object (the companion shares the orbit).
f.track(COMPANION, f.stationPos);
f.tick();
assert.equal(f.modelItem().show, true, 'outside the Cockpit it draws');
held = true;
// Frame after frame: hiding the model gives the docked dots back, and
// that must not make the layer forget the companion is docked (which
// showed the model again, and so on, every other frame).
for (let i = 0; i < 4; i++) {
f.tick();
assert.equal(
f.modelItem().show,
false,
`the Cockpit camera would sit inside the hull (tick ${i})`,
);
assert.equal(f.model._trackedOnStation(), true, `docked (tick ${i})`);
}
assert.equal(f.model._visualPosition(), null);
// Riding the station itself.
held = false;
f.track(STATION, f.stationPos);
f.tick();
assert.equal(f.modelItem().show, true);
held = true;
f.tick();
assert.equal(f.modelItem().show, false);
// A station that mounts the Cockpit camera on its model keeps drawing.
f.model.spec.hideInCockpit = false;
f.tick();
assert.equal(f.modelItem().show, true);
});
test('until the renderer has the model the dots stand at every distance, and stay so when it fails to load', async (t) => {
const f = fixture(t);
f.parts.rendering._showOrbitPath(STATION, TRACKED_ORBIT_COLOR);
f.track(COMPANION, f.stationPos);
f.cameraAt(MAX_M * 1.4);
f.tick(); // asks for the model
f.cameraAt(20_000);
f.tick();
f.tick();
// Loading: nothing is handed over, so the station never goes dark.
assert.equal(f.modelItem().show, false);
assert.equal(f.drawn(STATION).displayRange, undefined);
assert.equal(f.drawn(COMPANION).displayRange, undefined);
assert.equal(f.trackedDot().displayRange, undefined);
assert.equal(
f.ring(STATION).show,
true,
'the ring is not hidden for a model not drawn',
);
assert.equal(f.model._visualPosition(), null, 'the card keeps the dot');
assert.equal(f.model._cockpitMount(), null);
// The load fails: the dots stay at every distance, frame after frame.
f.failModel();
for (let i = 0; i < 3; i++) f.tick();
assert.equal(f.modelItem().show, false);
assert.equal(f.drawn(STATION).displayRange, undefined);
assert.equal(f.drawn(COMPANION).displayRange, undefined);
assert.equal(f.trackedDot().displayRange, undefined);
// After the retry delay the model is released, and the next frame asks
// for it again: one transient failure does not cost the session.
f.model.spec.retryAfterMs = 0;
f.tick();
assert.equal(f.modelSet(), undefined, 'released after a failure');
f.tick();
assert.ok(f.modelItem(), 'asked for again');
// That load finishes: the dots are handed over.
f.readyModel();
f.tick();
assert.equal(f.modelItem().show, true);
assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE);
assert.deepEqual(f.trackedDot().displayRange, FAR_RANGE);
});
test('a model still loading counts as undrawn out of range and is released', (t) => {
const f = fixture(t);
f.cameraAt(MAX_M * 1.4);
f.tick(); // asks for the model, which never answers
f.cameraAt(MAX_M * 5);
f.tick();
assert.ok(f.modelSet(), 'kept for a while');
f.model.spec.unloadAfterMs = 0;
f.tick();
assert.equal(f.modelSet(), undefined);
});
test('turning the layer off, or a while undrawn, releases the model; the next approach asks for it again', async (t) => {
const f = fixture(t);
await f.load();
f.cameraAt(20_000);
f.tick();
assert.equal(f.modelItem().show, true);
// Out of range, within the grace: kept.
f.cameraAt(MAX_M * 5);
f.tick();
assert.ok(f.modelSet(), 'kept for a while');
// Past it: released, and the dots stand everywhere.
f.model.spec.unloadAfterMs = 0;
f.tick();
assert.equal(f.modelSet(), undefined, 'its set is disposed');
assert.equal(f.drawn(STATION).displayRange, undefined);
// The next approach asks for it again.
f.cameraAt(MAX_M * 1.4);
f.tick();
assert.ok(f.modelItem(), 'asked for again');
f.readyModel();
f.cameraAt(20_000);
f.tick();
assert.equal(f.modelItem().show, true);
// Turning the layer off releases it at once.
f.model.spec.unloadAfterMs = 60_000;
// (The layer's disable asks the model once, as here: no frame runs then.)
f.state._enabled = false;
f.model._updateStationModel();
assert.equal(f.modelSet(), undefined);
assert.equal(f.drawn(STATION).displayRange, undefined);
});
test('within its range the model stands in for the dots and hides the ring; beyond it the dots draw', async (t) => {
const f = fixture(t);
await f.load();
f.parts.rendering._showOrbitPath(STATION, TRACKED_ORBIT_COLOR);
f.cameraAt(20_000);
f.tick();
assert.equal(f.modelItem().show, true);
assert.equal(f.updates.length, 1, 'the joints are driven');
assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE);
assert.deepEqual(
f.drawn(COMPANION).displayRange,
FAR_RANGE,
'docked, by orbit against orbit',
);
assert.equal(f.drawn(STRANGER).displayRange, undefined, 'not docked');
assert.equal(
f.drawn(STATION).show,
true,
'the range alone splits the distances',
);
assert.equal(f.model._standsInFor(COMPANION), true);
assert.equal(f.model._standsInFor(STRANGER), false);
assert.equal(
f.ring(STATION).show,
false,
'the ring runs off the model up close',
);
assert.ok(f.model._visualPosition(), 'the card anchors on the model');
assert.ok(f.model._cardClearPx() > 0);
// The tracked dot too, while the tracked satellite is the station (here
// an object docked to it)…
f.track(COMPANION, f.stationPos);
f.tick();
assert.deepEqual(f.trackedDot().displayRange, FAR_RANGE);
// …and not once another satellite is tracked.
f.track(STRANGER, f.strangerPos);
f.tick();
assert.equal(f.trackedDot().displayRange, undefined);
// Beyond its range the model is not drawn and the dots are, by their range.
f.cameraAt(MAX_M * 2.5);
f.tick();
assert.equal(f.modelItem().show, false);
assert.equal(f.model._visualPosition(), null);
assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE);
assert.equal(f.ring(STATION).show, true, "back to the layer's orbit toggle");
});
test('the dots and the ring come back when the model may not show, and on destroy', async (t) => {
const f = fixture(t);
await f.load();
f.parts.rendering._showOrbitPath(STATION, TRACKED_ORBIT_COLOR);
f.track(COMPANION, f.stationPos);
f.cameraAt(20_000);
f.tick();
assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE);
assert.deepEqual(f.trackedDot().displayRange, FAR_RANGE);
assert.equal(f.ring(STATION).show, false);
// Points off: the model may not show, so every dot draws at any distance.
f.state._params.showPoints = false;
f.tick();
assert.equal(f.modelItem().show, false);
assert.equal(f.drawn(STATION).displayRange, undefined);
assert.equal(f.drawn(COMPANION).displayRange, undefined);
assert.equal(f.trackedDot().displayRange, undefined);
assert.equal(f.model._standsInFor(COMPANION), false);
assert.equal(f.ring(STATION).show, true);
// Points on again: handed over again.
f.state._params.showPoints = true;
f.tick();
assert.equal(f.modelItem().show, true);
assert.deepEqual(f.drawn(STATION).displayRange, FAR_RANGE);
assert.deepEqual(f.drawn(COMPANION).displayRange, FAR_RANGE);
assert.deepEqual(f.trackedDot().displayRange, FAR_RANGE);
assert.equal(f.ring(STATION).show, false);
// Destroyed: the model leaves the scene and the dots are given back.
f.model._destroyStationModel();
f.parts.rendering._flushPoints();
assert.equal(f.modelSet(), undefined, 'its set is disposed');
assert.equal(f.drawn(STATION).displayRange, undefined);
assert.equal(f.drawn(COMPANION).displayRange, undefined);
assert.equal(f.trackedDot().displayRange, undefined);
assert.equal(f.ring(STATION).show, true);
assert.equal(f.model._visualPosition(), null);
});
+92
View File
@@ -0,0 +1,92 @@
import { STATIONS, stationTrackedOn } from './policy.js';
/**
* Which station a catalog entry belongs to. The layer knows more than one
* station (STATIONS in policy.js: the ISS, Tiangong), each drawn as a model
* part (stationModel.js) at its own catalog entry and standing in for the
* entries docked to it; the parts that key behaviour to "the station" (card
* anchor and clearance, detection marks, the LIVE and STATION sections, the
* Cockpit's mounts) ask here instead of naming the ISS. The model parts are
* read from `parts.stationModels` each time, so a layer built without them
* (tests, a part replaced) still answers.
*/
/**
* The model whose station `noradId` is drawn as: the station's own entry,
* or a docked object whose dot the model stands in for right now.
* @param {Array<{norad: number, _standsInFor?: (noradId: number) => boolean}>} models
* @param {number|null|undefined} noradId
* @returns {object|null}
*/
export function stationModelFor(models, noradId) {
if (noradId === null || noradId === undefined) return null;
for (const model of models)
if (model.norad === noradId || model._standsInFor?.(noradId)) return model;
return null;
}
/**
* The station that is selected: the tracked satellite is the station
* itself, or an object docked to it, judged by the dots sharing a position
* (`dockedCompanions`), by both orbits compared when tracking began
* (`trackedDockedToStation`, the station's NORAD or null), or by the
* station's model standing in for its dot.
* @param {ReadonlyArray<{key: string, norad: number}>} stations
* @param {Array<{norad: number, _standsInFor?: (noradId: number) => boolean}>} models
* @param {{trackedNorad: number|null, dockedCompanions?: {has(id: number): boolean}|null,
* trackedDockedToStation?: number|null}} selection
* @returns {{key: string, norad: number, model: object|null}|null} The
* station and its model part (null when none is built).
*/
export function trackedStationOf(
stations,
models,
{ trackedNorad, dockedCompanions, trackedDockedToStation },
) {
if (trackedNorad === null || trackedNorad === undefined) return null;
for (const station of stations) {
const model = models.find((m) => m.norad === station.norad) ?? null;
if (
stationTrackedOn(station.norad, trackedNorad, dockedCompanions) ||
trackedDockedToStation === station.norad ||
Boolean(model?._standsInFor?.(trackedNorad))
)
return { ...station, model };
}
return null;
}
/** The layer's station model parts, as built (index.js). */
export function stationModels(parts) {
return parts.stationModels ?? [];
}
/** See stationModelFor, over the layer's model parts. */
export function modelFor(parts, noradId) {
return stationModelFor(stationModels(parts), noradId);
}
/** See trackedStationOf, over the layer's stations, model parts and state. */
export function trackedStation(layerState, parts) {
return trackedStationOf(STATIONS, stationModels(parts), {
trackedNorad: layerState._trackedNorad,
dockedCompanions: layerState._dockedCompanions,
trackedDockedToStation: layerState._trackedDockedToStation ?? null,
});
}
/**
* The station whose model a click's draw hit landed on, over the layer's
* model parts: its NORAD number, or null for any other hit.
* @param {object} parts
* @param {{set?: string, id?: string}|null|undefined} hit
* @returns {number|null}
*/
export function modelHitNorad(parts, hit) {
if (!hit) return null;
for (const model of stationModels(parts)) {
const norad = model._hitNorad?.(hit) ?? null;
if (norad !== null) return norad;
}
return null;
}
@@ -0,0 +1,91 @@
// src/layers/satellites/stationModels.test.mjs — which station a catalog
// entry belongs to, over stand-in model parts.
import test from 'node:test';
import assert from 'node:assert/strict';
import { ISS_NORAD, STATIONS, TIANGONG_NORAD } from './policy.js';
import {
modelFor,
stationModelFor,
trackedStation,
trackedStationOf,
} from './stationModels.js';
const NAUKA = 49044;
const SHENZHOU = 60000;
const GPS = 32711;
const part = (norad, standsIn = []) => ({
norad,
_standsInFor: (id) => standsIn.includes(id),
});
test('the layer knows the ISS and Tiangong, each with a LIVE key', () => {
assert.deepEqual(
STATIONS.map((s) => [s.key, s.norad]),
[
['iss', ISS_NORAD],
['tiangong', TIANGONG_NORAD],
],
);
for (const station of STATIONS) assert.ok(station.companionRadiusM > 0);
});
test('an entry is drawn by the model at its own number, or one standing in for it', () => {
const iss = part(ISS_NORAD, [NAUKA]);
const tiangong = part(TIANGONG_NORAD, [SHENZHOU]);
const models = [iss, tiangong];
assert.equal(stationModelFor(models, ISS_NORAD), iss);
assert.equal(stationModelFor(models, NAUKA), iss);
assert.equal(stationModelFor(models, TIANGONG_NORAD), tiangong);
assert.equal(stationModelFor(models, SHENZHOU), tiangong);
assert.equal(stationModelFor(models, GPS), null);
assert.equal(stationModelFor(models, null), null);
assert.equal(stationModelFor([], ISS_NORAD), null);
});
test('the selected station: itself, a docked companion by position, by orbit, or by stand-in', () => {
const models = [part(ISS_NORAD), part(TIANGONG_NORAD, [SHENZHOU])];
const select = (selection) => trackedStationOf(STATIONS, models, selection);
assert.equal(select({ trackedNorad: null }), null);
assert.equal(select({ trackedNorad: GPS }), null);
assert.equal(select({ trackedNorad: ISS_NORAD })?.key, 'iss');
assert.equal(select({ trackedNorad: TIANGONG_NORAD })?.key, 'tiangong');
// Nauka's dot shares the ISS's position.
assert.equal(
select({ trackedNorad: NAUKA, dockedCompanions: new Set([ISS_NORAD]) })
?.key,
'iss',
);
// A Tianzhou judged docked by orbit when tracking began.
assert.equal(
select({ trackedNorad: 60001, trackedDockedToStation: TIANGONG_NORAD })
?.key,
'tiangong',
);
// A Shenzhou whose dot the Tiangong model stands in for.
assert.equal(select({ trackedNorad: SHENZHOU })?.key, 'tiangong');
// The answer carries the station's model part, or null without one.
assert.equal(select({ trackedNorad: ISS_NORAD })?.model, models[0]);
assert.equal(
trackedStationOf(STATIONS, [], { trackedNorad: TIANGONG_NORAD })?.model,
null,
);
});
test('the layer-state readers take the parts as built, or none', () => {
const parts = {};
const layerState = {
_trackedNorad: SHENZHOU,
_dockedCompanions: new Set(),
_trackedDockedToStation: TIANGONG_NORAD,
};
assert.equal(modelFor(parts, ISS_NORAD), null);
assert.equal(trackedStation(layerState, parts)?.key, 'tiangong');
assert.equal(trackedStation(layerState, parts)?.model, null);
parts.stationModels = [part(TIANGONG_NORAD)];
assert.equal(
trackedStation(layerState, parts)?.model,
parts.stationModels[0],
);
assert.equal(modelFor(parts, TIANGONG_NORAD), parts.stationModels[0]);
});
+376
View File
@@ -0,0 +1,376 @@
import { distance } from '../../geo/index.js';
import { findCamera, findFrame } from '../../render/rendererOf.js';
import {
issCommandCameraOnStation,
issCommandOffersZoom,
issCommandZoomOffset,
} from './issCommand.js';
/**
* The STATION section in Context, for whichever station is selected. A
* station is described once (`issStation.js` describes the ISS) and this
* presents it: Automatic, where the joints follow their rules and the panel
* says where the angles come from (telemetry, or computed when there is
* none); Manual, where the person moves them with the controls the
* description lists; and a zoom to the station from far away. Another
* station plugs in with a description of its own.
*
* @typedef {object} StationDescription
* @property {string} key Short id, e.g. 'iss'.
* @property {string} title The station's name, as a badge.
* @property {() => boolean} selected Whether this station is the tracked
* subject (also as one of its docked entries).
* @property {() => string} subjectName The tracked entry's name.
* @property {() => object|null} articulation The joint driver.
* @property {() => {state: string, poseAgeMs: number|null,
* liveUntilMs: number|null}|null} telemetry Where the angles come from.
* @property {() => {x: number, y: number, z: number}|null} position The
* station's drawn centre (ECEF metres), for the zoom.
* @property {string} zoomLabel The zoom button's text (a msg key).
* @property {{live?: string, computed: string}} notes Automatic's note on
* what moves the joints (msg keys): `live` while the articulation reports
* telemetry, `computed` otherwise (and always, for a station without a
* feed).
* @property {Array<{id: string, label: string, note?: string|null,
* kind: 'choices', choices: Array<{id: string, label: string,
* isDefault?: boolean, apply: (articulation: object) => void}>}|
* {id: string, label: string, kind: 'sliders', resume?: string,
* sliders: Array<{id: string, label: string, min: number, max: number,
* apply: (articulation: object, value: number) => void}>,
* resumeApply?: (articulation: object) => void}>} groups Manual controls.
* @property {(articulation: object) => void} automatic Hand every joint
* back to its rule.
*/
/** How often the status line's age is refreshed while the panel shows. */
export const STATION_PANEL_TICK_MS = 1000;
/**
* @param {{state: object, parts: object, stations: StationDescription[],
* now?: () => number}} context
*/
export function createStationPanel({
state: layerState,
parts,
stations,
now = Date.now,
}) {
const listeners = new Set();
let view = null;
/** The station shown, its mode, its Manual choices and slider values. */
let current = null;
let mode = 'automatic';
let choices = new Map();
let sliders = new Map();
let ticker = null;
let zoomTimer = null;
/** The frame pump while a joint glides, and when it stops. */
let pump = null;
let pumpUntil = 0;
/** The last view published, as text: an unchanged view is not republished. */
let publishedKey = null;
function _stationShown() {
if (!layerState._enabled) return null;
// The right rail is hidden while the Cockpit rides; nothing to show.
if (parts.cockpit?._cockpitHeld()) return null;
return stations.find((station) => station.selected()) ?? null;
}
function _resetManual(station) {
choices = new Map();
sliders = new Map();
for (const group of station?.groups ?? []) {
if (group.kind === 'choices') {
const chosen = group.choices.find((choice) => choice.isDefault);
if (chosen) choices.set(group.id, chosen.id);
} else for (const slider of group.sliders) sliders.set(slider.id, 0);
}
}
/**
* The telemetry status with its ages in whole seconds: the section words
* them so, and an age in ms would make every frame a change.
*/
function wholeSeconds(status) {
if (!status) return status;
const second = (ms) =>
Number.isFinite(ms) ? Math.floor(ms / 1000) * 1000 : ms;
return { ...status, poseAgeMs: second(status.poseAgeMs) };
}
function _publish() {
const station = current;
if (!station) {
if (view !== null) {
view = null;
publishedKey = null;
for (const listener of listeners) listener(null);
}
return;
}
const articulation = station.articulation();
const position = station.position();
const eye = position
? (findCamera(layerState._viewer)?.pose?.()?.position ?? null)
: null;
const range = position && eye ? distance(eye, position) : null;
const next = {
key: station.key,
title: station.title,
subject: station.subjectName(),
mode,
telemetry: wholeSeconds(station.telemetry()),
sunlit: mode === 'manual' ? null : (articulation?.isSunlit?.() ?? null),
note:
(articulation?.isLive?.() ? station.notes?.live : null) ??
station.notes?.computed ??
'',
groups: station.groups.map((group) =>
group.kind === 'choices'
? {
id: group.id,
label: group.label,
note: group.note ?? null,
kind: 'choices',
choices: group.choices.map((choice) => ({
id: choice.id,
label: choice.label,
active: choices.get(group.id) === choice.id,
})),
}
: {
id: group.id,
label: group.label,
note: group.note ?? null,
kind: 'sliders',
resume: group.resume ?? null,
sliders: group.sliders.map((slider) => ({
id: slider.id,
label: slider.label,
min: slider.min,
max: slider.max,
value: sliders.get(slider.id) ?? 0,
})),
},
),
zoom: {
offered:
range !== null && issCommandOffersZoom(range) && _cameraOnStation(),
label: station.zoomLabel,
},
};
// Called every frame from the tick: the section re-renders only on a
// change (the age line moves once a second, the rest on an action).
const key = JSON.stringify(next);
if (key === publishedKey) return;
publishedKey = key;
view = next;
for (const listener of listeners) listener(view);
}
function _tick() {
if (ticker) return;
ticker = setInterval(() => {
if (!current) {
clearInterval(ticker);
ticker = null;
return;
}
_publish();
_requestRender();
}, STATION_PANEL_TICK_MS);
ticker.unref?.();
}
/** Ask the renderer for a frame, through the frame port. */
function _requestRender() {
findFrame(layerState._viewer)?.requestRender('station-panel');
}
/**
* Keep frames coming while a joint glides to a new pose: one pump, run
* until the latest ask (a slider drag asks many times a second).
*/
function _renderFor(ms) {
if (!findFrame(layerState._viewer)) return;
pumpUntil = Math.max(pumpUntil, now() + ms);
if (pump) return;
pump = setInterval(() => {
_requestRender();
if (now() > pumpUntil) _stopPump();
}, 33);
pump.unref?.();
}
function _stopPump() {
if (pump) clearInterval(pump);
pump = null;
pumpUntil = 0;
}
function _stopZoom() {
if (zoomTimer) clearInterval(zoomTimer);
zoomTimer = null;
}
/**
* Whether the camera follows the layer's follow target, framed (see
* issCommand.js): the tracked satellite is the station, or docked to it.
*/
function _cameraOnStation() {
return issCommandCameraOnStation(
findCamera(layerState._viewer),
layerState._followTarget,
);
}
/**
* Bring the follow camera in to the station, a step per frame. Only while
* the follow camera is on it: from any other camera the steps would lead
* away, and a zoom pressed during the flight to the station would do so.
*/
function _zoom() {
_stopZoom();
if (!_cameraOnStation()) return false;
let steps = 0;
zoomTimer = setInterval(() => {
const camera = findCamera(layerState._viewer);
steps += 1;
if (
!camera ||
!current?.position() ||
!current?.selected() ||
!_cameraOnStation() ||
steps > 400
) {
_stopZoom();
return;
}
// While the camera follows the station, its follow offset is the eye's
// offset from it: shorten that, never move along the view. The port
// asks for the frame itself.
const next = issCommandZoomOffset(camera.followOffset.get());
if (!next) {
_stopZoom();
return;
}
camera.followOffset.set(next);
}, 16);
return true;
}
const actions = {
setStationMode(next) {
const articulation = current?.articulation();
if (!current || !articulation) return false;
const wanted = next === 'manual' ? 'manual' : 'automatic';
if (wanted === mode) return true;
mode = wanted;
if (mode === 'manual') articulation.setTelemetryAllowed?.(false);
else {
_resetManual(current);
current.automatic(articulation);
}
_renderFor(20_000);
_publish();
return true;
},
chooseStation(groupId, choiceId) {
const articulation = current?.articulation();
const group = current?.groups.find((g) => g.id === groupId);
const choice = group?.choices?.find((c) => c.id === choiceId);
if (!articulation || !choice) return false;
choices.set(groupId, choiceId);
choice.apply(articulation);
_renderFor(20_000);
_publish();
return true;
},
slideStation(sliderId, value) {
const articulation = current?.articulation();
const group = current?.groups.find((g) =>
g.sliders?.some((s) => s.id === sliderId),
);
const slider = group?.sliders.find((s) => s.id === sliderId);
const number = Number(value);
if (!articulation || !slider || !Number.isFinite(number)) return false;
const clamped = Math.min(slider.max, Math.max(slider.min, number));
sliders.set(sliderId, clamped);
slider.apply(articulation, clamped);
_renderFor(2000);
_publish();
return true;
},
resumeStationArm(groupId) {
const articulation = current?.articulation();
const group = current?.groups.find((g) => g.id === groupId);
if (!articulation || !group?.resumeApply) return false;
for (const slider of group.sliders) sliders.set(slider.id, 0);
group.resumeApply(articulation);
_renderFor(20_000);
_publish();
return true;
},
zoomStation() {
if (!current) return false;
return _zoom();
},
};
/**
* Per tick and on tracking changes: show the selected station's panel,
* or take it down. Leaving a station hands its joints back to Automatic,
* so no manual pose lingers.
*/
function _syncStationPanel() {
const station = _stationShown();
if (station !== current) {
if (current && mode === 'manual') {
const articulation = current.articulation();
if (articulation) current.automatic(articulation);
}
_stopZoom();
current = station;
mode = 'automatic';
_resetManual(station);
if (station) _tick();
}
_publish();
}
function _destroyStationPanel() {
// The joints go back to Automatic with the panel, as on leaving a station.
if (current && mode === 'manual') {
const articulation = current.articulation();
if (articulation) current.automatic(articulation);
}
_stopZoom();
_stopPump();
if (ticker) clearInterval(ticker);
ticker = null;
current = null;
mode = 'automatic';
_publish();
}
const methods = {
/**
* Receive the STATION section's view: the current one at once, then
* each change; null while no station is selected.
* @param {(view: object|null) => void} listener
* @returns {() => void} Stops listening.
*/
subscribeStationPanel(listener) {
listeners.add(listener);
listener(view);
return () => listeners.delete(listener);
},
/** The actions the section's controls call (the store's owners). */
getStationActions() {
return actions;
},
};
return { _syncStationPanel, _destroyStationPanel, methods };
}
+370
View File
@@ -0,0 +1,370 @@
// src/layers/satellites/stationPanel.test.mjs — the STATION section's
// presenter, over a stand-in station description.
import test from 'node:test';
import assert from 'node:assert/strict';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { ISS_COMMAND_ZOOM_RANGE_M } from './issCommand.js';
import { createStationPanel } from './stationPanel.js';
/**
* A camera port that follows what it is told to and keeps a follow offset,
* as the renderer's does once the follow has framed the eye.
*/
function fakeFollowCamera({ eye, offset }) {
const camera = {
eye,
offset,
followed: null,
followFramed: false,
offsetsSet: [],
pose: () => ({ position: { ...camera.eye } }),
followOffset: {
get: () => (camera.followFramed ? { ...camera.offset } : null),
set(next) {
camera.offset = { ...next };
camera.offsetsSet.push({ ...next });
},
},
};
return camera;
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function fixture() {
const calls = [];
const articulation = {
isSunlit: () => true,
isLive: () => false,
setTelemetryAllowed: (allowed) => calls.push(['telemetry', allowed]),
};
let selected = false;
let held = false;
let position = null;
let telemetry = { state: 'live', poseAgeMs: 3000, liveUntilMs: null };
const station = {
key: 'test',
title: 'TEST',
selected: () => selected,
subjectName: () => 'TEST STATION',
articulation: () => articulation,
telemetry: () => telemetry,
position: () => position,
zoomLabel: 'Zoom to the station',
notes: {
live: 'Joints on live telemetry.',
computed: 'Computed, not live telemetry.',
},
groups: [
{
id: 'sun',
label: 'Sun position',
kind: 'choices',
choices: [
{
id: 'follow',
label: 'Follow',
isDefault: true,
apply: () => calls.push(['sun', 'follow']),
},
{
id: 'ahead',
label: 'Ahead',
apply: () => calls.push(['sun', 'ahead']),
},
],
},
{
id: 'arm',
label: 'Arm',
kind: 'sliders',
resume: 'Resume',
sliders: [
{
id: 'shoulder',
label: 'Shoulder',
min: -120,
max: 120,
apply: (a, v) => calls.push(['shoulder', v]),
},
{
id: 'elbow',
label: 'Elbow',
min: -90,
max: 90,
apply: (a, v) => calls.push(['elbow', v]),
},
],
resumeApply: () => calls.push(['resume']),
},
],
automatic: () => calls.push(['automatic']),
};
const layerState = { _enabled: true, _viewer: null };
const parts = { cockpit: { _cockpitHeld: () => held } };
const panel = createStationPanel({
state: layerState,
parts,
stations: [station],
});
const views = [];
panel.methods.subscribeStationPanel((view) => views.push(view));
const actions = panel.methods.getStationActions();
return {
panel,
actions,
calls,
views,
view: () => views.at(-1),
layerState,
select: (on) => (selected = on),
hold: (on) => (held = on),
setTelemetry: (next) => (telemetry = next),
setPosition: (next) => (position = next),
};
}
test('the zoom is offered, and runs, only while the follow camera is on the station', async (t) => {
const f = fixture();
t.after(() => f.panel._destroyStationPanel());
const viewer = {};
const camera = fakeFollowCamera({
eye: { x: 5000, y: 0, z: 0 },
offset: { x: 3000, y: 4000, z: 0 },
});
const frames = [];
const { unbind } = bindFakeDraw(viewer, {
camera,
frame: { requestRender: (reason) => frames.push(reason) },
});
t.after(unbind);
const target = { key: 'satellites:25544' };
f.layerState._viewer = viewer;
f.layerState._followTarget = target;
f.setPosition({ x: 0, y: 0, z: 0 });
f.select(true);
f.panel._syncStationPanel();
assert.equal(f.view().zoom.offered, false, 'still flying to the station');
assert.equal(f.actions.zoomStation(), false);
camera.followed = { key: 'flights:other' };
camera.followFramed = true;
f.panel._syncStationPanel();
assert.equal(f.view().zoom.offered, false, 'following something else');
camera.followed = target;
camera.followFramed = false;
f.panel._syncStationPanel();
assert.equal(f.view().zoom.offered, false, 'the follow has not framed yet');
camera.followFramed = true;
f.panel._syncStationPanel();
assert.equal(f.view().zoom.offered, true);
assert.equal(f.actions.zoomStation(), true);
await sleep(120);
const ranges = camera.offsetsSet.map((o) => Math.hypot(o.x, o.y, o.z));
assert.ok(ranges.length >= 3, 'the zoom stepped the follow offset');
for (let i = 0; i < ranges.length; i++) {
const before = i === 0 ? 5000 : ranges[i - 1];
assert.ok(
ranges[i] < before,
`step ${i} came in: ${before} -> ${ranges[i]}`,
);
assert.ok(ranges[i] >= ISS_COMMAND_ZOOM_RANGE_M, 'never past the range');
}
// The bearing is kept: the offset only shortens.
const last = camera.offsetsSet.at(-1);
assert.ok(Math.abs(last.x / last.y - 3 / 4) < 1e-9);
assert.equal(last.z, 0);
// The follow ending stops the zoom where it is.
camera.followed = null;
const steps = camera.offsetsSet.length;
await sleep(50);
assert.equal(camera.offsetsSet.length, steps);
camera.followed = target;
camera.eye = { x: 300, y: 0, z: 0 };
f.panel._syncStationPanel();
assert.equal(f.view().zoom.offered, false, 'close in, the zoom goes');
assert.ok(frames.length === 0 || frames.every((r) => r === 'station-panel'));
});
test('a new subscriber gets the current view at once: nothing while no station is selected', () => {
const f = fixture();
assert.deepEqual(f.views, [null]);
f.panel._syncStationPanel();
assert.deepEqual(f.views, [null], 'unchanged nothing is not re-published');
f.panel._destroyStationPanel();
});
test('selecting the station publishes it in Automatic with its defaults', (t) => {
const f = fixture();
t.after(() => f.panel._destroyStationPanel());
f.select(true);
f.panel._syncStationPanel();
const view = f.view();
assert.equal(view.key, 'test');
assert.equal(view.title, 'TEST');
assert.equal(view.subject, 'TEST STATION');
assert.equal(view.mode, 'automatic');
assert.deepEqual(view.telemetry, {
state: 'live',
poseAgeMs: 3000,
liveUntilMs: null,
});
assert.equal(view.sunlit, true);
assert.match(view.note, /Computed, not live telemetry/);
assert.deepEqual(
view.groups[0].choices.map((c) => [c.id, c.active]),
[
['follow', true],
['ahead', false],
],
);
assert.deepEqual(
view.groups[1].sliders.map((s) => s.value),
[0, 0],
);
assert.equal(view.groups[1].resume, 'Resume');
assert.deepEqual(view.zoom, { offered: false, label: 'Zoom to the station' });
assert.deepEqual(f.calls, [], 'Automatic touches nothing on entry');
});
test('Manual pauses telemetry and offers the controls; Automatic hands the joints back', (t) => {
const f = fixture();
t.after(() => f.panel._destroyStationPanel());
f.select(true);
f.panel._syncStationPanel();
assert.equal(f.actions.setStationMode('manual'), true);
assert.equal(f.view().mode, 'manual');
assert.equal(f.view().sunlit, null, "the Sun line is Automatic's");
assert.deepEqual(f.calls, [['telemetry', false]]);
assert.equal(f.actions.setStationMode('manual'), true, 'again is a no-op');
assert.equal(f.calls.length, 1);
assert.equal(f.actions.chooseStation('sun', 'ahead'), true);
assert.equal(f.view().groups[0].choices[1].active, true);
assert.equal(f.actions.setStationMode('automatic'), true);
assert.equal(f.view().mode, 'automatic');
assert.deepEqual(f.calls.at(-1), ['automatic']);
assert.equal(f.view().groups[0].choices[0].active, true, 'choices reset');
});
test('choices apply to the articulation; an unknown choice is refused', (t) => {
const f = fixture();
t.after(() => f.panel._destroyStationPanel());
f.select(true);
f.panel._syncStationPanel();
assert.equal(f.actions.chooseStation('sun', 'ahead'), true);
assert.deepEqual(f.calls, [['sun', 'ahead']]);
assert.equal(f.actions.chooseStation('sun', 'nowhere'), false);
assert.equal(f.actions.chooseStation('arm', 'ahead'), false);
});
test('sliders clamp to their range and refuse non-numbers', (t) => {
const f = fixture();
t.after(() => f.panel._destroyStationPanel());
f.select(true);
f.panel._syncStationPanel();
assert.equal(f.actions.slideStation('shoulder', '45'), true);
assert.equal(f.actions.slideStation('elbow', 500), true);
assert.equal(f.actions.slideStation('elbow', 'abc'), false);
assert.equal(f.actions.slideStation('wrist', 10), false);
assert.deepEqual(f.calls, [
['shoulder', 45],
['elbow', 90],
]);
assert.deepEqual(
f.view().groups[1].sliders.map((s) => s.value),
[45, 90],
);
assert.equal(f.actions.resumeStationArm('arm'), true);
assert.deepEqual(f.calls.at(-1), ['resume']);
assert.deepEqual(
f.view().groups[1].sliders.map((s) => s.value),
[0, 0],
);
assert.equal(
f.actions.resumeStationArm('sun'),
false,
'choices have no resume',
);
});
test('leaving the station in Manual hands its joints back and takes the section down', (t) => {
const f = fixture();
t.after(() => f.panel._destroyStationPanel());
f.select(true);
f.panel._syncStationPanel();
f.actions.setStationMode('manual');
f.actions.slideStation('shoulder', 30);
f.select(false);
f.panel._syncStationPanel();
assert.equal(f.view(), null);
assert.deepEqual(f.calls.at(-1), ['automatic']);
f.select(true);
f.panel._syncStationPanel();
assert.equal(f.view().mode, 'automatic');
assert.deepEqual(
f.view().groups[1].sliders.map((s) => s.value),
[0, 0],
);
});
test('the section is away while the Cockpit holds the rail, and while the layer is off', (t) => {
const f = fixture();
t.after(() => f.panel._destroyStationPanel());
f.select(true);
f.hold(true);
f.panel._syncStationPanel();
assert.equal(f.view(), null);
f.hold(false);
f.panel._syncStationPanel();
assert.equal(f.view().key, 'test');
f.layerState._enabled = false;
f.panel._syncStationPanel();
assert.equal(f.view(), null);
});
test('every sync re-reads the telemetry status for the status line', (t) => {
const f = fixture();
t.after(() => f.panel._destroyStationPanel());
f.select(true);
f.panel._syncStationPanel();
f.setTelemetry({
state: 'unavailable',
poseAgeMs: 61_000,
liveUntilMs: null,
});
f.panel._syncStationPanel();
assert.equal(f.view().telemetry.state, 'unavailable');
});
test('actions without a station are refused; destroy publishes nothing', () => {
const f = fixture();
assert.equal(f.actions.setStationMode('manual'), false);
assert.equal(f.actions.chooseStation('sun', 'ahead'), false);
assert.equal(f.actions.slideStation('shoulder', 1), false);
assert.equal(f.actions.resumeStationArm('arm'), false);
assert.equal(f.actions.zoomStation(), false);
f.select(true);
f.panel._syncStationPanel();
assert.ok(f.view());
f.panel._destroyStationPanel();
assert.equal(f.view(), null);
});
test('frame after frame, the section is republished only when the age crosses a whole second', (t) => {
const f = fixture();
t.after(() => f.panel._destroyStationPanel());
f.select(true);
f.setTelemetry({ state: 'live', poseAgeMs: 3010, liveUntilMs: null });
f.panel._syncStationPanel();
const published = f.views.length;
assert.equal(f.view().telemetry.poseAgeMs, 3000, 'in whole seconds');
// The tick runs every frame; the age moves by milliseconds.
for (const age of [3020, 3150, 3600, 3999]) {
f.setTelemetry({ state: 'live', poseAgeMs: age, liveUntilMs: null });
f.panel._syncStationPanel();
}
assert.equal(f.views.length, published, 'nothing new to show');
f.setTelemetry({ state: 'live', poseAgeMs: 4001, liveUntilMs: null });
f.panel._syncStationPanel();
assert.equal(f.views.length, published + 1);
assert.equal(f.view().telemetry.poseAgeMs, 4000);
});
@@ -0,0 +1,97 @@
// src/layers/satellites/stationResume.test.mjs — handing a station's moving
// parts back from the STATION section's Manual: every joint posed by hand
// leaves its manual angle, the ones the illustrative sway does not move
// included, and the ISS's Automatic lets telemetry back in.
import assert from 'node:assert/strict';
import test from 'node:test';
import { createIssArticulation, ISS_ARM_JOINTS } from './issArticulation.js';
import { issStationDescription } from './issStation.js';
import { createNodePoses } from './stationModel.js';
import {
createTiangongArticulation,
TIANGONG_ARMS,
} from './tiangongArticulation.js';
/** A station on its usual axes, in sunlight, as the model part places it. */
const AT = { x: 6_780_000, y: 0, z: 0 };
const AXES = { x: [0, 1, 0], y: [0, 0, 1], z: [1, 0, 0] };
const DATE = new Date(Date.UTC(2026, 10, 16, 12, 0, 0));
test('ISS: Resume gives the Canadarm2 joints the sway does not move their filed pose back', () => {
const articulation = createIssArticulation();
const nodes = createNodePoses();
articulation.update(nodes, DATE, AT, AXES, 1_000);
const held = ISS_ARM_JOINTS.filter((joint) => !joint.sway);
const swaying = ISS_ARM_JOINTS.find((joint) => joint.sway);
assert.ok(held.length > 0 && swaying);
for (const joint of [...held, swaying])
articulation.setJoint(joint.node, joint.pivot, joint.axis, Math.PI / 2);
for (const joint of held) assert.ok(nodes.poses[joint.node], joint.node);
articulation.resumeArm();
for (const joint of held)
assert.equal(
nodes.poses[joint.node],
undefined,
`${joint.node} back to its filed pose`,
);
// A swaying joint is posed by the sway again on the next update.
articulation.update(nodes, DATE, AT, AXES, 2_000);
assert.ok(nodes.poses[swaying.node]);
});
test('Tiangong: resuming an arm gives its held joints their folded pose back, and only that arm', () => {
const articulation = createTiangongArticulation();
const nodes = createNodePoses();
articulation.update(nodes, DATE, AT, AXES, 1_000);
const heldOf = (key) =>
TIANGONG_ARMS[key].filter((joint) => !joint.sway && !joint.centre);
for (const key of ['cmm', 'emm'])
for (const joint of heldOf(key))
articulation.setJoint(joint.node, joint.pivot, joint.axis, 1);
articulation.resumeArm('cmm');
for (const joint of heldOf('cmm'))
assert.equal(nodes.poses[joint.node], undefined, joint.node);
for (const joint of heldOf('emm'))
assert.ok(nodes.poses[joint.node], `${joint.node} still by hand`);
articulation.resumeArm();
for (const joint of heldOf('emm'))
assert.equal(nodes.poses[joint.node], undefined, joint.node);
});
test('a node given no matrix leaves the item’s nodes, as a model node goes back to its authored pose', () => {
const nodes = createNodePoses();
const identity = new Float64Array(16);
identity[0] = identity[5] = identity[10] = identity[15] = 1;
nodes.getNode('JOINT').matrix = identity;
assert.ok(nodes.poses.JOINT);
nodes.getNode('JOINT').matrix = undefined;
assert.equal('JOINT' in nodes.poses, false);
});
test("the ISS's Automatic lets telemetry back in and hands every part back", () => {
const calls = [];
const recorder = new Proxy(
{},
{
get:
(_, name) =>
(...args) =>
calls.push([name, ...args]),
},
);
const station = issStationDescription({ state: {}, parts: {} });
station.automatic(recorder);
const names = calls.map(([name]) => name);
assert.deepEqual(
calls.find(([name]) => name === 'setTelemetryAllowed'),
['setTelemetryAllowed', true],
);
for (const name of [
'setOverride',
'setDishOverride',
'setDeploy',
'setRadiatorDeploy',
'resumeArm',
])
assert.ok(names.includes(name), name);
});
@@ -0,0 +1,484 @@
import { sunPositionFixed } from '../../geo/celestial.js';
import {
ISS_JOINT_RATE,
issAimMatrix,
issArmAngles,
issAxisMatrix,
issInShadow,
issRelayDirections,
issStepAngle,
issStepDirection,
issSunInModelFrame,
} from './issArticulation.js';
import { tiangongJoint } from './tiangongJoints.js';
/**
* Tiangong's moving parts, driven from the joint table (tiangongJoints.js):
* every angle is computed, since China publishes no live telemetry for the
* station. The rules are the ISS's (issArticulation.js), written for joints
* whose axes and rest normals come from the table instead of being fixed:
*
* - a wing on one joint (Tianhe's two, each visiting vehicle's two) turns
* about its boom so its cell side faces the Sun;
* - a lab wing (Wentian's and Mengtian's two each) turns first about the
* lab's axis (alpha), so the wing's own axis is across the Sun, then about
* that axis (beta), so the cells face it, the ISS's SARJ/BGA pair;
* - in the Earth's shadow the wings turn flat to the Earth (cell side to
* zenith), which puts them edge-on to the flight direction, the ISS's
* feathering;
* - the high-gain antenna aims at the highest of China's Tianlian relay
* satellites over the equator;
* - the two arms sway slowly for illustration (their real pose is not public).
*
* Joints turn at most ISS_JOINT_RATE on screen.
*/
/** Below this the Sun is too close to a joint's axis to steer by it. */
const MIN_STEER = 0.05;
/** The dish does not look below this much above the station's horizon plane. */
const DISH_MIN_UP = 0.15;
/** Where the wings turn in shadow: cell side to zenith, on the model's axes. */
const ZENITH = Object.freeze([0, 1, 0]);
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a, b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
/** `v` turned by `angle` about the unit vector `axis` (Rodrigues). */
function rotate(v, axis, angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
const k = cross(axis, v);
const d = dot(axis, v) * (1 - c);
return [0, 1, 2].map((i) => v[i] * c + k[i] * s + axis[i] * d);
}
/** The signed difference wrapped to (-π, π]. */
function wrap(delta) {
let d = delta % (2 * Math.PI);
if (d > Math.PI) d -= 2 * Math.PI;
if (d <= -Math.PI) d += 2 * Math.PI;
return d;
}
/** Of `angle` and `angle + π`, the one nearer to `previous`. */
function nearestHalfTurn(angle, previous) {
const flipped = angle + Math.PI;
return Math.abs(wrap(angle - previous)) <= Math.abs(wrap(flipped - previous))
? angle
: flipped;
}
const wing = (node, normal) =>
Object.freeze({ ...tiangongJoint(node), normal: Object.freeze(normal) });
/**
* Wings turned by one joint, with the cell side's normal at rest. The
* station's and the forward and aft vehicles' wings lie flat (cells up); the
* nadir Shenzhou hangs below the node, so its wings' cells face forward.
*/
export const TIANGONG_ONE_AXIS_WINGS = Object.freeze([
wing('TIANHE_ARRAY_PORT_ALPHA', ZENITH),
wing('TIANHE_ARRAY_STBD_ALPHA', ZENITH),
wing('SHENZHOU_FORWARD_ARRAY_PORT_ALPHA', ZENITH),
wing('SHENZHOU_FORWARD_ARRAY_STBD_ALPHA', ZENITH),
wing('SHENZHOU_NADIR_ARRAY_PORT_ALPHA', [0, 0, 1]),
wing('SHENZHOU_NADIR_ARRAY_STBD_ALPHA', [0, 0, 1]),
wing('TIANZHOU_AFT_ARRAY_PORT_ALPHA', ZENITH),
wing('TIANZHOU_AFT_ARRAY_STBD_ALPHA', ZENITH),
]);
/** The lab wings: an alpha joint about the lab's axis, a beta joint under it. */
export const TIANGONG_TWO_AXIS_WINGS = Object.freeze(
[
'WENTIAN_ARRAY_FWD',
'WENTIAN_ARRAY_AFT',
'MENGTIAN_ARRAY_FWD',
'MENGTIAN_ARRAY_AFT',
].map((stem) =>
Object.freeze({
alpha: tiangongJoint(`${stem}_ALPHA`),
beta: tiangongJoint(`${stem}_BETA`),
normal: ZENITH,
}),
),
);
/**
* The arms' joints, base to tip, with the illustrative sway: `centre` and
* `sway` radians over `period` seconds, about the folded pose in the file.
* The joints that lift the booms sway on one side of rest only, so the arms
* rise off the hull and never swing into it.
*/
const arm = (prefix, sway) =>
Object.freeze(
['SHR', 'SHY', 'SHP', 'EP', 'WP', 'WY', 'WR'].map((name) => {
const [centreDeg = 0, swayDeg = 0, period = 0] = sway[name] ?? [];
return Object.freeze({
...tiangongJoint(`${prefix}_${name}`),
centre: (centreDeg * Math.PI) / 180,
sway: (swayDeg * Math.PI) / 180,
period,
});
}),
);
export const TIANGONG_ARMS = Object.freeze({
/** The Tianhe arm (CMM), its booms folded along the core module. */
cmm: arm('CMM', { SHP: [12, 6, 71], EP: [-14, 8, 53], WP: [0, 5, 41] }),
/** The Wentian arm (EMM), folded along the lab. */
emm: arm('EMM', { SHP: [-12, 6, 67], EP: [14, 8, 47], WP: [0, 5, 37] }),
});
/** The high-gain antenna's gimbal; rest boresight +Y. */
export const TIANGONG_HGA = tiangongJoint('TIANHE_HGA');
/**
* China's Tianlian II relay satellites over the equator, degrees east, the
* station's counterparts to NASA's TDRS: II-01 at 79.9°E, II-02 at 171.04°E,
* II-03 at 10.5°E (Wikipedia, "Tianlian", and satcat.com's definitive orbit
* for 53100 at 10.56°E; II-03's slot is not stated by the launch reports, which
* say only that the three form a global network). Nominal slots, not a live
* roster: which satellite the station uses at a given moment is not public.
*/
export const TIANGONG_RELAY_LONGITUDES_DEG = Object.freeze([
79.9, 171.04, 10.5,
]);
/**
* The angle that turns a wing's cell side onto the Sun about one axis.
* @param {number[]} sun Unit vector on the model's axes.
* @param {{axis: readonly number[], normal: readonly number[]}} joint The
* turn axis and the cell side's normal at rest (perpendicular to it).
* @param {number} [previous] Held when the Sun is along the axis.
* @returns {number} Radians.
*/
export function tiangongOneAxisAngle(sun, { axis, normal }, previous = 0) {
const across = cross(axis, normal);
const u = dot(sun, normal);
const v = dot(sun, across);
if (Math.hypot(u, v) < MIN_STEER) return previous;
return Math.atan2(v, u);
}
/**
* The two angles that face a lab wing to the Sun: `alpha` about the lab's
* axis puts the wing's own axis across the Sun, `beta` about that axis turns
* the cell side onto it.
* @param {number[]} sun Unit vector on the model's axes.
* @param {{alphaAxis: readonly number[], betaAxis: readonly number[],
* normal: readonly number[]}} joint Axes at rest; the normal is
* perpendicular to both.
* @param {number} [previousAlpha] Alpha has two answers half a turn apart
* (beta makes up the difference); the nearer to this is kept, and it is
* held when the Sun is along the alpha axis.
* @returns {{alpha: number, beta: number}} Radians.
*/
export function tiangongTwoAxisAngles(
sun,
{ alphaAxis, betaAxis, normal },
previousAlpha = 0,
) {
const across = cross(alphaAxis, betaAxis);
const u = dot(sun, betaAxis);
const v = dot(sun, across);
const alpha =
Math.hypot(u, v) < MIN_STEER
? previousAlpha
: nearestHalfTurn(Math.atan2(-u, v), previousAlpha);
// The Sun as the wing sees it after the alpha turn.
const local = rotate(sun, alphaAxis, -alpha);
const beta = Math.atan2(
dot(local, cross(betaAxis, normal)),
dot(local, normal),
);
return { alpha, beta };
}
/**
* Every wing's target angles.
* @param {number[]} sun Unit vector toward the Sun on the model's axes.
* @param {boolean} sunlit False in the Earth's shadow: the wings turn flat.
* @param {{one: number[], alpha: number[]}} [previous] The last targets.
* @returns {{one: number[], alpha: number[], beta: number[]}} Radians, per
* TIANGONG_ONE_AXIS_WINGS and TIANGONG_TWO_AXIS_WINGS entry.
*/
export function tiangongWingTargets(sun, sunlit, previous = null) {
const toward = sunlit ? sun : ZENITH;
const one = TIANGONG_ONE_AXIS_WINGS.map((joint, i) =>
tiangongOneAxisAngle(toward, joint, previous?.one[i] ?? 0),
);
const two = TIANGONG_TWO_AXIS_WINGS.map((pair, i) =>
tiangongTwoAxisAngles(
toward,
{
alphaAxis: pair.alpha.axis,
betaAxis: pair.beta.axis,
normal: pair.normal,
},
previous?.alpha[i] ?? 0,
),
);
return {
one,
alpha: two.map((t) => t.alpha),
beta: two.map((t) => t.beta),
};
}
/**
* Where the Tianlian satellites are from the station, on the model's axes,
* the highest above the station first.
* @param {number[]} positionEcef Meters.
* @param {{x:number[], y:number[], z:number[]}} axes Flight axes.
* @returns {number[][]} Unit vectors [port, zenith, forward].
*/
export function tiangongRelayDirections(positionEcef, axes) {
return issRelayDirections(positionEcef, axes, TIANGONG_RELAY_LONGITUDES_DEG);
}
/**
* Drives the loaded model's joints. Same contract as the ISS driver
* (`update`, `reset`, the STATION section's `setOverride`, `setJoint`,
* `resumeArm`, `isSunlit`), minus telemetry: `isLive` is always false.
*/
export function createTiangongArticulation() {
let boundModel = null;
let nodes = null;
let angles = null;
let targets = null;
let lastMs = 0;
let override = null;
let lastSunlit = null;
/** Where the dish looks now, on the model's axes. */
let dish = null;
/** STATION section: arms being posed by hand, so their sway is off. */
const armManual = new Set();
/**
* STATION section: wings set by hand, node name → radians. A wing with an
* entry here holds that angle (reached at the joint rate) instead of
* following the Sun; the others keep following.
*/
const wingManual = new Map();
const scratchMatrix = new Float64Array(16);
function bind(model) {
boundModel = model;
const get = (joint) => model.getNode(joint.node) ?? null;
nodes = {
one: TIANGONG_ONE_AXIS_WINGS.map(get),
alpha: TIANGONG_TWO_AXIS_WINGS.map((pair) => get(pair.alpha)),
beta: TIANGONG_TWO_AXIS_WINGS.map((pair) => get(pair.beta)),
dish: get(TIANGONG_HGA),
arms: Object.fromEntries(
Object.entries(TIANGONG_ARMS).map(([key, joints]) => [
key,
joints.map(get),
]),
),
};
angles = null;
dish = null;
}
function sunEcef(date) {
const sun = sunPositionFixed(date.getTime());
const length = Math.hypot(sun.x, sun.y, sun.z) || 1;
return [sun.x / length, sun.y / length, sun.z / length];
}
function write(node, joint, angle) {
if (!node) return;
node.matrix = issAxisMatrix(joint.pivot, joint.axis, angle, scratchMatrix);
}
/**
* @param {{ready: boolean, getNode: (name: string) => object|undefined}} model
* A ready model, or any holder of nodes that take a `matrix`.
* @param {Date} date The instant the model is placed at.
* @param {{x:number,y:number,z:number}} position Earth-fixed station position.
* @param {{x:number[], y:number[], z:number[]}} axes Its flight axes.
* @param {number} [nowMs] Wall clock, for the turn rate.
*/
function update(model, date, position, axes, nowMs = Date.now()) {
if (!model.ready) return;
if (model !== boundModel) bind(model);
const forced = override?.(nowMs) ?? null;
if (forced) {
lastSunlit = Boolean(forced.sunlit);
targets = tiangongWingTargets(forced.sun, forced.sunlit, targets);
} else {
const sun = sunEcef(date);
const sunlit = !issInShadow([position.x, position.y, position.z], sun);
lastSunlit = sunlit;
targets = tiangongWingTargets(
issSunInModelFrame(sun, axes),
sunlit,
targets,
);
}
// A first frame, or one after a pause, goes straight to the pose.
const elapsed = (nowMs - lastMs) / 1000;
lastMs = nowMs;
const maxStep =
!angles || !(elapsed >= 0) || elapsed > 2
? Number.POSITIVE_INFINITY
: ISS_JOINT_RATE * elapsed;
// A wing set by hand aims for its set angle; the rest for the Sun's.
const goalFor = (group, joints) =>
targets[group].map((target, i) =>
wingManual.has(joints[i].node)
? wingManual.get(joints[i].node)
: target,
);
const goals = {
one: goalFor('one', TIANGONG_ONE_AXIS_WINGS),
alpha: goalFor(
'alpha',
TIANGONG_TWO_AXIS_WINGS.map((pair) => pair.alpha),
),
beta: goalFor(
'beta',
TIANGONG_TWO_AXIS_WINGS.map((pair) => pair.beta),
),
};
const step = (group) =>
goals[group].map((target, i) =>
issStepAngle(angles?.[group][i] ?? 0, target, maxStep),
);
const next = { one: step('one'), alpha: step('alpha'), beta: step('beta') };
TIANGONG_ONE_AXIS_WINGS.forEach((joint, i) => {
if (!angles || next.one[i] !== angles.one[i])
write(nodes.one[i], joint, next.one[i]);
});
TIANGONG_TWO_AXIS_WINGS.forEach((pair, i) => {
if (!angles || next.alpha[i] !== angles.alpha[i])
write(nodes.alpha[i], pair.alpha, next.alpha[i]);
if (!angles || next.beta[i] !== angles.beta[i])
write(nodes.beta[i], pair.beta, next.beta[i]);
});
angles = next;
// The dish: the highest relay satellite; one below the station's horizon
// plane keeps its last aim.
const current = dish ?? [0, 1, 0];
const wanted = tiangongRelayDirections(
[position.x, position.y, position.z],
axes,
)[0];
const target = wanted && wanted[1] >= DISH_MIN_UP ? wanted : current;
const stepped = issStepDirection(current, target, maxStep);
if (!dish || stepped.some((c, k) => Math.abs(c - current[k]) > 1e-9))
if (nodes.dish)
nodes.dish.matrix = issAimMatrix(
TIANGONG_HGA.pivot,
stepped,
scratchMatrix,
);
dish = stepped;
// Arms: an illustrative sway about the folded pose (see TIANGONG_ARMS).
for (const [key, joints] of Object.entries(TIANGONG_ARMS)) {
if (armManual.has(key)) continue;
const sway = issArmAngles(nowMs / 1000, joints);
joints.forEach((joint, i) => {
if (!joint.sway && !joint.centre) return;
write(nodes.arms[key][i], joint, joint.centre + sway[i]);
});
}
}
/**
* STATION section: turn any named node about an axis through a pivot. A
* node of either arm takes that arm off its sway.
* @param {string} name
* @param {number[]} pivot
* @param {number[]} axis Unit vector.
* @param {number} angle Radians.
*/
function setJoint(name, pivot, axis, angle) {
for (const [key, joints] of Object.entries(TIANGONG_ARMS))
if (joints.some((joint) => joint.node === name)) armManual.add(key);
const node = boundModel?.getNode(name);
if (node) node.matrix = issAxisMatrix(pivot, axis, angle, scratchMatrix);
}
/** Forget the model and every manual choice: the next update starts clean. */
function reset() {
boundModel = null;
nodes = null;
angles = null;
targets = null;
dish = null;
override = null;
wingManual.clear();
armManual.clear();
}
/**
* STATION section: a function giving the Sun on the model's axes (and
* whether the station is lit) in place of the real one, or null for the
* real one.
* @param {((nowMs:number)=>{sun:number[], sunlit:boolean}|null)|null} fn
*/
function setOverride(fn) {
override = fn;
}
/** Whether the station is in sunlight, as of the last update. */
function isSunlit() {
return lastSunlit;
}
/**
* STATION section: hand an arm back to its sway; both when no arm is named.
* @param {'cmm'|'emm'} [key]
*/
function resumeArm(key) {
for (const arm of key ? [key] : [...armManual]) {
if (!armManual.delete(arm)) continue;
// Joints the sway does not move would keep their manual angle: they go
// back to the folded pose. The swaying ones are posed again next update.
for (const joint of TIANGONG_ARMS[arm] ?? []) {
if (joint.sway || joint.centre) continue;
const node = boundModel?.getNode(joint.node);
if (node) node.matrix = undefined;
}
}
}
/**
* STATION section: hold one wing joint at an angle, by its node name
* (a TIANGONG_ONE_AXIS_WINGS entry, or a lab wing's alpha or beta node).
* The joint turns there at the joint rate on the next updates. Null lets
* the wing follow the Sun again.
* @param {string} name
* @param {number|null} angle Radians.
*/
function setWingAngle(name, angle) {
if (angle === null || !Number.isFinite(angle)) wingManual.delete(name);
else wingManual.set(name, angle);
}
/** STATION section: every wing back to the Sun. */
function resumeWings() {
wingManual.clear();
}
return {
update,
reset,
setOverride,
setJoint,
resumeArm,
setWingAngle,
resumeWings,
isSunlit,
/** No telemetry exists for Tiangong: the angles are always computed. */
isLive: () => false,
setTelemetryAllowed() {},
};
}
@@ -0,0 +1,238 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { ISS_RELAY_LONGITUDES_DEG } from './issArticulation.js';
import { TIANGONG_MODEL_URL } from './policy.js';
import {
TIANGONG_ARMS,
TIANGONG_HGA,
TIANGONG_ONE_AXIS_WINGS,
TIANGONG_RELAY_LONGITUDES_DEG,
TIANGONG_TWO_AXIS_WINGS,
tiangongOneAxisAngle,
tiangongRelayDirections,
tiangongTwoAxisAngles,
tiangongWingTargets,
} from './tiangongArticulation.js';
import { TIANGONG_JOINTS, tiangongJoint } from './tiangongJoints.js';
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a, b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
const unit = (v) => v.map((c) => c / Math.hypot(...v));
/** `v` turned by `angle` about `axis` (Rodrigues), the turn the matrix makes. */
const rotate = (v, axis, angle) => {
const c = Math.cos(angle);
const s = Math.sin(angle);
const k = cross(axis, v);
const d = dot(axis, v) * (1 - c);
return [0, 1, 2].map((i) => v[i] * c + k[i] * s + axis[i] * d);
};
const SUNS = [
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[1, 0, 0],
[0.5, 0.5, 0.7],
[-0.6, 0.2, -0.77],
[0.3, -0.9, 0.3],
[0.9, 0.1, -0.4],
].map(unit);
test("the joint table is the model build's: 37 nodes, every kind, frozen", () => {
assert.equal(TIANGONG_JOINTS.length, 37);
const kinds = new Map();
for (const joint of TIANGONG_JOINTS) {
kinds.set(joint.kind, (kinds.get(joint.kind) ?? 0) + 1);
assert.ok(Object.isFrozen(joint) && Object.isFrozen(joint.pivot));
assert.equal(joint.pivot.length, 3);
assert.ok(Math.abs(Math.hypot(...joint.axis) - 1) < 1e-9, joint.node);
if (joint.kind === 'dock') assert.equal(joint.rangeDeg, null);
else assert.equal(joint.rangeDeg.length, 2);
}
// 2 Tianhe wings, 4 lab wings and 6 vehicle wings turn on alpha joints.
assert.deepEqual(Object.fromEntries(kinds), {
alpha: 12,
beta: 4,
antenna: 1,
dock: 6,
arm: 14,
});
assert.equal(tiangongJoint('CMM_EP').parent, 'CMM_SHP');
assert.throws(() => tiangongJoint('NOT_A_JOINT'));
});
test('a one-axis wing turns its cell side onto the Sun, as far as its axis allows', () => {
for (const wing of TIANGONG_ONE_AXIS_WINGS) {
assert.ok(Math.abs(dot(wing.axis, wing.normal)) < 1e-9, wing.node);
for (const sun of SUNS) {
const angle = tiangongOneAxisAngle(sun, wing);
const normal = rotate(wing.normal, wing.axis, angle);
// The best the wing can do: the Sun's part across its axis.
const reachable = Math.hypot(
dot(sun, wing.normal),
dot(sun, cross(wing.axis, wing.normal)),
);
if (reachable < 0.05) continue;
assert.ok(
Math.abs(dot(normal, sun) - reachable) < 1e-6,
`${wing.node} ${sun}`,
);
}
}
// The Sun along the axis: nothing to steer by, the last angle holds.
const tianhe = TIANGONG_ONE_AXIS_WINGS[0];
assert.equal(tiangongOneAxisAngle([1, 0, 0], tianhe, 0.7), 0.7);
});
test('a lab wing faces the Sun exactly: alpha across it, beta onto it', () => {
for (const pair of TIANGONG_TWO_AXIS_WINGS) {
const joint = {
alphaAxis: pair.alpha.axis,
betaAxis: pair.beta.axis,
normal: pair.normal,
};
for (const sun of SUNS) {
if (Math.abs(dot(sun, pair.alpha.axis)) > 0.95) continue;
const { alpha, beta } = tiangongTwoAxisAngles(sun, joint);
// The beta joint hangs from the alpha joint: beta turns first.
const normal = rotate(
rotate(pair.normal, pair.beta.axis, beta),
pair.alpha.axis,
alpha,
);
assert.ok(dot(normal, sun) > 1 - 1e-6, `${pair.alpha.node} ${sun}`);
const wingAxis = rotate(pair.beta.axis, pair.alpha.axis, alpha);
assert.ok(
Math.abs(dot(wingAxis, sun)) < 1e-6,
'wing axis across the Sun',
);
}
// Alpha keeps the half turn nearer its last answer.
const first = tiangongTwoAxisAngles(unit([0.2, 1, 0.3]), joint, 0);
const flipped = tiangongTwoAxisAngles(
unit([0.2, 1, 0.3]),
joint,
first.alpha + Math.PI,
);
assert.ok(Math.abs(Math.abs(flipped.alpha - first.alpha) - Math.PI) < 1e-9);
// Sun along the lab: alpha holds.
assert.equal(tiangongTwoAxisAngles([1, 0, 0], joint, 0.4).alpha, 0.4);
}
});
test("in the Earth's shadow every wing turns flat to the Earth, edge into the flight", () => {
const targets = tiangongWingTargets(unit([0.3, -0.9, 0.3]), false, {
one: TIANGONG_ONE_AXIS_WINGS.map(() => 3),
alpha: TIANGONG_TWO_AXIS_WINGS.map(() => 3),
});
TIANGONG_ONE_AXIS_WINGS.forEach((wing, i) => {
const normal = rotate(wing.normal, wing.axis, targets.one[i]);
assert.ok(Math.abs(normal[1] - 1) < 1e-9, wing.node);
});
TIANGONG_TWO_AXIS_WINGS.forEach((pair, i) => {
// The nearer half turn to 3 rad is ±π, with beta making up the rest.
assert.ok(Math.abs(Math.cos(targets.alpha[i]) + 1) < 1e-9, pair.alpha.node);
const normal = rotate(
rotate(pair.normal, pair.beta.axis, targets.beta[i]),
pair.alpha.axis,
targets.alpha[i],
);
assert.ok(Math.abs(normal[1] - 1) < 1e-9);
});
// Lit, the targets face the Sun instead.
const lit = tiangongWingTargets([0, 0, 1], true);
assert.ok(Math.abs(Math.abs(lit.one[0]) - Math.PI / 2) < 1e-9);
});
test('the antenna aims at Tianlian, not TDRS: unit vectors, highest first', () => {
assert.deepEqual([...TIANGONG_RELAY_LONGITUDES_DEG], [79.9, 171.04, 10.5]);
assert.notDeepEqual(
[...TIANGONG_RELAY_LONGITUDES_DEG],
[...ISS_RELAY_LONGITUDES_DEG],
);
// Over 80°E at 400 km: Tianlian II-01 is nearly overhead.
const lon = (79.9 * Math.PI) / 180;
const r = 6_771_000;
const position = [r * Math.cos(lon), r * Math.sin(lon), 0];
const axes = {
x: [-Math.sin(lon), Math.cos(lon), 0],
y: [0, 0, 1],
z: unit(position),
};
const directions = tiangongRelayDirections(position, axes);
assert.equal(directions.length, 3);
for (const d of directions) assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-9);
assert.ok(directions[0][1] > 0.999, 'II-01 overhead');
assert.ok(
directions[0][1] >= directions[1][1] &&
directions[1][1] >= directions[2][1],
);
assert.deepEqual(TIANGONG_HGA.axis, [0, 1, 0]);
});
test('the arms sway on one side of rest only, so they lift off the hull', () => {
for (const joints of Object.values(TIANGONG_ARMS)) {
assert.equal(joints.length, 7);
for (const joint of joints) {
if (!joint.sway) {
assert.equal(joint.centre, 0);
continue;
}
// The sway never crosses rest unless it is centred on it (wrist pitch).
assert.ok(
joint.centre === 0 || Math.abs(joint.centre) > joint.sway,
joint.node,
);
assert.ok(joint.period > 0);
}
}
});
test('the model file has every joint node, under its parent, with an identity rest', () => {
const glb = readFileSync(
new URL(`../../../public${TIANGONG_MODEL_URL}`, import.meta.url),
);
const jsonLength = glb.readUInt32LE(12);
const gltf = JSON.parse(glb.subarray(20, 20 + jsonLength).toString('utf8'));
const byName = new Map(gltf.nodes.map((node, index) => [node.name, index]));
const parentOf = new Map();
gltf.nodes.forEach((node, index) =>
(node.children ?? []).forEach((child) => parentOf.set(child, index)),
);
for (const joint of TIANGONG_JOINTS) {
const index = byName.get(joint.node);
assert.ok(index !== undefined, joint.node);
const node = gltf.nodes[index];
assert.equal(
gltf.nodes[parentOf.get(index)].name,
joint.parent,
joint.node,
);
if (joint.kind !== 'dock') {
assert.equal(node.translation ?? null, null, joint.node);
assert.equal(node.rotation ?? null, null, joint.node);
assert.equal(node.matrix ?? null, null, joint.node);
}
}
// Each wing's mesh is thin along the cell normal the rules assume.
const thin = (meshNode, normal) => {
const node = gltf.nodes[byName.get(meshNode)];
const accessor =
gltf.accessors[gltf.meshes[node.mesh].primitives[0].attributes.POSITION];
const size = [0, 1, 2].map((i) => accessor.max[i] - accessor.min[i]);
const along = normal.findIndex((c) => c !== 0);
assert.ok(
size[along] < Math.min(...size.filter((_, i) => i !== along)) / 3,
meshNode,
);
};
for (const wing of TIANGONG_ONE_AXIS_WINGS)
thin(wing.node.replace(/_ALPHA$/, ''), wing.normal);
for (const pair of TIANGONG_TWO_AXIS_WINGS)
thin(pair.beta.node.replace(/_BETA$/, ''), pair.normal);
});
+280
View File
@@ -0,0 +1,280 @@
/**
* Tiangong's joint and dock-marker nodes, as the model file carries them in
* each node's glTF `extras` (the model build's joints.json, copied here; the
* app reads this table, never the file's extras). Root frame, meters: glTF +X
* port, +Y zenith, +Z forward. Every driven joint is a node with an identity
* rest transform whose moving mesh hangs beneath it, so a turn of `angle` about
* `axis` through `pivot` is `issAxisMatrix(pivot, axis, angle)`, as for the ISS.
* `kind`: alpha (a wing's drive about its boom), beta (a lab wing's turn about
* its own axis, under its alpha), arm (the two robotic arms, seven joints
* each, base to tip), antenna (the high-gain dish, rest boresight +Y), dock (a
* docking port's outer face, not driven: `axis` is a docked vehicle's
* direction, `rangeDeg` null). `approximate` marks the model author's
* estimates against published dimensions.
* @type {ReadonlyArray<Readonly<{node: string, pivot: number[], axis: number[],
* kind: 'alpha'|'beta'|'arm'|'antenna'|'dock', rangeDeg: number[]|null,
* approximate: boolean, parent: string}>>}
*/
export const TIANGONG_JOINTS = Object.freeze(
[
[
'TIANHE_ARRAY_PORT_ALPHA',
[1.4, 0, -6.7],
[1, 0, 0],
'alpha',
[-180, 180],
false,
'tiangong',
],
[
'TIANHE_ARRAY_STBD_ALPHA',
[-1.4, 0, -6.7],
[-1, 0, 0],
'alpha',
[-180, 180],
false,
'tiangong',
],
[
'TIANHE_HGA',
[0, 2.4, -6],
[0, 1, 0],
'antenna',
[-90, 90],
true,
'tiangong',
],
['DOCK_FORWARD', [0, 0, 8.3], [0, 0, 1], 'dock', null, false, 'tiangong'],
['DOCK_AFT', [0, 0, -8.3], [0, 0, -1], 'dock', null, false, 'tiangong'],
['DOCK_NADIR', [0, -2, 6.4], [0, -1, 0], 'dock', null, true, 'tiangong'],
['DOCK_ZENITH', [0, 2, 6.4], [0, 1, 0], 'dock', null, true, 'tiangong'],
['BERTH_PORT', [2.1, 0, 6.4], [1, 0, 0], 'dock', null, true, 'tiangong'],
['BERTH_STBD', [-2.1, 0, 6.4], [-1, 0, 0], 'dock', null, true, 'tiangong'],
[
'WENTIAN_ARRAY_FWD_ALPHA',
[-18.9, 0, 6.9],
[-1, 0, 0],
'alpha',
[-180, 180],
false,
'tiangong',
],
[
'WENTIAN_ARRAY_FWD_BETA',
[-18.9, 0, 7.7],
[0, 0, 1],
'beta',
[-180, 180],
false,
'WENTIAN_ARRAY_FWD_ALPHA',
],
[
'WENTIAN_ARRAY_AFT_ALPHA',
[-18.9, 0, 5.9],
[-1, 0, 0],
'alpha',
[-180, 180],
false,
'tiangong',
],
[
'WENTIAN_ARRAY_AFT_BETA',
[-18.9, 0, 5.1],
[0, 0, -1],
'beta',
[-180, 180],
false,
'WENTIAN_ARRAY_AFT_ALPHA',
],
[
'MENGTIAN_ARRAY_FWD_ALPHA',
[18.9, 0, 6.9],
[1, 0, 0],
'alpha',
[-180, 180],
false,
'tiangong',
],
[
'MENGTIAN_ARRAY_FWD_BETA',
[18.9, 0, 7.7],
[0, 0, 1],
'beta',
[-180, 180],
false,
'MENGTIAN_ARRAY_FWD_ALPHA',
],
[
'MENGTIAN_ARRAY_AFT_ALPHA',
[18.9, 0, 5.9],
[1, 0, 0],
'alpha',
[-180, 180],
false,
'tiangong',
],
[
'MENGTIAN_ARRAY_AFT_BETA',
[18.9, 0, 5.1],
[0, 0, -1],
'beta',
[-180, 180],
false,
'MENGTIAN_ARRAY_AFT_ALPHA',
],
[
'CMM_SHR',
[0.5, 1.9, 3.6],
[0, 1, 0],
'arm',
[-270, 270],
true,
'tiangong',
],
[
'CMM_SHY',
[0.5, 2.3, 3.6],
[0, 0, 1],
'arm',
[-270, 270],
true,
'CMM_SHR',
],
[
'CMM_SHP',
[0.5, 2.7, 3.6],
[1, 0, 0],
'arm',
[-270, 270],
true,
'CMM_SHY',
],
[
'CMM_EP',
[0.5, 2.7, -0.9],
[1, 0, 0],
'arm',
[-270, 270],
true,
'CMM_SHP',
],
['CMM_WP', [0.5, 3.3, 3.6], [1, 0, 0], 'arm', [-270, 270], true, 'CMM_EP'],
['CMM_WY', [0.5, 3.3, 4.1], [0, 1, 0], 'arm', [-270, 270], true, 'CMM_WP'],
['CMM_WR', [0.5, 3.3, 4.6], [0, 0, 1], 'arm', [-270, 270], true, 'CMM_WY'],
[
'EMM_SHR',
[-6, 2.3, 6.4],
[0, 1, 0],
'arm',
[-270, 270],
true,
'tiangong',
],
[
'EMM_SHY',
[-6, 2.55, 6.4],
[1, 0, 0],
'arm',
[-270, 270],
true,
'EMM_SHR',
],
[
'EMM_SHP',
[-6, 2.85, 6.4],
[0, 0, 1],
'arm',
[-270, 270],
true,
'EMM_SHY',
],
['EMM_EP', [-8, 2.85, 6.4], [0, 0, 1], 'arm', [-270, 270], true, 'EMM_SHP'],
['EMM_WP', [-6, 3.2, 6.4], [0, 0, 1], 'arm', [-270, 270], true, 'EMM_EP'],
['EMM_WY', [-5.7, 3.2, 6.4], [0, 1, 0], 'arm', [-270, 270], true, 'EMM_WP'],
['EMM_WR', [-5.4, 3.2, 6.4], [1, 0, 0], 'arm', [-270, 270], true, 'EMM_WY'],
[
'SHENZHOU_FORWARD_ARRAY_PORT_ALPHA',
[1.4, 0, 15.1],
[1, 0, 0],
'alpha',
[-180, 180],
true,
'SHENZHOU_FORWARD',
],
[
'SHENZHOU_FORWARD_ARRAY_STBD_ALPHA',
[-1.4, 0, 15.1],
[-1, -0, -0],
'alpha',
[-180, 180],
true,
'SHENZHOU_FORWARD',
],
[
'SHENZHOU_NADIR_ARRAY_PORT_ALPHA',
[1.4, -8.8, 6.4],
[1, 0, 0],
'alpha',
[-180, 180],
true,
'SHENZHOU_NADIR',
],
[
'SHENZHOU_NADIR_ARRAY_STBD_ALPHA',
[-1.4, -8.8, 6.4],
[-1, -0, -0],
'alpha',
[-180, 180],
true,
'SHENZHOU_NADIR',
],
[
'TIANZHOU_AFT_ARRAY_PORT_ALPHA',
[1.4, 0, -16.6],
[1, 0, 0],
'alpha',
[-180, 180],
true,
'TIANZHOU_AFT',
],
[
'TIANZHOU_AFT_ARRAY_STBD_ALPHA',
[-1.4, 0, -16.6],
[-1, -0, -0],
'alpha',
[-180, 180],
true,
'TIANZHOU_AFT',
],
].map(([node, pivot, axis, kind, rangeDeg, approximate, parent]) =>
Object.freeze({
node,
pivot: Object.freeze(pivot),
axis: Object.freeze(axis),
kind,
rangeDeg: rangeDeg && Object.freeze(rangeDeg),
approximate,
parent,
}),
),
);
const BY_NODE = new Map(TIANGONG_JOINTS.map((joint) => [joint.node, joint]));
/**
* One joint by node name.
* @param {string} node
* @returns {(typeof TIANGONG_JOINTS)[number]}
*/
export function tiangongJoint(node) {
const joint = BY_NODE.get(node);
if (!joint) throw new Error(`Tiangong has no joint ${node}`);
return joint;
}
/** The visiting vehicles' mesh nodes; hiding one hides its arrays with it. */
export const TIANGONG_VEHICLE_NODES = Object.freeze([
'SHENZHOU_FORWARD',
'SHENZHOU_NADIR',
'TIANZHOU_AFT',
]);
+74
View File
@@ -0,0 +1,74 @@
import {
ISS_COMPANION_COARSE_M,
ISS_COMPANION_RADIUS_M,
ISS_COMPANION_SCAN_MS,
ISS_MODEL_LOCAL_AXES,
ISS_MODEL_MAX_DISTANCE_M,
ISS_MODEL_MIN_PX,
ISS_ORBIT_HIDE_M,
TIANGONG_CARD_CLEAR_M,
TIANGONG_MODEL_URL,
TIANGONG_NORAD,
} from './policy.js';
import { createStationModel } from './stationModel.js';
import { createTiangongArticulation } from './tiangongArticulation.js';
import { tiangongCockpitMount } from './tiangongMounts.js';
/**
* Whether a catalog entry at Tiangong is one of the station's own modules
* (CelesTrak lists them as "CSS (TIANHE)", "CSS (WENTIAN)", "CSS (MENGTIAN)")
* rather than a visiting Shenzhou or Tianzhou. A missing entry counts as a
* module.
* @param {number} noradId
* @param {{name?: string}|undefined} entry
* @returns {boolean}
*/
export function tiangongIsModule(noradId, entry) {
return (
noradId === TIANGONG_NORAD || /^CSS\s*\(/i.test(entry?.name ?? 'CSS (')
);
}
/**
* Tiangong as the station model factory describes it. The file is in meters
* (scale 1) and in the ISS file's frame, so it takes the ISS's local-axes
* mapping: the station is assumed to fly like the ISS, Tianhe along the
* velocity with the node (forward port) forward, the labs across the orbit,
* nadir to the Earth. Its joints are computed only; there is no telemetry.
* The Cockpit rides it from views on the model (`tiangongMounts.js`), and
* its ring follows the layer's orbit toggle like any tracked satellite's.
* @returns {import('./stationModel.js').StationModelSpec}
*/
export function tiangongModelSpec() {
return {
key: 'tiangong',
label: 'Tiangong', // i18n-ignore: the station's name, for log lines
norad: TIANGONG_NORAD,
modelUrl: TIANGONG_MODEL_URL,
scale: 1,
minPx: ISS_MODEL_MIN_PX,
maxDistanceM: ISS_MODEL_MAX_DISTANCE_M,
orbitHideM: ISS_ORBIT_HIDE_M,
cardClearM: TIANGONG_CARD_CLEAR_M,
companionRadiusM: ISS_COMPANION_RADIUS_M,
companionCoarseM: ISS_COMPANION_COARSE_M,
companionScanMs: ISS_COMPANION_SCAN_MS,
localAxes: ISS_MODEL_LOCAL_AXES,
isModule: tiangongIsModule,
createArticulation: createTiangongArticulation,
createTelemetry: null,
cockpitMount: tiangongCockpitMount,
// The Cockpit rides the station from a mount on the model, so the model
// stays while it does.
hideInCockpit: false,
syncOrbit: null,
};
}
/**
* Tiangong as a 3D model when the camera is close (stationModel.js).
* @param {{state: object, parts: object, resolveAsset?: (url: string) => string}} context
*/
export function createTiangongModel(context) {
return createStationModel(tiangongModelSpec(), context);
}
@@ -0,0 +1,125 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { issModelSpec } from './issModel.js';
import {
ISS_MODEL_LOCAL_AXES,
ISS_NORAD,
TIANGONG_MODEL_URL,
TIANGONG_NORAD,
} from './policy.js';
import { stationModelShouldShow } from './stationModel.js';
import { tiangongIsModule, tiangongModelSpec } from './tiangongModel.js';
test("Tiangong is CSS (TIANHE) by NORAD number, drawn at the file's meters", () => {
const spec = tiangongModelSpec();
assert.equal(TIANGONG_NORAD, 48274);
assert.equal(spec.norad, TIANGONG_NORAD);
assert.equal(spec.key, 'tiangong');
assert.equal(spec.scale, 1);
assert.equal(spec.modelUrl, TIANGONG_MODEL_URL);
// The same frame as the ISS file, so the same flight-axes mapping.
assert.equal(spec.localAxes, ISS_MODEL_LOCAL_AXES);
// No telemetry; Cockpit views on the model, so the model stays while the
// Cockpit rides it.
assert.equal(spec.createTelemetry, null);
assert.equal(typeof spec.cockpitMount, 'function');
assert.equal(spec.hideInCockpit, false);
assert.equal(spec.syncOrbit, null);
assert.equal(typeof spec.createArticulation().update, 'function');
});
test("the ISS spec keeps the ISS's own rules", () => {
const spec = issModelSpec({ parts: {} });
assert.equal(spec.norad, ISS_NORAD);
assert.equal(spec.key, 'iss');
assert.equal(spec.hideInCockpit, false);
assert.equal(typeof spec.cockpitMount, 'function');
assert.equal(typeof spec.createTelemetry, 'function');
assert.equal(typeof spec.syncOrbit, 'function');
});
test("the station's modules are CSS (…) entries; ships are vehicles", () => {
assert.equal(
tiangongIsModule(TIANGONG_NORAD, { name: 'CSS (TIANHE)' }),
true,
);
assert.equal(tiangongIsModule(53239, { name: 'CSS (WENTIAN)' }), true);
assert.equal(tiangongIsModule(54216, { name: 'CSS (MENGTIAN)' }), true);
assert.equal(tiangongIsModule(60000, { name: 'SHENZHOU-23 (SZ-23)' }), false);
assert.equal(tiangongIsModule(60001, { name: 'TIANZHOU-10' }), false);
assert.equal(
tiangongIsModule(60002, undefined),
true,
'unknown: not a vehicle',
);
});
test("a station hidden for the Cockpit stays hidden; the dot's rules otherwise", () => {
const shown = {
enabled: true,
showPoints: true,
hasStation: true,
classVisible: true,
tracked: false,
cockpitHidden: false,
};
assert.equal(stationModelShouldShow(shown), true);
assert.equal(
stationModelShouldShow({ ...shown, cockpitHidden: true }),
false,
);
assert.equal(stationModelShouldShow({ ...shown, hasStation: false }), false);
assert.equal(
stationModelShouldShow({ ...shown, classVisible: false, tracked: true }),
true,
);
});
test('the shipped asset is centred on the station, in meters, with its own textures', () => {
const glb = readFileSync(
new URL(`../../../public${TIANGONG_MODEL_URL}`, import.meta.url),
);
assert.equal(glb.toString('latin1', 0, 4), 'glTF');
const jsonLength = glb.readUInt32LE(12);
const gltf = JSON.parse(glb.subarray(20, 20 + jsonLength).toString('utf8'));
assert.deepEqual(gltf.scenes[0].nodes.length, 1);
const root = gltf.nodes[gltf.scenes[0].nodes[0]];
assert.equal(root.name, 'tiangong');
// The same compression and texture format as the ISS file.
assert.ok(gltf.extensionsUsed.includes('KHR_draco_mesh_compression'));
assert.ok(gltf.extensionsUsed.includes('EXT_texture_webp'));
assert.ok(gltf.textures.length > 0);
assert.equal(gltf.animations ?? undefined, undefined);
// Station extents (without the vehicles): 41.9 m across the lab wings,
// 57.2 m along the flight direction. The root puts their centre at the
// origin, so minimumPixelSize scales about the orbital position.
const vehicles = new Set([
'SHENZHOU_FORWARD',
'SHENZHOU_NADIR',
'TIANZHOU_AFT',
]);
const min = [Infinity, Infinity, Infinity];
const max = [-Infinity, -Infinity, -Infinity];
const visit = (index) => {
const node = gltf.nodes[index];
if (vehicles.has(node.name)) return;
const offset = node.translation ?? [0, 0, 0];
for (const primitive of gltf.meshes[node.mesh]?.primitives ?? []) {
const accessor = gltf.accessors[primitive.attributes.POSITION];
for (let i = 0; i < 3; i++) {
min[i] = Math.min(min[i], accessor.min[i] + offset[i]);
max[i] = Math.max(max[i], accessor.max[i] + offset[i]);
}
}
(node.children ?? []).forEach(visit);
};
root.children.forEach(visit);
assert.ok(Math.abs(max[0] - min[0] - 41.9) < 0.1, `X ${max[0] - min[0]}`);
assert.ok(Math.abs(max[2] - min[2] - 57.2) < 0.1, `Z ${max[2] - min[2]}`);
for (let i = 0; i < 3; i++)
assert.ok(
Math.abs((min[i] + max[i]) / 2 + root.translation[i]) < 0.05,
`centre ${i}`,
);
});
+156
View File
@@ -0,0 +1,156 @@
import { TIANGONG_NORAD } from './policy.js';
import {
issMountView,
issMountWorld,
issNextMountView,
issPreviousMountView,
} from './issMounts.js';
/**
* The Cockpit's views from Tiangong, as `issMounts.js` gives the ISS's: a
* place on the model (`eye`, metres on the model's axes: port, zenith,
* forward) and where it looks (`forward`, `up`). The model is the layer's
* own build (`public/models/README.md`): Tianhe along the forward axis with
* the node at its forward end, Wentian and Mengtian out to either side of
* the node, a Shenzhou on the forward and nadir ports and a Tianzhou aft.
* The views are from the modules the catalog lists (CSS (TIANHE), CSS
* (WENTIAN), CSS (MENGTIAN)) and from the docked vehicle, so each rides an
* entry of its own; Tiangong needs no cards.
*/
export const TIANGONG_WENTIAN_NORAD = 53239;
export const TIANGONG_MENGTIAN_NORAD = 54216;
const mount = (eye, forward, up) =>
Object.freeze({
eye: Object.freeze(eye),
forward: Object.freeze(forward),
up: Object.freeze(up),
});
export const TIANGONG_MOUNTS = Object.freeze({
/**
* Tianhe lies along the station's long axis, its wings at the aft end:
* from the top of the hull just forward of the wing roots, looking ahead
* along the station to the node and the two labs across it, the Earth
* below.
*/
tianhe: mount([0, 3.0, -3], [0, -0.4, 0.92], [0, 1, 0]),
/**
* Wentian reaches out from the node on the model's starboard side: from
* the top of its outer end, looking out past its wings and down, the
* arrays turning through the view as they follow the Sun.
*/
wentian: mount([-14, 2.9, 6.4], [-0.8, -0.5, 0.3], [0, 1, 0]),
/** Mengtian, the same on the port side. */
mengtian: mount([14, 2.9, 6.4], [0.8, -0.5, 0.3], [0, 1, 0]),
/**
* A docked vehicle (a Shenzhou, a Tianzhou): the catalog does not say
* which port it is on, so it takes the place of the Tianzhou on the aft
* port: looking out behind the station and down, the Earth falling away.
*/
docked: mount([2.4, 0.5, -13], [0, -0.5, -0.87], [0, 1, 0]),
});
export const TIANGONG_MOUNT_ORDER = Object.freeze([
'tianhe',
'wentian',
'mengtian',
'docked',
]);
/**
* The views on offer, in order, each with the name it is shown under and
* the catalog entry it rides: the modules whenever the station is drawn
* (with no entry to ride when the catalog lacks one), the docked vehicle
* only when there is one.
* @param {{tianheName?: string|null, wentianName?: string|null,
* mengtianName?: string|null, dockedName?: string|null,
* tianheNorad?: number|null, wentianNorad?: number|null,
* mengtianNorad?: number|null, dockedNorad?: number|null}} [input]
* @returns {Array<{key: 'tianhe'|'wentian'|'mengtian'|'docked',
* label: string, noradId: number|null, card: null}>}
*/
export function tiangongMountViews({
tianheName,
wentianName,
mengtianName,
dockedName,
tianheNorad = null,
wentianNorad = null,
mengtianNorad = null,
dockedNorad = null,
} = {}) {
const labels = {
tianhe: tiangongMountLabel(tianheName) || 'TIANHE',
wentian: tiangongMountLabel(wentianName) || 'WENTIAN',
mengtian: tiangongMountLabel(mengtianName) || 'MENGTIAN',
docked: tiangongMountLabel(dockedName),
};
const entries = {
tianhe: tianheNorad,
wentian: wentianNorad,
mengtian: mengtianNorad,
docked: dockedNorad,
};
return TIANGONG_MOUNT_ORDER.filter((key) => labels[key]).map((key) => ({
key,
label: labels[key],
noradId: Number.isFinite(entries[key]) ? entries[key] : null,
card: null,
}));
}
/**
* A view's name from its entry's catalog name, without the "CSS (…)" the
* catalog wraps the station's modules in.
* @param {string|null|undefined} name
* @returns {string}
*/
export function tiangongMountLabel(name) {
const text = String(name ?? '').trim();
const inner = /^CSS\s*\((.+)\)$/i.exec(text);
return (inner ? inner[1] : text).trim();
}
/**
* The station model spec's `cockpitMount` for Tiangong: the view asked for
* (the first when none is, or it is not on offer), in the world.
* @param {{key: string|null, centre: {x:number,y:number,z:number},
* axes: {x:number[], y:number[], z:number[]},
* name: (noradId: number|null) => string|null,
* entry: (noradId: number|null) => number|null,
* dockedVehicle: number|null}} input
* @returns {object}
*/
export function tiangongCockpitMount({
key,
centre,
axes,
name,
entry,
dockedVehicle,
}) {
const views = tiangongMountViews({
tianheName: name(TIANGONG_NORAD),
wentianName: name(TIANGONG_WENTIAN_NORAD),
mengtianName: name(TIANGONG_MENGTIAN_NORAD),
dockedName: name(dockedVehicle),
tianheNorad: entry(TIANGONG_NORAD),
wentianNorad: entry(TIANGONG_WENTIAN_NORAD),
mengtianNorad: entry(TIANGONG_MENGTIAN_NORAD),
dockedNorad: entry(dockedVehicle),
});
const view = issMountView(views, key);
return {
...issMountWorld(TIANGONG_MOUNTS[view.key], centre, axes),
key: view.key,
label: view.label,
noradId: view.noradId,
card: view.card,
views,
};
}
export { issNextMountView as tiangongNextMountView };
export { issPreviousMountView as tiangongPreviousMountView };
@@ -0,0 +1,127 @@
// src/layers/satellites/tiangongMounts.test.mjs — the Cockpit's views from
// Tiangong: offered in order from the modules the catalog lists and the
// docked vehicle, each riding its own entry, placed on the model's axes.
import assert from 'node:assert/strict';
import test from 'node:test';
import { TIANGONG_NORAD } from './policy.js';
import {
TIANGONG_MENGTIAN_NORAD,
TIANGONG_MOUNT_ORDER,
TIANGONG_MOUNTS,
TIANGONG_WENTIAN_NORAD,
tiangongCockpitMount,
tiangongMountLabel,
tiangongMountViews,
} from './tiangongMounts.js';
const summary = (views) =>
views.map(({ key, label, noradId }) => ({ key, label, noradId }));
test('the station offers its views in order, Tianhe first', () => {
assert.deepEqual(
[...TIANGONG_MOUNT_ORDER],
['tianhe', 'wentian', 'mengtian', 'docked'],
);
for (const key of TIANGONG_MOUNT_ORDER) assert.ok(TIANGONG_MOUNTS[key]);
assert.equal(
new Set([TIANGONG_NORAD, TIANGONG_WENTIAN_NORAD, TIANGONG_MENGTIAN_NORAD])
.size,
3,
);
const views = tiangongMountViews({
tianheName: 'CSS (TIANHE)',
wentianName: 'CSS (WENTIAN)',
mengtianName: 'CSS (MENGTIAN)',
dockedName: 'SHENZHOU-23 (SZ-23)',
tianheNorad: TIANGONG_NORAD,
wentianNorad: TIANGONG_WENTIAN_NORAD,
mengtianNorad: TIANGONG_MENGTIAN_NORAD,
dockedNorad: 69180,
});
assert.deepEqual(summary(views), [
{ key: 'tianhe', label: 'TIANHE', noradId: TIANGONG_NORAD },
{ key: 'wentian', label: 'WENTIAN', noradId: TIANGONG_WENTIAN_NORAD },
{ key: 'mengtian', label: 'MENGTIAN', noradId: TIANGONG_MENGTIAN_NORAD },
{ key: 'docked', label: 'SHENZHOU-23 (SZ-23)', noradId: 69180 },
]);
// Every view rides a catalog entry: no cards.
assert.ok(views.every((view) => view.card === null));
// No vehicle docked: no view from one. The modules are part of the model,
// so they are offered even when the catalog has no entry for them.
assert.deepEqual(summary(tiangongMountViews()), [
{ key: 'tianhe', label: 'TIANHE', noradId: null },
{ key: 'wentian', label: 'WENTIAN', noradId: null },
{ key: 'mengtian', label: 'MENGTIAN', noradId: null },
]);
});
test('the view is named after the entry, without the catalog’s "CSS (…)"', () => {
assert.equal(tiangongMountLabel('CSS (WENTIAN)'), 'WENTIAN');
assert.equal(tiangongMountLabel('TIANZHOU-10'), 'TIANZHOU-10');
assert.equal(tiangongMountLabel(null), '');
});
test('every mount is outside the hull, with a usable view frame', () => {
for (const key of TIANGONG_MOUNT_ORDER) {
const { eye, forward, up } = TIANGONG_MOUNTS[key];
// Tianhe and the labs are 4.2 m across: no eye inside them (2.1 m of an
// axis), and none far from the station (the labs reach ~20 m out).
const offAxis = Math.hypot(eye[0], eye[1]);
const offLab = Math.hypot(eye[1], eye[2] - 6.4);
assert.ok(offAxis > 2.1 || offLab > 2.1, `${key} sits inside a module`);
assert.ok(Math.hypot(...eye) < 40, `${key} is off the station`);
assert.ok(Math.hypot(...forward) > 0.9, `${key} looks somewhere`);
assert.ok(Math.hypot(...up) > 0.9, `${key} has an up`);
assert.ok(forward[1] < 0, `${key} looks down at the Earth`);
}
});
test('the spec’s mount gives the view asked for in the world, else the first', () => {
const centre = { x: 6_780_000, y: 0, z: 0 };
// The model's axes in the world: port = +y, zenith = +x (away from the
// Earth), forward = +z.
const axes = { x: [0, 0, 1], y: [0, 1, 0], z: [1, 0, 0] };
const names = new Map([
[TIANGONG_NORAD, 'CSS (TIANHE)'],
[TIANGONG_WENTIAN_NORAD, 'CSS (WENTIAN)'],
[69180, 'SHENZHOU-23 (SZ-23)'],
]);
const input = {
centre,
axes,
name: (id) => names.get(id) ?? null,
entry: (id) => (names.has(id) ? id : null),
dockedVehicle: 69180,
};
const first = tiangongCockpitMount({ ...input, key: null });
assert.equal(first.key, 'tianhe');
// The modules are 4.2 m across: no eye inside Tianhe (2.1 m of its axis).
assert.ok(
Math.hypot(TIANGONG_MOUNTS.tianhe.eye[0], TIANGONG_MOUNTS.tianhe.eye[1]) >
2.1,
);
assert.equal(first.noradId, TIANGONG_NORAD);
assert.deepEqual(
first.views.map((view) => view.key),
['tianhe', 'wentian', 'mengtian', 'docked'],
);
// Tianhe's eye is 3 m above the hull (+x in the world), 3 m aft (−z).
assert.ok(Math.abs(first.position.y) < 1e-9);
assert.ok(Math.abs(first.position.x - (6_780_000 + 3.0)) < 1e-9);
assert.ok(Math.abs(first.position.z + 3) < 1e-9);
assert.ok(first.direction.z > 0.9, 'looks ahead along the station');
assert.ok(first.direction.x < 0, 'and down');
const docked = tiangongCockpitMount({ ...input, key: 'docked' });
assert.equal(docked.key, 'docked');
assert.equal(docked.noradId, 69180);
assert.equal(docked.label, 'SHENZHOU-23 (SZ-23)');
assert.ok(docked.direction.z < -0.8, 'looks behind the station');
const unknown = tiangongCockpitMount({ ...input, key: 'cupola' });
assert.equal(unknown.key, 'tianhe', 'a view not on offer gives the first');
// The frame is unit and square.
const d = docked.direction;
const u = docked.up;
assert.ok(Math.abs(Math.hypot(d.x, d.y, d.z) - 1) < 1e-9);
assert.ok(Math.abs(Math.hypot(u.x, u.y, u.z) - 1) < 1e-9);
assert.ok(Math.abs(d.x * u.x + d.y * u.y + d.z * u.z) < 1e-9);
});
+141
View File
@@ -0,0 +1,141 @@
import { msg } from '../../i18n/index.js';
import { issCommandFastOrbit } from './issCommand.js';
import { ISS_ARM_LABELS, ISS_SUN_POSES } from './issStation.js';
import { TIANGONG_NORAD } from './policy.js';
import { trackedStation } from './stationModels.js';
import {
TIANGONG_ARMS,
TIANGONG_ONE_AXIS_WINGS,
TIANGONG_TWO_AXIS_WINGS,
} from './tiangongArticulation.js';
/** The lab wings' slider labels, per TIANGONG_TWO_AXIS_WINGS entry. */
const LAB_WING_LABELS = [
[msg('Wentian forward · alpha'), msg('Wentian forward · beta')],
[msg('Wentian aft · alpha'), msg('Wentian aft · beta')],
[msg('Mengtian forward · alpha'), msg('Mengtian forward · beta')],
[msg('Mengtian aft · alpha'), msg('Mengtian aft · beta')],
];
/**
* Tiangong as the STATION section describes it (stationPanel.js): its joint
* driver from the model part, computed values only (China publishes no
* telemetry), and the Manual controls: the Sun's position or a fast orbit,
* and the two arms posed by joint.
* @param {{state: object, parts: object}} context
* @returns {import('./stationPanel.js').StationDescription}
*/
export function tiangongStationDescription({ state: layerState, parts }) {
const model = () => parts.tiangongModel ?? null;
const armGroup = (id, label, joints) => ({
id,
label,
kind: 'sliders',
resume: msg('Resume sway'),
sliders: joints.map((joint, i) => ({
id: joint.node,
label: ISS_ARM_LABELS[i],
min: -120,
max: 120,
apply: (a, value) =>
a.setJoint(
joint.node,
joint.pivot,
joint.axis,
(value * Math.PI) / 180,
),
})),
resumeApply: (a) => a.resumeArm(id),
});
// Every wing has a joint of its own, so each can be set apart from the
// others; a wing not touched keeps following the Sun.
const wingSlider = (joint, label) => ({
id: joint.node,
label,
min: -180,
max: 180,
apply: (a, value) => a.setWingAngle(joint.node, (value * Math.PI) / 180),
});
const wingGroup = (id, label, sliders) => ({
id,
label,
kind: 'sliders',
resume: msg('Follow the Sun'),
sliders,
resumeApply: (a) => a.resumeWings(),
});
const tianheWings = wingGroup('tianhe-wings', msg('Tianhe wings (degrees)'), [
wingSlider(TIANGONG_ONE_AXIS_WINGS[0], msg('Port wing')),
wingSlider(TIANGONG_ONE_AXIS_WINGS[1], msg('Starboard wing')),
]);
const labWings = wingGroup(
'lab-wings',
msg('Lab wings (degrees)'),
TIANGONG_TWO_AXIS_WINGS.flatMap((pair, i) => [
wingSlider(pair.alpha, LAB_WING_LABELS[i][0]),
wingSlider(pair.beta, LAB_WING_LABELS[i][1]),
]),
);
return {
key: 'tiangong',
title: 'Tiangong', // i18n-ignore: the station's name
selected: () => trackedStation(layerState, parts)?.norad === TIANGONG_NORAD,
subjectName: () =>
layerState._catalog.get(layerState._trackedNorad)?.name?.trim() ||
`Tiangong · NORAD ${TIANGONG_NORAD}`,
articulation: () => model()?._articulation ?? null,
// No feed exists: the status line says so instead of waiting for one.
telemetry: () => ({ state: 'none', poseAgeMs: null, liveUntilMs: null }),
position: () =>
model()?._visualPosition?.() ??
layerState._trackedFrameCartesian ??
parts.rendering?._pointPosition?.(TIANGONG_NORAD) ??
null,
zoomLabel: msg('Zoom to Tiangong'),
notes: {
computed: msg(
'Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.',
),
},
groups: [
{
id: 'sun',
label: msg('Sun position'),
kind: 'choices',
choices: [
{
id: 'follow',
label: msg('Follow the Sun'),
isDefault: true,
apply: (a) => a.setOverride(null),
},
...ISS_SUN_POSES.map(({ id, label, sun, sunlit }) => ({
id,
label,
apply: (a) => {
const fixed = { sun, sunlit };
a.setOverride(() => fixed);
},
})),
{
id: 'orbit',
label: msg('Fast orbit (40 s)'),
apply: (a) => {
const start = Date.now();
a.setOverride((nowMs) => issCommandFastOrbit(nowMs - start));
},
},
],
},
tianheWings,
labWings,
armGroup('cmm', msg('Tianhe arm (degrees)'), TIANGONG_ARMS.cmm),
armGroup('emm', msg('Wentian arm (degrees)'), TIANGONG_ARMS.emm),
],
automatic: (a) => {
a.setOverride(null);
a.resumeWings();
a.resumeArm();
},
};
}
@@ -0,0 +1,179 @@
// src/layers/satellites/tiangongStation.test.mjs — Tiangong's STATION
// description: every wing can be set apart from the others, and Automatic
// hands them all back to the Sun.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
createTiangongArticulation,
TIANGONG_ONE_AXIS_WINGS,
TIANGONG_TWO_AXIS_WINGS,
} from './tiangongArticulation.js';
import { issAxisMatrix } from './issArticulation.js';
import { tiangongStationDescription } from './tiangongStation.js';
import { TIANGONG_NORAD } from './policy.js';
function recordingArticulation() {
const calls = [];
return {
calls,
setOverride: (fn) => calls.push(['override', fn === null ? null : 'fn']),
setJoint: (node, pivot, axis, angle) => calls.push(['joint', node, angle]),
resumeArm: (key) => calls.push(['resumeArm', key ?? null]),
setWingAngle: (node, angle) => calls.push(['wing', node, angle]),
resumeWings: () => calls.push(['resumeWings']),
};
}
function description() {
const layerState = {
_trackedNorad: TIANGONG_NORAD,
_catalog: new Map([[TIANGONG_NORAD, { name: 'CSS (TIANHE)' }]]),
_points: new Map(),
_trackedFrameCartesian: null,
};
const parts = { tiangongModel: { _articulation: null } };
return tiangongStationDescription({ state: layerState, parts });
}
test('the description offers one slider per wing joint: two on Tianhe, eight on the labs', () => {
const d = description();
const tianhe = d.groups.find((g) => g.id === 'tianhe-wings');
const labs = d.groups.find((g) => g.id === 'lab-wings');
assert.equal(tianhe.kind, 'sliders');
assert.deepEqual(
tianhe.sliders.map((s) => s.id),
TIANGONG_ONE_AXIS_WINGS.slice(0, 2).map((w) => w.node),
);
assert.equal(labs.sliders.length, 8);
assert.deepEqual(
labs.sliders.map((s) => s.id),
TIANGONG_TWO_AXIS_WINGS.flatMap((p) => [p.alpha.node, p.beta.node]),
);
const labels = new Set(labs.sliders.map((s) => s.label));
assert.equal(labels.size, 8, 'every lab slider has a label of its own');
for (const slider of [...tianhe.sliders, ...labs.sliders]) {
assert.equal(slider.min, -180);
assert.equal(slider.max, 180);
}
// The arms are still there, after the wings.
assert.deepEqual(
d.groups.map((g) => g.id),
['sun', 'tianhe-wings', 'lab-wings', 'cmm', 'emm'],
);
});
test('a wing slider sets that wing alone, in radians; the group resume frees them all', () => {
const d = description();
const a = recordingArticulation();
const labs = d.groups.find((g) => g.id === 'lab-wings');
labs.sliders[3].apply(a, 90);
assert.deepEqual(a.calls, [['wing', labs.sliders[3].id, Math.PI / 2]]);
labs.resumeApply(a);
assert.deepEqual(a.calls.at(-1), ['resumeWings']);
assert.equal(labs.resume, 'Follow the Sun');
});
test('Automatic hands the Sun, the wings and the arms back', () => {
const d = description();
const a = recordingArticulation();
d.automatic(a);
assert.deepEqual(a.calls, [
['override', null],
['resumeWings'],
['resumeArm', null],
]);
});
/** A stand-in model whose nodes keep the last matrix written. */
function fakeModel() {
const nodes = new Map();
return {
ready: true,
nodes,
getNode(name) {
// Cesium's node clones the matrix it is given; the driver writes a
// shared scratch matrix, so the stand-in must clone too.
if (!nodes.has(name))
nodes.set(name, {
_matrix: null,
get matrix() {
return this._matrix;
},
set matrix(value) {
this._matrix = Cesium.Matrix4.clone(value);
},
});
return nodes.get(name);
},
};
}
test('the driver holds a wing set by hand at its angle while the others follow the Sun', () => {
const driver = createTiangongArticulation();
const model = fakeModel();
const date = new Date('2026-11-13T12:00:00Z');
const position = new Cesium.Cartesian3(6_780_000, 0, 0);
const axes = { x: [0, 1, 0], y: [0, 0, 1], z: [1, 0, 0] };
// A fixed Sun: the real one would fetch Cesium's Earth-orientation data.
const fixed = { sun: [0, 0.6, 0.8], sunlit: true };
driver.setOverride(() => fixed);
driver.update(model, date, position, axes, 1000);
const port = TIANGONG_ONE_AXIS_WINGS[0];
const starboard = TIANGONG_ONE_AXIS_WINGS[1];
const portBefore = Cesium.Matrix4.clone(model.getNode(port.node).matrix);
const starboardBefore = Cesium.Matrix4.clone(
model.getNode(starboard.node).matrix,
);
driver.setWingAngle(port.node, 1.2);
// Long after the last frame: the step is not rate-limited.
driver.update(model, date, position, axes, 11_000);
const expected = issAxisMatrix(
port.pivot,
port.axis,
1.2,
new Cesium.Matrix4(),
);
assert.ok(
Cesium.Matrix4.equalsEpsilon(
model.getNode(port.node).matrix,
expected,
1e-9,
),
'the port wing is at the set angle',
);
assert.ok(
Cesium.Matrix4.equalsEpsilon(
model.getNode(starboard.node).matrix,
starboardBefore,
1e-9,
),
'the starboard wing kept its Sun angle (same Sun, same date)',
);
assert.equal(
Cesium.Matrix4.equals(model.getNode(port.node).matrix, portBefore),
false,
'the set angle differs from the Sun angle',
);
driver.resumeWings();
driver.update(model, date, position, axes, 21_000);
assert.ok(
Cesium.Matrix4.equalsEpsilon(
model.getNode(port.node).matrix,
portBefore,
1e-9,
),
'back to the Sun once freed',
);
// Null frees one wing on its own.
driver.setWingAngle(port.node, 0.3);
driver.setWingAngle(port.node, null);
driver.update(model, date, position, axes, 31_000);
assert.ok(
Cesium.Matrix4.equalsEpsilon(
model.getNode(port.node).matrix,
portBefore,
1e-9,
),
);
});
+68 -6
View File
@@ -1,19 +1,21 @@
import { cameraOf } from '../../render/rendererOf.js';
import { entityFollowTarget, stopFollowing } from '../../data/followed.js';
import { satelliteClassText } from '../../data/satelliteClass.js';
import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { clone, scale } from '../../geo/vector.js';
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import { clone, distance, scale } from '../../geo/vector.js';
import { t } from '../../i18n/index.js';
import { formatQuantity, unitLabel } from '../../ui/unitLabels.js';
import {
ISS_NORAD,
CONTEXT_REFRESH_INTERVAL_MS,
HIGH_ORBIT_ALTITUDE_M,
ISS_NORAD,
STATIONS,
TRACK_VIEW_FROM_HIGH_SCALE,
TRACK_VIEW_FROM_LEO,
TRACKED_ORBIT_COLOR,
} from './policy.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { modelFor } from './stationModels.js';
export function createTracking({ state: layerState, services, parts, source }) {
const { clearFocusTarget } = services.focus;
@@ -118,6 +120,8 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedEntity = null;
}
layerState._trackedNorad = null;
layerState._trackedDockedToStation = null;
layerState._trackedDockedToIss = false;
parts.controls._syncIssOrbit?.();
// A held Cockpit subject that stops being tracked gets its marks back.
if (layerState._cockpitSubjectNorad !== null)
@@ -384,11 +388,27 @@ export function createTracking({ state: layerState, services, parts, source }) {
: t('DOCKED · {name}', { name: companions[0] }),
);
}
// While a station's model shows, the card keeps clear of it: the gap
// follows the station's size on screen, in steps so the card is not
// republished every frame.
const clearPx =
modelFor(parts, layerState._trackedNorad)?._cardClearPx?.() ?? null;
const current = readEntityRecord(layerState._trackedEntity)?.labelModel;
// The overlay's gap is twice the anchor radius, so half the clearance,
// in 4 px steps. The step kept stands until the clearance has moved a
// pixel past the step's edge: at an edge, sub-pixel jitter in the range
// would otherwise flip it, and republish the card, every frame.
const kept = current?.anchorRadiusPx ?? null;
const anchorRadiusPx = !clearPx
? null
: kept !== null && Math.abs(clearPx / 2 - kept) < 3
? kept
: Math.round(clearPx / 8) * 4;
// Compare the WHOLE detail array: comparing only `details[0]` swallowed any
// change confined to the companions line, so the card would never republish.
const unchanged =
current?.title === title &&
(current?.anchorRadiusPx ?? null) === anchorRadiusPx &&
current?.details?.length === details.length &&
details.every((line, index) => current.details[index] === line);
if (unchanged) return;
@@ -396,10 +416,38 @@ export function createTracking({ state: layerState, services, parts, source }) {
title,
details,
accent: '#ffd84d',
...(anchorRadiusPx ? { anchorRadiusPx, anchorRadiusScale: null } : {}),
};
refreshTrackedReadout(layerState._trackedEntity);
}
/**
* The station a satellite is docked to: both orbits, propagated to one
* instant, within the station's companion radius (dots are moved at
* different moments, so their spacing cannot say). A station is docked to
* nothing, and the dense group never is.
* @param {number} noradId
* @returns {number|null} The station's NORAD number, or null.
*/
function _dockedToStation(noradId) {
if (STATIONS.some((station) => station.norad === noradId)) return null;
const sat = layerState._catalog.get(noradId);
if (!sat?.satrec || sat.group === 'dense') return null;
const date = new Date(layerState.now());
const at = (p) => fromDegrees(p.longitude, p.latitude, p.altitude);
let own = null;
for (const station of STATIONS) {
const entry = layerState._catalog.get(station.norad);
if (!entry?.satrec) continue;
own ??= parts.orbits.propagatePosition(sat.satrec, date);
if (!own) return null;
const there = parts.orbits.propagatePosition(entry.satrec, date);
if (there && distance(at(own), at(there)) <= station.companionRadiusM)
return station.norad;
}
return null;
}
function _trackSatellite(noradId, { origin = 'programmatic' } = {}) {
_clearTracking(false, { origin });
@@ -414,9 +462,18 @@ export function createTracking({ state: layerState, services, parts, source }) {
// Hide the dot — the tracked dot draws it, larger and over everything.
parts.rendering._hidePoint(noradId);
// Show orbital path
parts.rendering._showOrbitPath(noradId, TRACKED_ORBIT_COLOR);
if (noradId === ISS_NORAD) parts.controls._syncIssOrbit?.();
// Show orbital path. An object docked to the ISS (Nauka, a Progress…)
// flies the station's orbit under elements of its own: its ring would
// run beside the ISS's, a second line through the same station. The
// ISS's ring stands for it instead. Another station's ring is drawn only
// while that station is tracked, so its docked objects keep their own.
layerState._trackedDockedToStation = _dockedToStation(noradId);
layerState._trackedDockedToIss =
layerState._trackedDockedToStation === ISS_NORAD;
if (!layerState._trackedDockedToIss)
parts.rendering._showOrbitPath(noradId, TRACKED_ORBIT_COLOR);
if (noradId === ISS_NORAD || layerState._trackedDockedToIss)
parts.controls._syncIssOrbit?.();
// The tracked position propagates per evaluation through the per-frame
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.
@@ -453,6 +510,11 @@ export function createTracking({ state: layerState, services, parts, source }) {
entityRecord(layerState._trackedEntity).trackedId = `satellites:${noradId}`;
entityRecord(layerState._trackedEntity).displayPosition =
_trackedDisplayCached;
// Up close a station is a 3D model: the card welds to where it is drawn.
// So does the card of an object docked to it, which the model stands in
// for.
entityRecord(layerState._trackedEntity).visualPosition = () =>
modelFor(parts, noradId)?._visualPosition?.() ?? null;
_updateTrackedSatelliteLabelModel(initialPos?.altitude ?? null);
const dotPosition = parts.rendering._pointPosition(noradId);
+17
View File
@@ -5,6 +5,7 @@ import { createCredits } from './credits.js';
import { createPickRouter } from './pickRouter.js';
import { createSelection } from './selection.js';
import { createViewerHost } from './viewerHost.js';
import { subscribePhotoViewers } from './photoViewers.js';
import { filtersOf, requiresKeyIdFor, validateProviders } from './registry.js';
import { normalizeFilter, resolveFilter, sameFilter } from './filter.js';
import { worldTimeFor } from '../../time/worldClock.js';
@@ -703,6 +704,22 @@ export function createStreetLevelLayer({
attachViewerHost(element) {
parts.viewerHost.attach(element);
},
/**
* Receive every presentation of the photo viewer the providers whose
* photos are plain files (KartaView, Panoramax) mount in the viewer
* host, the one mounted last (see photoViewers.js), starting with the
* current one; null while none is mounted. A view draws it (see
* photoViewer.js); with nobody subscribed, those providers' photos
* cannot open.
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
subscribePhotoViewer(listener) {
return subscribePhotoViewers(
[...state.providers.values()].map((entry) => entry.instance.viewer),
listener,
);
},
setProviderEnabled,
openImage,
/**
+38
View File
@@ -2176,3 +2176,41 @@ test('proceed() is asked after the lookup: false loads nothing and clears the sp
true,
);
});
test('subscribePhotoViewer hands on the photo viewer a provider presents, the later mount’s while two overlap', async (t) => {
const presenting = (id, pickPrefix) => {
const provider = fakeProvider({ id, pickPrefix });
const create = provider.create;
const listeners = new Set();
provider.present = (view) => {
for (const listener of [...listeners]) listener(view);
};
provider.create = (context) => {
const instance = create(context);
instance.viewer.subscribeView = (listener) => {
listeners.add(listener);
listener(null);
return () => listeners.delete(listener);
};
return instance;
};
return provider;
};
const a = presenting('mapillary', 'mly:');
const b = presenting('other', 'oth:');
const { layer } = await enabledLayer(t, [a, b]);
const shown = [];
const unsubscribe = layer.subscribePhotoViewer((view) => shown.push(view));
assert.deepEqual(shown, [null], 'the current one first');
const supersede = () => {};
const viewA = { host: 'a', mountKey: 1, actions: { supersede } };
const viewB = { host: 'b', mountKey: 2, actions: { supersede } };
a.present(viewA);
b.present(viewB);
a.present(null);
b.present(null);
assert.deepEqual(shown, [null, viewA, viewB, null]);
unsubscribe();
a.present(viewA);
assert.equal(shown.length, 4, 'unsubscribed');
});
+296 -85
View File
@@ -4,8 +4,14 @@ import {
wrapDegrees,
} from './panorama.js';
import { imageSize } from './imageSize.js';
import { nextViewKey } from './photoViewers.js';
import { msg, t } from '../../i18n/index.js';
// Each mount's and each canvas's key comes from `nextViewKey()`, never
// reused by any viewer: a view that sees one viewer unmount and another
// mount in the same tick still draws them fresh elements (a destroyed
// renderer leaves its canvas's context lost).
/**
* EXPAND puts the viewer's wrap full screen, or (iPhone) opens it as a
* popover. Each is tried on its own: a browser that cannot parse one
@@ -151,6 +157,16 @@ async function loadBitmap(url, timeoutMs, resize, failure, signal) {
}
}
/**
* Unmounted, superseded or left without a view before the view drew what
* was waiting on it (`undrawn`): a mount or an open that fails as closed.
*/
function undrawn() {
return Object.assign(new Error('Street-level viewer was closed'), {
undrawn: true,
});
}
/**
* A picture refused for its size (`tooLarge`): the viewer will not load
* that file another way, an <img> having no size limit at all.
@@ -213,6 +229,28 @@ export function panoSizeFor(canvasPixels, fovDeg) {
* or pinch to zoom), and ‹ › to step along the sequence (also ← →). Poses
* follow the view direction.
*
* The adapter draws nothing itself. It presents the viewer through
* `subscribeView()` (the street-level layer's `subscribePhotoViewer()`): a
* fresh `{host, mountKey, providerId, label, alt, kind, src, fit, canvasKey,
* dragging, prevLabel, prevDisabled, nextLabel, nextDisabled, actions}` on
* each change,
* or null while unmounted. A view draws it into `host` (the application's is
* `StreetLevelPhotoViewer`), forwards its events to `actions` and hands each
* element back through `actions.attach(name, element)` on every draw: the
* panorama canvas to draw on, the frame and picture to measure, the root
* and buttons to keep focus. A view may draw at once, inside its listener,
* or later (Vue draws on a microtask). Each mount has its own `mountKey`,
* and a new `canvasKey` asks for a fresh canvas (a lost WebGL context):
* neither is ever reused. `actions.supersede()` tells a viewer another one
* is drawn in its place: it unmounts, and a mount still waiting to be drawn
* fails as closed. Mounting with no view subscribed fails, and a mount or
* a panorama's open waiting on a draw when the last view leaves fails as
* closed (the mount unmounts; the open leaves no photo shown). A view
* handing back another canvas element than the renderer's (one subscribed
* since) gets the panorama drawn again on it, as after a lost context;
* while several views draw, a canvas the panorama moved off is not moved
* back to, and once one view is left its canvas is taken back.
*
* Photos are normalized by the provider: `{id, sequenceId, lon, lat,
* heading, isPano, capturedAt}` plus whatever its `sources` read.
*
@@ -249,11 +287,29 @@ export function createPhotoViewer({
}) {
const LOAD_FAILED = `The ${name} photo could not be loaded`;
const listeners = new Set();
/** The elements the view handed back. */
let root = null;
let picture = null;
let canvas = null;
let prevButton = null;
let nextButton = null;
/** What the view draws; null while unmounted. */
let presented = null;
const viewListeners = new Set();
/** Waiting for the view's root (a mount), or its canvas: a fresh one, or the next draw. */
const rootWaiters = new Set();
const canvasWaiters = new Set();
/** How many times the view has handed the canvas back (once per draw). */
let canvasDraws = 0;
/**
* Canvases the panorama moved off while more than one view draws: one
* handed back again (a second view drawing its own) is not moved back to,
* so two views cannot take turns. Forgotten once a single view is left,
* so its canvas is taken back.
*/
let retiredCanvases = new WeakSet();
/** The canvas moved while an open waited on its draw. */
let canvasMoved = false;
let renderer = null;
/** WebGL failed once: 360° photos show their front view instead. */
let rendererFailed = false;
@@ -265,8 +321,6 @@ export function createPhotoViewer({
let drag = null;
let poseFrame = 0;
let removeListeners = [];
/** The document the viewer was built in (new canvases come from it). */
let documentOf = null;
/** A context loss's look direction, for the reopen of that photo. */
let restoreView = null;
/** The panel's viewer box, where Esc is listened for (null: the root). */
@@ -354,44 +408,77 @@ export function createPhotoViewer({
});
}
/** Present the viewer with `patch` applied (null: nothing to draw). */
function present(patch) {
if (patch === null) presented = null;
else if (presented) presented = { ...presented, ...patch };
else return;
for (const listener of [...viewListeners]) listener(presented);
}
/** Settle everything waiting on the view (it drew, or it went). */
function wake(waiters) {
for (const resolve of waiters) resolve();
waiters.clear();
}
/** A draw of the canvas, or none coming: unmounted, no view, or the open stopped. */
function canvasDrawn(drawn, signal) {
if (drawn() || !presented || !viewListeners.size || signal?.aborted)
return Promise.resolve();
return new Promise((resolve) => {
canvasWaiters.add(resolve);
signal?.addEventListener?.('abort', resolve, { once: true });
});
}
/** The panorama canvas once the view has drawn it, or the open stopped. */
function canvasReady(signal) {
return canvasDrawn(() => Boolean(canvas), signal);
}
/**
* A draw of the canvas after the `count`th (it hands the canvas back each
* time), or none coming. A view may draw synchronously, inside the
* presentation, before anything waits: counted, that draw is not missed.
*/
function drawnAfter(count, signal) {
return canvasDrawn(() => canvasDraws > count, signal);
}
function syncButtons() {
const enabled = Boolean(photo?.sequenceId) && showing !== null;
if (prevButton) prevButton.disabled = !enabled;
if (nextButton) nextButton.disabled = !enabled;
present({ prevDisabled: !enabled, nextDisabled: !enabled });
if (enabled) checkEnds(photo);
}
/** Disable ‹ or › at once where the sequence ends (it also warms the neighbours). */
function checkEnds(target) {
for (const [delta, button] of [
[-1, prevButton],
[1, nextButton],
])
for (const delta of [-1, 1])
step(target, delta).then(
(id) => {
if (photo === target && button && !id) disable(button);
if (photo === target && presented && !id) disable(delta);
},
() => {},
);
}
/** Disable a step button, keeping keyboard focus in the viewer. */
function disable(button) {
if (button.ownerDocument?.activeElement === button) root?.focus?.();
button.disabled = true;
function disable(delta) {
const button = delta < 0 ? prevButton : nextButton;
if (button && button.ownerDocument?.activeElement === button)
root?.focus?.();
present(delta < 0 ? { prevDisabled: true } : { nextDisabled: true });
}
function show(kind) {
showing = kind;
if (picture) picture.hidden = kind !== 'flat';
if (canvas) canvas.hidden = kind !== 'pano';
if (root) root.dataset.kind = kind || '';
present({ kind: kind || '' });
syncButtons();
}
function applyRenderMode() {
if (picture)
picture.style.objectFit = renderMode === 'fill' ? 'cover' : 'contain';
present({ fit: renderMode === 'fill' ? 'cover' : 'contain' });
}
function ensureRenderer() {
@@ -410,7 +497,34 @@ export function createPhotoViewer({
* with it: drop the renderer, and show the photo again on a new one.
*/
function onContextLost(event) {
// Only the canvas on screen: a replaced one has nothing left to lose.
const from = event?.currentTarget ?? event?.target;
if (from && from !== canvas) return;
event.preventDefault?.();
dropRenderer();
// A lost canvas hands back its lost context: the view draws a new
// element in its place and hands it back.
canvas = null;
present({ canvasKey: nextViewKey() });
reopen();
}
/**
* The view drew the panorama on another canvas element than the
* renderer's (a view that subscribed since): the renderer cannot follow
* it, so the photo is drawn again on a new one, as after a lost context.
*/
function moveCanvas(element) {
dropRenderer();
retiredCanvases.add(canvas);
canvas = element;
// An open waiting on the draw goes on, on the new canvas.
if (openingId !== null) canvasMoved = true;
else reopen();
}
/** Let the renderer go, keeping the user's look for the photo's reopen. */
function dropRenderer() {
const lost = renderer;
renderer = null;
// The new renderer starts facing the photo's heading: keep the user's look.
@@ -421,12 +535,10 @@ export function createPhotoViewer({
} catch {
/* already gone */
}
// A lost canvas hands back its lost context: draw on a new element.
const fresh = makeCanvas(documentOf);
fresh.hidden = canvas.hidden;
canvas.replaceWith?.(fresh);
canvas = fresh;
// Show the photo again through the core, unless a newer one is opening.
}
/** Show the panorama again through the core, unless a newer photo is opening. */
function reopen() {
if (showing === 'pano' && photo && openingId === null) {
const again = photo.id;
show(null);
@@ -435,20 +547,6 @@ export function createPhotoViewer({
}
}
/** The panorama canvas, wired for drag, pinch, wheel and context loss. */
function makeCanvas(doc) {
const element = doc.createElement('canvas');
element.className = 'sl-photo-pano';
element.hidden = true;
listen(element, 'pointerdown', onPointerDown);
listen(element, 'pointermove', onPointerMove);
listen(element, 'pointerup', onPointerUp);
listen(element, 'pointercancel', onPointerUp);
listen(element, 'wheel', onWheel, { passive: false });
listen(element, 'webglcontextlost', onContextLost);
return element;
}
/**
* Step along the sequence from the photo showing, or from the one on its
* way after an earlier press, and open it through the core.
@@ -469,8 +567,7 @@ export function createPhotoViewer({
// Closed, or another photo was opened meanwhile.
if ((openingId ?? photo?.id) !== fromId) return;
if (!nextId) {
const button = delta < 0 ? prevButton : nextButton;
if (button && photo?.id === fromId) disable(button);
if (presented && photo?.id === fromId) disable(delta);
return;
}
openingId = nextId;
@@ -504,7 +601,7 @@ export function createPhotoViewer({
y: event.clientY,
view: renderer.getView(),
};
canvas.classList.add('sl-photo-dragging');
present({ dragging: true });
}
function onPointerMove(event) {
@@ -532,7 +629,7 @@ export function createPhotoViewer({
if (pointers.size < 2) pinch = null;
if (!drag || event.pointerId !== drag.id) return;
drag = null;
canvas.classList.remove('sl-photo-dragging');
present({ dragging: false });
}
function onWheel(event) {
@@ -603,51 +700,81 @@ export function createPhotoViewer({
);
}
/** The elements the view hands back, by name. */
const ELEMENTS = {
root: (element) => (root = element),
picture: (element) => (picture = element),
canvas: (element) => (canvas = element),
prev: (element) => (prevButton = element),
next: (element) => (nextButton = element),
};
/** Present the viewer in `host`; its view draws it and hands back its elements. */
function build(host) {
const doc = host.ownerDocument;
documentOf = doc;
root = doc.createElement('div');
root.className = 'sl-photo-viewer';
root.dataset.provider = providerId;
root.tabIndex = 0;
root.setAttribute('role', 'group');
root.setAttribute(
'aria-label',
t(
// Events from a view drawn for an earlier mount are not this one's.
const current =
(handler) =>
(...args) => {
if (presented?.actions === actions) handler(...args);
};
const actions = {
attach(name, element) {
if (presented?.actions !== actions || !element) return;
const retired = name === 'canvas' && retiredCanvases.has(element);
if (retired) {
// Another view still draws the panorama: this draw is counted, so
// an open waiting on it goes on, but the panorama stays put.
} else if (
name === 'canvas' &&
renderer &&
canvas &&
element !== canvas
)
moveCanvas(element);
else ELEMENTS[name]?.(element);
if (name === 'root') wake(rootWaiters);
if (name === 'canvas') {
canvasDraws++;
wake(canvasWaiters);
}
},
keydown: current(onKeyDown),
pointerdown: current(onPointerDown),
pointermove: current(onPointerMove),
pointerup: current(onPointerUp),
wheel: current(onWheel),
contextLost: current(onContextLost),
supersede: current(() => adapter.unmount()),
step: current((delta, event) => {
event?.stopPropagation?.();
stepBy(delta);
}),
};
presented = {
host,
mountKey: nextViewKey(),
providerId,
label: t(
'{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom',
{ name },
),
);
picture = doc.createElement('img');
picture.className = 'sl-photo-flat';
picture.alt = t('{name} street-level photo', { name });
picture.draggable = false;
picture.hidden = true;
canvas = makeCanvas(doc);
const nav = (label, glyph, delta) => {
const button = doc.createElement('button');
button.type = 'button';
button.className = `sl-photo-step sl-photo-step-${delta < 0 ? 'prev' : 'next'}`;
button.textContent = glyph;
button.title = label;
button.setAttribute('aria-label', label);
button.disabled = true;
listen(button, 'click', (event) => {
event.stopPropagation();
stepBy(delta);
});
return button;
alt: t('{name} street-level photo', { name }),
kind: undefined,
src: null,
fit: renderMode === 'fill' ? 'cover' : 'contain',
canvasKey: nextViewKey(),
dragging: false,
prevLabel: t('Previous photo in this sequence (←)'),
prevDisabled: true,
nextLabel: t('Next photo in this sequence (→)'),
nextDisabled: true,
actions,
};
prevButton = nav(t('Previous photo in this sequence (←)'), '‹', -1);
nextButton = nav(t('Next photo in this sequence (→)'), '›', 1);
root.append(picture, canvas, prevButton, nextButton);
host.append(root);
listen(root, 'keydown', onKeyDown);
present({});
// The viewer's box in the panel; without one, the root's own handler
// takes Esc (one listener per element and type).
escapeTarget = host.closest?.('.sl-viewer-wrap') ?? null;
if (escapeTarget) listen(escapeTarget, 'keydown', onEscapeKey);
applyRenderMode();
}
function teardown() {
@@ -655,13 +782,17 @@ export function createPhotoViewer({
pinch = null;
for (const remove of removeListeners) remove();
removeListeners = [];
escapeTarget = null;
if (poseFrame) cancelAnimationFrame(poseFrame);
poseFrame = 0;
drag = null;
renderer?.destroy();
renderer = null;
root?.remove();
// The view takes its elements away.
present(null);
root = picture = canvas = prevButton = nextButton = null;
wake(rootWaiters);
wake(canvasWaiters);
showing = null;
photo = null;
}
@@ -738,7 +869,7 @@ export function createPhotoViewer({
try {
const image = await loadAs(url, { crossOrigin: false, signal });
if (seq !== openSeq || photo !== target || showing !== 'flat') return;
picture.src = image.src;
present({ src: image.src });
sharp.shown = url;
requestRender();
} catch {
@@ -770,7 +901,8 @@ export function createPhotoViewer({
/** The sharp panorama this viewer needs now: 2,048 docked, 4,096 expanded. */
function panoSizeNow() {
const ratio = Math.min(globalThis.devicePixelRatio || 1, 2);
const width = (canvas?.clientWidth || 0) * ratio;
// The canvas fills the frame; until the view shows it, it measures 0.
const width = (canvas?.clientWidth || root?.clientWidth || 0) * ratio;
return panoSizeFor(width, renderer?.getView().fov ?? PANO_FOV_DEFAULT_DEG);
}
@@ -801,8 +933,33 @@ export function createPhotoViewer({
else if (!keepView || showing !== 'pano')
renderer.setView({ yaw: 0, pitch: 0, fov: PANO_FOV_DEFAULT_DEG });
photo = target;
// Shown first: a hidden canvas measures 0 and would be sized 1×1.
// Shown first: a hidden canvas measures 0 and would be sized 1×1. The
// view draws it shown, at once or on a microtask, and hands the canvas
// back then.
const draws = canvasDraws;
canvasMoved = false;
show('pano');
await drawnAfter(draws, signal);
// The view drew it on another canvas: the panorama goes there.
if (canvasMoved && seq === openSeq && !renderer && ensureRenderer()) {
const moved = restoreView?.id === target.id ? restoreView.view : null;
restoreView = null;
if (moved) renderer.setView(moved);
}
canvasMoved = false;
// The last view left before drawing it: the canvas was never shown, and
// nothing is drawn until a view is back.
if (seq === openSeq && canvasDraws === draws && !viewListeners.size) {
image.close?.();
photo = null;
show(null);
throw undrawn();
}
if (seq !== openSeq || !renderer) {
image.close?.();
if (seq !== openSeq) return false;
throw new Error(LOAD_FAILED);
}
renderer.setImage(image);
panoWidth = first.width || 0;
// A sharper version of the photo before was dropped by `open`; one of
@@ -827,7 +984,7 @@ export function createPhotoViewer({
}
if (!image) throw failure || new Error(LOAD_FAILED);
if (seq !== openSeq) return false;
picture.src = image.src;
present({ src: image.src });
flatSharp = { shown: null, loading: null };
photo = target;
show('flat');
@@ -837,11 +994,17 @@ export function createPhotoViewer({
async function openPhoto(id, seq, keepView, signal) {
const target = await getPhoto(id, { signal });
if (seq !== openSeq) return;
// A canvas lost moments ago: the view is drawing its replacement.
if (sources.hasPano(target) && !rendererFailed) {
await canvasReady(signal);
if (seq !== openSeq) return;
}
let shown = false;
if (sources.hasPano(target) && ensureRenderer()) {
try {
shown = await showPano(target, seq, keepView, signal);
} catch {
} catch (error) {
if (error?.undrawn) throw error;
// The panorama failed: its front view is better than nothing.
if (seq !== openSeq) return;
shown = await showFlat(target, seq, signal);
@@ -857,10 +1020,36 @@ export function createPhotoViewer({
const adapter = {
async mount(host) {
if (!host) throw new Error('Street Level viewer has no host element');
if (root && root.parentNode === host) return;
if (root && presented?.host === host) return;
teardown();
rendererFailed = false;
if (!viewListeners.size)
throw new Error('Street Level photo viewer has no view to draw it');
// Resolves once the view drew the viewer, or it was unmounted, or its
// last view left, meanwhile.
const waitRoot = () => new Promise((resolve) => rootWaiters.add(resolve));
let drawn = waitRoot();
build(host);
// This mount's presentation: a later mount presents its own. A view
// may have unmounted it already, inside its first draw.
const mine = presented?.actions;
if (!mine) throw undrawn();
for (;;) {
if (!root) await drawn;
const current = presented?.actions === mine;
if (root && current) return;
// Unmounted, superseded or mounted again: that is not this mount.
if (!current) throw undrawn();
// Its last view left, and another subscribed since: it draws.
if (viewListeners.size) {
drawn = waitRoot();
continue;
}
// No view will draw it. Unmounted, as when superseded, so a view
// subscribing later draws nothing.
adapter.unmount();
throw undrawn();
}
},
/** Resolves once the photo is on screen and its pose was emitted. */
@@ -896,7 +1085,7 @@ export function createPhotoViewer({
photo = null;
flatSharp = { shown: null, loading: null };
show(null);
if (picture) picture.removeAttribute('src');
present({ src: null });
renderer?.clear?.();
},
@@ -937,6 +1126,28 @@ export function createPhotoViewer({
listeners.add(listener);
return () => listeners.delete(listener);
},
/**
* Receive every presentation of the viewer, starting with the current
* one (null while unmounted).
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
subscribeView(listener) {
viewListeners.add(listener);
listener(presented);
return () => {
// The last view went: a mount or an open waiting on its draw fails
// as closed.
if (!viewListeners.delete(listener)) return;
// One view left: the canvases moved off are its to hand back again.
if (viewListeners.size <= 1) retiredCanvases = new WeakSet();
if (!viewListeners.size) {
wake(rootWaiters);
wake(canvasWaiters);
}
};
},
};
return adapter;
}
+435 -10
View File
@@ -1,7 +1,14 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createPhotoViewer } from './photoViewer.js';
import { fakeHost, until } from '../../testSupport/kartaViewFakes.mjs';
import {
fakeHost,
until,
resetPhotoView,
} from '../../testSupport/kartaViewFakes.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
const PHOTOS = {
a: { id: 'a', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: true },
@@ -56,7 +63,7 @@ function setup() {
pending.get(url).reject(new Error('gone'));
pending.delete(url);
};
return { viewer, loads, images, release, fail, host: fakeHost() };
return { viewer, loads, images, release, fail, host: fakeHost(viewer) };
}
const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
@@ -146,7 +153,7 @@ test('Esc: the docked viewer offers it to the provider first; expanded, it is th
onEscape: () => ++asked > 0,
load: async (url) => ({ src: url }),
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
const root = host.children[0];
const press = () => {
@@ -195,7 +202,7 @@ test('a sharp panorama still downloading when another photo opens is aborted', a
});
t.after(() => delete globalThis.devicePixelRatio);
globalThis.devicePixelRatio = 1;
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
parts(host).canvas.clientWidth = 1800;
await viewer.open('a');
@@ -235,7 +242,7 @@ test('a lost WebGL context while the first panorama loads releases its bitmap',
};
},
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
const opening = viewer.open('a');
assert.ok(await until(() => land !== null), 'the panorama is loading');
@@ -262,7 +269,7 @@ test('docked, Esc anywhere in the viewer’s box (toolbar, caption) is offered t
onEscape: () => ++asked > 0,
load: async (url) => ({ src: url }),
});
const host = fakeHost();
const host = fakeHost(viewer);
const wrap = fakeHost();
host.closest = (selector) => (selector === '.sl-viewer-wrap' ? wrap : null);
await viewer.mount(host);
@@ -363,7 +370,7 @@ function heldViewer() {
pending.get(url).resolve({ src: url });
pending.delete(url);
};
return { viewer, pending, signals, loads, release, host: fakeHost() };
return { viewer, pending, signals, loads, release, host: fakeHost(viewer) };
}
test('a new open, a close or an unmount stops the downloads of the open before it', async () => {
@@ -439,7 +446,6 @@ test('a resize while another photo opens does not upgrade the photo still shown'
});
test('a panorama is always decoded at a bounded size', async () => {
const env = heldViewer();
const options = [];
const viewer = createPhotoViewer({
providerId: 'test',
@@ -461,7 +467,7 @@ test('a panorama is always decoded at a bounded size', async () => {
destroy() {},
}),
});
await viewer.mount(env.host);
await viewer.mount(fakeHost(viewer));
await viewer.open('a');
// SOURCES' panoFirst names no size: the viewer still bounds it.
assert.deepEqual(options[0].resize, [2048, 1024]);
@@ -549,7 +555,7 @@ test('a browser without :fullscreen / :popover-open (Safari < 16.4) still opens
onEscape: () => ++asked > 0,
load: async (url) => ({ src: url }),
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
const root = host.children[0];
// Safari 16.0–16.3: neither pseudo-class parses, so closest() throws.
@@ -571,3 +577,422 @@ test('a browser without :fullscreen / :popover-open (Safari < 16.4) still opens
assert.doesNotThrow(() => root.fire('keydown', event), 'Esc does not throw');
assert.equal(asked, 1, 'Esc reaches the provider');
});
test('a panorama reopened after a lost context waits for the view’s fresh canvas', async () => {
const canvases = [];
const reopened = [];
const viewer = createPhotoViewer({
providerId: 'test',
name: 'Test',
sources: SOURCES,
getPhoto: async (id) => PHOTOS[id],
step: async () => null,
onStep() {},
onReopen: (id) => reopened.push(id),
load: async (url) => ({ src: url }),
createRenderer: (canvas) => {
canvases.push(canvas);
return {
setImage() {},
setView() {},
getView: () => ({ yaw: 0, pitch: 0, fov: 80 }),
resize() {},
clear() {},
destroy() {},
};
},
});
// A view that draws on a microtask, as Vue does, handing its canvas back
// each time, but draws a replacement canvas only a while after it is
// asked.
let shown = null;
let canvas = { name: 'canvas', clientWidth: 400 };
let late = null;
viewer.subscribeView((view) => {
const first = view && !shown;
const replaced = view && shown && view.canvasKey !== shown.canvasKey;
shown = view;
if (!view) return;
queueMicrotask(() => {
if (first)
for (const name of ['root', 'picture', 'prev', 'next'])
view.actions.attach(name, { name, clientWidth: 400 });
if (replaced) {
canvas = null;
late = () => {
canvas = { name: 'canvas again', clientWidth: 400 };
shown.actions.attach('canvas', canvas);
};
}
if (canvas) view.actions.attach('canvas', canvas);
});
});
await viewer.mount({});
await viewer.open('a');
assert.equal(shown.kind, 'pano');
shown.actions.contextLost({ preventDefault() {} });
assert.deepEqual(reopened, ['a']);
const opening = viewer.open('a');
await tick();
assert.equal(canvases.length, 1, 'no renderer without a canvas');
late();
await opening;
assert.deepEqual(
canvases.map((canvas) => canvas.name),
['canvas', 'canvas again'],
);
assert.equal(shown.kind, 'pano', 'not the front view');
});
/**
* A panorama viewer whose sequence goes on both ways (its ‹ › present no
* change once shown), drawn by `view` alone, not by the shared fake view.
*/
function panoramaViewer() {
const images = [];
const viewer = createPhotoViewer({
providerId: 'test',
name: 'Test',
sources: SOURCES,
getPhoto: async (id) => PHOTOS[id],
step: async () => 'b',
onStep() {},
load: async (url) => ({ src: url }),
createRenderer: () => ({
setImage: (image) => images.push(image.src),
setView() {},
getView: () => ({ yaw: 0, pitch: 0, fov: 80 }),
resize() {},
clear() {},
destroy() {},
}),
});
return { viewer, images };
}
/** Elements a view hands back: what the viewer measures and focuses. */
const elements = () =>
Object.fromEntries(
['root', 'picture', 'canvas', 'prev', 'next'].map((name) => [
name,
{ clientWidth: 400, clientHeight: 250 },
]),
);
/** Whether `promise` settles within a few macrotasks. */
const settles = (promise) =>
Promise.race([
promise.then(
() => true,
() => true,
),
new Promise((resolve) => setTimeout(() => resolve(false), 50)),
]);
test('a view that draws at once, inside its listener, opens a panorama', async () => {
const { viewer, images } = panoramaViewer();
const parts = elements();
const unsubscribe = viewer.subscribeView((view) => {
if (!view) return;
for (const [name, element] of Object.entries(parts))
view.actions.attach(name, element);
});
await viewer.mount(fakeHost());
assert.equal(await settles(viewer.open('a')), true, 'not left pending');
assert.deepEqual(images, ['a-first']);
viewer.unmount();
unsubscribe();
});
test('a panorama’s open waiting on the view’s draw fails as closed when the view leaves', async () => {
const { viewer, images } = panoramaViewer();
const parts = elements();
const kinds = [];
const presented = [];
// Draws the mount, then nothing more.
const unsubscribe = viewer.subscribeView((view) => {
presented.push(view);
if (!view) return;
kinds.push(view.kind);
if (kinds.length > 1) return;
for (const [name, element] of Object.entries(parts))
view.actions.attach(name, element);
});
await viewer.mount(fakeHost());
const opening = viewer.open('a');
assert.ok(await until(() => kinds.includes('pano')), 'waiting on a draw');
unsubscribe();
assert.equal(await settles(opening), true, 'not left pending');
await assert.rejects(opening, /viewer was closed/);
assert.deepEqual(images, [], 'nothing uploaded to a canvas never shown');
// A view back draws the viewer mounted, with no photo shown.
let again = null;
const resubscribe = viewer.subscribeView((view) => (again = view));
assert.ok(again, 'still mounted');
assert.equal(again.kind, '');
resubscribe();
viewer.unmount();
});
test('a mount waiting on the view’s draw fails as closed when the view leaves, and is unmounted', async () => {
const { viewer } = panoramaViewer();
const unsubscribe = viewer.subscribeView(() => {});
const mounting = viewer.mount(fakeHost());
unsubscribe();
assert.equal(await settles(mounting), true, 'not left pending');
await assert.rejects(mounting, /viewer was closed/);
let current;
const resubscribe = viewer.subscribeView((view) => (current = view));
assert.equal(current, null, 'nothing presented');
await assert.rejects(viewer.open('a'), /not mounted/);
resubscribe();
});
test('a view handing back another canvas gets the panorama drawn again on it', async () => {
const renderers = [];
const reopened = [];
const viewer = createPhotoViewer({
providerId: 'test',
name: 'Test',
sources: SOURCES,
getPhoto: async (id) => PHOTOS[id],
step: async () => 'b',
onStep() {},
onReopen: (id) => {
reopened.push(id);
viewer.open(id);
},
load: async (url) => ({ src: url }),
createRenderer: (canvas) => {
const renderer = {
canvas,
images: [],
destroyed: false,
setImage: (image) => renderer.images.push(image.src),
setView() {},
getView: () => ({ yaw: 10, pitch: 0, fov: 80 }),
resize() {},
clear() {},
destroy: () => (renderer.destroyed = true),
};
renderers.push(renderer);
return renderer;
},
});
const drawWith = (parts) => (view) => {
if (!view) return;
for (const [name, element] of Object.entries(parts))
view.actions.attach(name, element);
};
const first = elements();
const unsubscribe = viewer.subscribeView(drawWith(first));
await viewer.mount(fakeHost());
await viewer.open('a');
assert.equal(renderers[0].canvas, first.canvas);
// Another view takes over, with elements of its own.
const second = elements();
const resubscribe = viewer.subscribeView(drawWith(second));
unsubscribe();
assert.ok(await until(() => renderers[1]?.images.length > 0));
assert.deepEqual(reopened, ['a']);
assert.equal(renderers[0].destroyed, true);
assert.equal(renderers[1].canvas, second.canvas);
assert.deepEqual(renderers[1].images, ['a-first']);
viewer.unmount();
resubscribe();
});
test('the shared fake view draws only the later of two mounts, as the app does', async () => {
const one = setup();
const two = setup();
await one.viewer.mount(one.host);
assert.equal(one.host.children.length, 1);
await two.viewer.mount(one.host);
assert.equal(one.host.children.length, 1, 'one root, not one per viewer');
await assert.rejects(one.viewer.open('f'), /not mounted/, 'superseded');
two.viewer.unmount();
});
test('a viewer left by an earlier test is not superseded by a later test’s', async () => {
const earlier = setup();
await earlier.viewer.mount(earlier.host);
// As before each test.
resetPhotoView();
const later = setup();
await later.viewer.mount(later.host);
await tick();
const opening = earlier.viewer.open('f');
await until(() => earlier.loads.includes('f-first'));
earlier.release('f-first');
await opening;
earlier.viewer.unmount();
later.viewer.unmount();
});
/** A panorama viewer whose renderers and flat loads the test reads. */
function trackedViewer(options = {}) {
const renderers = [];
const loads = [];
const viewer = createPhotoViewer({
providerId: 'test',
name: 'Test',
sources: SOURCES,
getPhoto: async (id) => PHOTOS[id],
step: async () => null,
onStep() {},
load: async (url) => {
loads.push(url);
return { src: url };
},
createRenderer: (canvas) => {
const renderer = {
canvas,
images: [],
setImage: (image) => renderer.images.push(image.src),
setView() {},
getView: () => ({ yaw: 0, pitch: 0, fov: 80 }),
resize() {},
clear() {},
destroy() {},
};
renderers.push(renderer);
return renderer;
},
...options,
});
return { viewer, renderers, loads };
}
/** Hand `parts` back to the viewer that presented `view`. */
const attachAll = (view, parts) => {
for (const [name, element] of Object.entries(parts))
view.actions.attach(name, element);
};
test('a mount overtaken by a second mount of the same viewer closes, and the second stays', async () => {
const { viewer } = trackedViewer();
let latest = null;
const unsubscribe = viewer.subscribeView((view) => (latest = view));
const first = viewer.mount({ id: 1 });
const hostTwo = { id: 2 };
const second = viewer.mount(hostTwo);
// The view draws on a later macrotask.
setTimeout(() => latest && attachAll(latest, elements()), 0);
await assert.rejects(first, /viewer was closed/);
await second;
assert.equal(latest?.host, hostTwo, 'the second mount is presented');
viewer.unmount();
unsubscribe();
});
test('a mount whose view subscribes again in the same tick is drawn', async () => {
const { viewer } = trackedViewer();
let latest = null;
const view = (next) => (latest = next);
let unsubscribe = viewer.subscribeView(view);
const mounting = viewer.mount({});
// The view is replaced at once, and draws on a later macrotask.
unsubscribe();
unsubscribe = viewer.subscribeView(view);
setTimeout(() => latest && attachAll(latest, elements()), 0);
await mounting;
assert.ok(latest, 'still presented');
viewer.unmount();
unsubscribe();
});
test('a canvas handed back while a panorama’s open waits on its draw takes the panorama', async () => {
const { viewer, renderers, loads } = trackedViewer();
const first = elements();
const second = elements();
let latest = null;
let hold = false;
const unsubscribe = viewer.subscribeView((view) => {
latest = view;
if (view && !hold) attachAll(view, first);
});
await viewer.mount({});
hold = true;
const opening = viewer.open('a');
assert.ok(await until(() => latest?.kind === 'pano'), 'waiting on a draw');
// The view draws it with a canvas of its own.
attachAll(latest, second);
await opening;
assert.equal(latest.kind, 'pano', 'not the front view');
assert.deepEqual(loads, ['a-first'], 'no flat version loaded');
assert.equal(renderers.at(-1).canvas, second.canvas);
assert.deepEqual(renderers.at(-1).images, ['a-first']);
viewer.unmount();
unsubscribe();
});
test('two views handing back canvases of their own do not take the panorama in turns', async () => {
let reopened = 0;
const { viewer, renderers } = trackedViewer({
onReopen: (id) => {
reopened++;
if (reopened < 20) viewer.open(id).catch(() => {});
},
});
const one = elements();
const two = elements();
const unsubscribes = [
viewer.subscribeView((view) => view && attachAll(view, one)),
viewer.subscribeView((view) => view && attachAll(view, two)),
];
await viewer.mount({});
await viewer.open('a');
const built = renderers.length;
// Each presentation is drawn by both views.
for (const mode of ['fill', 'letterbox', 'fill']) {
viewer.setRenderMode(mode);
for (let i = 0; i < 5; i++) await tick();
}
assert.equal(reopened, 0);
assert.equal(renderers.length, built, 'the panorama stays where it is');
assert.deepEqual(renderers.at(-1).images, ['a-first']);
viewer.unmount();
for (const unsubscribe of unsubscribes) unsubscribe();
});
test('the panorama goes back to the one view left once a second view leaves', async () => {
const { viewer, renderers } = trackedViewer({
onReopen: (id) => viewer.open(id).catch(() => {}),
});
const one = elements();
const two = elements();
const unsubscribeOne = viewer.subscribeView(
(view) => view && attachAll(view, one),
);
await viewer.mount({});
await viewer.open('a');
// A second view subscribes and draws its own canvas: the panorama moves.
const unsubscribeTwo = viewer.subscribeView(
(view) => view && attachAll(view, two),
);
for (let i = 0; i < 5; i++) await tick();
assert.equal(renderers.at(-1).canvas, two.canvas);
unsubscribeTwo();
assert.ok(
await settles(viewer.open('b')),
'the next open is not left waiting',
);
for (let i = 0; i < 5; i++) await tick();
assert.equal(
renderers.at(-1).canvas,
one.canvas,
'the panorama is back on the view left',
);
assert.equal(renderers.at(-1).images.at(-1), 'b-first');
viewer.unmount();
unsubscribeOne();
});
test('a mount its view unmounts inside the first draw fails as closed', async () => {
const { viewer } = trackedViewer();
const unsubscribe = viewer.subscribeView((view) => {
if (view) viewer.unmount();
});
await assert.rejects(viewer.mount({}), /Street-level viewer was closed/);
unsubscribe();
});
+102
View File
@@ -0,0 +1,102 @@
/** The last key handed out by `nextViewKey()`. */
let viewKeys = 0;
/**
* A key no viewer or picker was ever given: photo viewers key their mounts
* and canvases with it, and a presentation without a mount key is stamped
* with one when first seen, so both rank on one scale.
*/
export function nextViewKey() {
return ++viewKeys;
}
/**
* Each keyless viewer's current mount, `{actions, key}`: stamped once, by
* whichever picker sees it first, and kept until it presents null, so a
* picker made later ranks it the same.
*/
const keylessMounts = new WeakMap();
/**
* Receive the photo viewer to draw, out of several photo viewers mounting
* in one host (see photoViewer.js): the one mounted last, whatever order
* they present in. One view draws one viewer, so a viewer still mounting
* when a later one presents is superseded: it settles its mount as closed
* and stops presenting. Starts with the current one (null while none is
* mounted).
*
* Two fields of a presentation are read here (see ViewerAdapter.subscribeView
* in registry.js):
* - `mountKey`, a number larger for each later mount (from `nextViewKey()`),
* orders the mounts. A presentation without one counts as mounted when
* any picker first saw it present: it is stamped with a `nextViewKey()`
* then, the same for every picker, however many are made later.
* - `actions.supersede()`, where present, is called on each presentation
* not drawn, whenever more than one presents. It runs on a microtask,
* after the presentation that won has reached every subscriber: a
* subscriber never sees the superseded one withdraw before it sees the
* one replacing it.
* @param {Iterable<{subscribeView?: Function}>} viewers
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
export function subscribePhotoViewers(viewers, listener) {
// Each viewer's current presentation and its rank, {view, key}.
const shown = new Map();
let ready = false;
let closed = false;
let superseding = false;
let last;
/** A mount's rank: its key, or the stamp of its first presentation. */
const rank = (viewer, view) => {
if (Number.isFinite(view.mountKey)) return view.mountKey;
let mount = keylessMounts.get(viewer);
if (!mount || mount.actions !== view.actions) {
mount = { actions: view.actions, key: nextViewKey() };
keylessMounts.set(viewer, mount);
}
return mount.key;
};
// The others are not drawn: a mount still waiting on the view never
// would be.
const supersede = () => {
superseding = false;
if (closed || !last) return;
for (const { view } of [...shown.values()])
if (view !== last) view.actions?.supersede?.();
};
const publish = () => {
let next = null;
for (const entry of shown.values())
if (!next || entry.key > next.key) next = entry;
next = next?.view ?? null;
if (!ready) return;
if (next !== last) {
last = next;
listener(next);
}
if (last && shown.size > 1 && !superseding) {
superseding = true;
queueMicrotask(supersede);
}
};
const unsubscribes = [];
for (const viewer of viewers) {
const unsubscribe = viewer?.subscribeView?.((view) => {
if (closed) return;
if (!view) {
shown.delete(viewer);
keylessMounts.delete(viewer);
} else shown.set(viewer, { view, key: rank(viewer, view) });
publish();
});
if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe);
}
ready = true;
publish();
if (last === undefined) listener((last = null));
return () => {
closed = true;
for (const unsubscribe of unsubscribes.splice(0)) unsubscribe();
};
}
@@ -0,0 +1,215 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createPhotoViewer } from './photoViewer.js';
import { nextViewKey, subscribePhotoViewers } from './photoViewers.js';
/**
* A photo viewer whose presentations the test sends; `superseded` counts.
* Unlike photoViewer.js it keeps presenting once superseded, so the order
* is seen to come from the mount keys alone.
*/
function fakeViewer() {
const listeners = new Set();
let current = null;
const viewer = {
superseded: 0,
view(mountKey) {
return {
mountKey,
actions: { supersede: () => viewer.superseded++ },
};
},
present(view) {
current = view;
for (const listener of [...listeners]) listener(view);
},
subscribeView(listener) {
listeners.add(listener);
listener(current);
return () => listeners.delete(listener);
},
};
return viewer;
}
test('the later mount is drawn, whatever order the viewers present in', async () => {
const a = fakeViewer();
const b = fakeViewer();
const shown = [];
const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view));
assert.deepEqual(shown, [null], 'the current one first');
const first = a.view(1);
a.present(first);
const later = b.view(2);
b.present(later);
assert.equal(shown.at(-1), later);
// Once every subscriber has the later one.
await Promise.resolve();
assert.equal(a.superseded, 1, 'the earlier mount is told it is not drawn');
// The earlier viewer presents again: it does not take the view back.
a.present({ ...first, kind: 'flat' });
assert.equal(shown.at(-1), later);
assert.equal(shown.length, 3);
b.present(null);
assert.equal(shown.at(-1).mountKey, 1, 'the only one presenting');
a.present(null);
assert.equal(shown.at(-1), null);
unsubscribe();
a.present(first);
assert.equal(shown.length, 5, 'unsubscribed');
});
/** A viewer that, superseded, unmounts as photoViewer.js does: it presents null. */
function unmountingViewer() {
const viewer = fakeViewer();
const view = viewer.view;
viewer.view = (mountKey) => {
const presented = view(mountKey);
const supersede = presented.actions.supersede;
presented.actions.supersede = () => {
supersede();
viewer.present(null);
};
return presented;
};
return viewer;
}
test('every subscriber sees the earlier mount, then the later one, with no gap', async () => {
const a = unmountingViewer();
const b = unmountingViewer();
const first = [];
const second = [];
const unsubscribes = [
subscribePhotoViewers([a, b], (view) => first.push(view)),
subscribePhotoViewers([a, b], (view) => second.push(view)),
];
const earlier = a.view(1);
a.present(earlier);
const later = b.view(2);
b.present(later);
await Promise.resolve();
assert.equal(a.superseded, 1, 'superseded once, by both');
assert.deepEqual(first, [null, earlier, later]);
assert.deepEqual(second, [null, earlier, later], 'never null between');
for (const unsubscribe of unsubscribes) unsubscribe();
});
test('a presentation without a mount key counts as mounted when it began presenting', async () => {
const a = fakeViewer();
const b = fakeViewer();
const c = fakeViewer();
const shown = [];
const unsubscribe = subscribePhotoViewers([a, b, c], (view) =>
shown.push(view),
);
a.present(a.view(nextViewKey()));
const keyless = b.view(undefined);
b.present(keyless);
assert.equal(shown.at(-1), keyless, 'after the keyed one');
// Of two without, the one that began presenting last.
const newer = c.view(undefined);
c.present(newer);
assert.equal(shown.at(-1), newer);
b.present({ ...keyless, kind: 'flat' });
assert.equal(shown.at(-1), newer, 'presenting again is not a new mount');
// A keyed mount made after them wins.
const latest = a.view(nextViewKey());
a.present(latest);
assert.equal(shown.at(-1), latest);
await Promise.resolve();
assert.ok(b.superseded > 0 && c.superseded > 0, 'the keyless ones are told');
unsubscribe();
});
test('a presentation that is not drawn is superseded even when the pick stays', async () => {
const a = fakeViewer();
const b = fakeViewer();
const shown = [];
const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view));
const later = b.view(2);
b.present(later);
// An earlier mount presents once the later one is drawn.
a.present(a.view(1));
assert.deepEqual(shown, [null, later]);
await Promise.resolve();
assert.equal(a.superseded, 1);
unsubscribe();
});
test('a photo viewer mounting while a keyless presentation shows is drawn, and the keyless one superseded', async () => {
let superseded = 0;
const keyless = {
subscribeView(listener) {
listener({ actions: { supersede: () => superseded++ } });
return () => {};
},
};
const viewer = createPhotoViewer({
providerId: 'test',
name: 'Test',
sources: {},
getPhoto: async () => null,
step: async () => null,
onStep() {},
});
const shown = [];
const element = { clientWidth: 400, clientHeight: 250 };
const unsubscribe = subscribePhotoViewers([keyless, viewer], (view) => {
shown.push(view);
if (!view?.mountKey) return;
for (const name of ['root', 'picture', 'canvas', 'prev', 'next'])
view.actions.attach(name, element);
});
const mounting = viewer.mount({});
const outcome = await Promise.race([
mounting.then(() => 'mounted'),
new Promise((resolve) => setTimeout(() => resolve('pending'), 50)),
]);
assert.equal(outcome, 'mounted');
assert.ok(Number.isFinite(shown.at(-1)?.mountKey), 'the mount is drawn');
assert.ok(superseded >= 1, 'the keyless one is told');
viewer.unmount();
unsubscribe();
});
test('a presentation without actions or supersede is drawn and passed over without throwing', async () => {
const a = fakeViewer();
const b = fakeViewer();
const shown = [];
const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view));
a.present({ mountKey: 1 });
const later = { mountKey: 2, actions: {} };
assert.doesNotThrow(() => b.present(later));
await Promise.resolve();
assert.equal(shown.at(-1), later);
a.present({ mountKey: 3 });
await Promise.resolve();
assert.equal(shown.at(-1).mountKey, 3);
unsubscribe();
});
test('a keyless viewer on screen keeps its place when the picker is made again', async () => {
const keyed = fakeViewer();
const keyless = fakeViewer();
keyed.present(keyed.view(nextViewKey()));
const shown = [];
let unsubscribe = subscribePhotoViewers([keyless, keyed], (view) =>
shown.push(view),
);
const mounted = keyless.view(undefined);
keyless.present(mounted);
assert.equal(shown.at(-1), mounted);
await Promise.resolve();
unsubscribe();
// A new picker, the keyless viewer first: it is still the later mount.
const again = [];
unsubscribe = subscribePhotoViewers([keyless, keyed], (view) =>
again.push(view),
);
assert.equal(again.at(-1), mounted);
await Promise.resolve();
assert.equal(keyless.superseded, 0, 'never told it is not drawn');
assert.ok(keyed.superseded > 0);
unsubscribe();
});
@@ -13,7 +13,12 @@ import {
TOO_HIGH_HINT,
} from './policy.js';
import { validateProviders } from '../../registry.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
drawn,
fakeHost,
until,
resetPhotoView,
} from '../../../../testSupport/kartaViewFakes.mjs';
import {
bindStreetViewer,
coverageViewer,
@@ -22,6 +27,9 @@ import {
} from '../../../../testSupport/streetLevelFakes.mjs';
import { fakeDrawPort } from '../../../../testSupport/fakeDrawPort.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
/** A photo record `metres` east of (42.3314, -83.0458), in sequence `seq` at `index`. */
function photoRecord(id, { metres = 0, seq = '14010', index = 0 } = {}) {
const lon = -83.0458 + metres / 82_300;
@@ -190,7 +198,7 @@ test('the nearest photo is the closest within 50 m, and opening it asks nothing
});
const id = await instance.nearestImage({ lat: 42.3314, lon: -83.0458 });
assert.equal(id, 'near');
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
await instance.viewer.open(id);
assert.deepEqual(source.calls.photo, [], 'the lookup filled the cache');
@@ -285,7 +293,7 @@ const press = async (button, opened) => {
async function mounted(sourceOptions, contextOptions) {
const env = setup(sourceOptions, contextOptions);
const host = fakeHost();
const host = fakeHost(env.instance.viewer);
await env.instance.viewer.mount(host);
const poses = [];
env.instance.viewer.onPose((pose) => poses.push(pose.imageId));
@@ -970,7 +978,7 @@ test('after a GPU reset the photo is drawn again by the viewer, not through the
context.actions.reportError = (message) => errors.push(message);
const instance = definition.create(context);
actions.instance = instance;
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
const poses = [];
instance.viewer.onPose((pose) => poses.push(pose.imageId));
@@ -978,6 +986,7 @@ test('after a GPU reset the photo is drawn again by the viewer, not through the
const canvas = () => host.children[0].children[1];
const kind = () => host.children[0].dataset.kind;
canvas().fire('webglcontextlost');
await drawn();
assert.equal(kind(), '', 'cleared while it is drawn again');
assert.ok(await until(() => kind() === 'pano'), 'drawn again');
assert.ok(poses.length >= 2);
@@ -1010,7 +1019,7 @@ test('the marker is KartaView’s own cone, and it points along the drive, not a
photos: page.photos.map((record) => ({ ...record, heading: '200' })),
};
};
const host = fakeHost();
const host = fakeHost(env.instance.viewer);
await env.instance.viewer.mount(host);
const bearings = [];
env.instance.viewer.onPose((pose) => bearings.push(pose.bearing));
@@ -1101,7 +1110,7 @@ test('a sequence page that lands while a lost GPU context recovers still draws i
const instance = definition.create(context);
actions.instance = instance;
const cones = await withCones(t, { instance });
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
await instance.viewer.open('p-0');
// › to the next panorama; the GPU resets while it loads.
@@ -1,7 +1,15 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createKartaViewViewer, loadImage, panoSizeFor } from './viewer.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
drawn,
fakeHost,
until,
resetPhotoView,
} from '../../../../testSupport/kartaViewFakes.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
const PHOTOS = {
flat1: {
@@ -148,7 +156,7 @@ function setup({
});
const poses = [];
viewer.onPose((pose) => poses.push(pose));
const host = fakeHost();
const host = fakeHost(viewer);
return {
viewer,
poses,
@@ -223,6 +231,7 @@ test('a flat photo shows its 1280 px version, then the sharp one, with a pose fa
assert.equal(picture.src, loads[1].url, 'upgraded to the sharp version');
assert.equal(viewer.supportsRenderModes(), true);
viewer.setRenderMode('fill');
await drawn();
assert.equal(picture.style.objectFit, 'cover');
});
@@ -357,12 +366,14 @@ test('a newer open wins; close hides the photo; unmount tears down the panorama'
assert.equal(renderers.length, 0, 'nor built a WebGL context');
await viewer.open('pano1');
viewer.close();
await drawn();
const { picture, canvas, root } = parts(host);
assert.equal(canvas.hidden, true);
assert.equal(picture.hidden, true);
assert.equal(root.dataset.kind, '');
await assert.rejects(viewer.open('nope'), /no such photo/);
viewer.unmount();
await drawn();
assert.equal(host.children.length, 0);
assert.equal(renderers[0].destroyed, true);
await assert.rejects(viewer.open('flat1'), /not mounted/);
@@ -463,12 +474,14 @@ test('a lost WebGL context drops the panorama and shows the photo again on a new
const lost = parts(host).canvas;
lost.fire('webglcontextlost');
assert.equal(renderers[0].destroyed, true);
await drawn();
// A lost canvas only ever gives back its lost context: a new element.
assert.notEqual(parts(host).canvas, lost);
assert.deepEqual(stepped, ['pano1'], 'reopened through the core');
assert.ok(await until(() => renderers.length === 2), 'a new renderer');
assert.equal(renderers[1].canvas, parts(host).canvas);
assert.equal(poses.at(-1).imageId, 'pano1');
await drawn();
assert.equal(parts(host).canvas.hidden, false);
});
@@ -498,7 +511,7 @@ test('a WebGL failure only lasts until the viewer is mounted again', async () =>
return renderer;
},
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
await viewer.open('pano1');
assert.equal(parts(host).picture.hidden, false, 'front view');
@@ -589,7 +602,7 @@ function heldSetup({ slowSteps = false } = {}) {
});
const poses = [];
viewer.onPose((pose) => poses.push(pose.imageId));
const host = fakeHost();
const host = fakeHost(viewer);
/** Let the load showing `what` (e.g. 'a@1280') finish. */
const release = async (what) => {
assert.ok(
@@ -798,7 +811,7 @@ function heldPanoSetup(held) {
});
const poses = [];
viewer.onPose((pose) => poses.push(pose));
return { viewer, renderers, stepped, poses, host: fakeHost(), release };
return { viewer, renderers, stepped, poses, host: fakeHost(viewer), release };
}
const pano2Preview = Buffer.from(
@@ -931,7 +944,7 @@ test('a docked viewer keeps the 1,280 px photo; expanding it brings the 2,560 px
viewer.resize();
assert.ok(await until(() => loads.length === 2));
assert.match(loads[1].url, /rs:fit:2560:2560/);
assert.equal(parts(host).picture.src, loads[1].url);
assert.ok(await until(() => parts(host).picture.src === loads[1].url));
viewer.resize();
for (let i = 0; i < 4; i++) await settle();
assert.equal(loads.length, 2, 'once only');
@@ -14,7 +14,12 @@ import {
} from './policy.js';
import { validateProviders } from '../../registry.js';
import { tileBounds } from '../../tileMath.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
drawn,
fakeHost,
until,
resetPhotoView,
} from '../../../../testSupport/kartaViewFakes.mjs';
import {
bindStreetViewer,
coverageViewer,
@@ -27,6 +32,9 @@ import {
stacItem,
} from '../../../../testSupport/panoramaxFixtures.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
const ORIGIN = { lon: 2.3495, lat: 48.8874 };
/** A point `metres` east of ORIGIN. */
const east = (metres) => ({
@@ -284,7 +292,7 @@ async function mounted(sourceOptions, contextOptions) {
const env = setup(sourceOptions, contextOptions);
const poses = [];
env.instance.viewer.onPose((pose) => poses.push(pose.imageId));
const host = fakeHost();
const host = fakeHost(env.instance.viewer);
await env.instance.viewer.mount(host);
const [, , prev, next] = host.children[0].children;
return { ...env, poses, prev, next };
@@ -320,7 +328,7 @@ test('one lookup for a picture asked twice at once', async () => {
await gate;
return getItem(id);
};
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
const first = instance.viewer.open('s-0');
const second = instance.viewer.open('s-0');
@@ -985,7 +993,7 @@ test('after a GPU reset the viewer draws the same picture itself, leaving the co
const { context, actions } = fakeContext();
const instance = definition.create(context);
actions.instance = instance;
const host = fakeHost();
const host = fakeHost(instance.viewer);
await instance.viewer.mount(host);
const poses = [];
instance.viewer.onPose((pose) => poses.push(pose.imageId));
@@ -994,6 +1002,8 @@ test('after a GPU reset the viewer draws the same picture itself, leaving the co
const kind = () => host.children[0].dataset.kind;
assert.equal(kind(), 'pano');
canvas().fire('webglcontextlost');
await drawn();
assert.equal(kind(), '', 'cleared while it is drawn again');
assert.ok(await until(() => kind() === 'pano'), 'drawn again');
assert.deepEqual(poses, ['p-0', 'p-0']);
assert.deepEqual(actions.opened, [], 'not through the core');
@@ -2,9 +2,16 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { PANORAMAX_SOURCES, createPanoramaxViewer } from './viewer.js';
import { normalizeItem } from './policy.js';
import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs';
import {
fakeHost,
until,
resetPhotoView,
} from '../../../../testSupport/kartaViewFakes.mjs';
import { stacItem } from '../../../../testSupport/panoramaxFixtures.mjs';
// Each test draws its own viewers only.
test.beforeEach(resetPhotoView);
const photo = (options) =>
normalizeItem(stacItem({ lon: 2.35, lat: 48.85, ...options }));
@@ -59,7 +66,7 @@ function setup() {
});
const poses = [];
viewer.onPose((pose) => poses.push(pose));
return { viewer, poses, loads, renderers, stepped, host: fakeHost() };
return { viewer, poses, loads, renderers, stepped, host: fakeHost(viewer) };
}
const parts = (host) => {
@@ -252,7 +259,7 @@ test('without WebGL a 360° picture shows its whole equirectangular image flat',
throw new Error('no WebGL');
},
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
await viewer.open('pano');
const { picture } = parts(host);
@@ -272,7 +279,7 @@ test('a picture whose SD fails falls back to the thumbnail; the original only fo
return { src: url };
},
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
await viewer.open('flat');
assert.deepEqual(tried, [PHOTOS.flat.urls.sd, PHOTOS.flat.urls.thumb]);
@@ -326,7 +333,7 @@ test('an SD panorama refused for its size is not fetched again as a flat photo',
destroy() {},
}),
});
const host = fakeHost();
const host = fakeHost(viewer);
await viewer.mount(host);
await viewer.open('pano');
const sdLoads = loads.filter((l) => l.url === PHOTOS.pano.urls.sd);
+10
View File
@@ -63,6 +63,16 @@ export function filtersOf(provider) {
* @property {(mode: 'letterbox'|'fill') => void} [setRenderMode]
* @property {() => boolean} [supportsRenderModes] False while the image has no frame to fit (a panorama): FIT / FILL hide.
* @property {(listener: (pose: StreetPose) => void) => () => void} onPose
* @property {(listener: (view: ?object) => void) => () => void} [subscribeView]
* An adapter that draws nothing itself presents its viewer here, for the
* layer's `subscribePhotoViewer()` (see photoViewer.js): its current
* presentation at once, then each new one, null while unmounted. One view
* draws one viewer (photoViewers.js picks it), reading two fields:
* `mountKey`, a number larger for each later mount (the later mount is
* drawn; a presentation without one counts as mounted when it began
* presenting), and `actions.supersede()`, called on a mount that is not
* drawn because a later one is (it should unmount, failing a mount still
* waiting to be drawn; an adapter without it is simply not drawn).
*
* @typedef {object} StreetPose
* @property {string} providerId
+34
View File
@@ -27,6 +27,7 @@ import {
followsClock,
} from './policy.js';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
import { locateOnTrack } from '../../data/locate.js';
const UUID_KEY =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -628,6 +629,39 @@ export function createQueries({
return components.selection.selectAndFocusVessel(record);
},
/**
* The track reference of a loaded vessel, so it can be looked up again
* once it has left the feed (see locate).
* @param {string} id
* @returns {string|null}
*/
referenceOf(id) {
if (id === null || id === undefined) return null;
return recordFor(String(id).trim())?.reference ?? null;
},
/**
* Where a vessel is at the layer's time (the world clock's while the
* layer follows it, else now), from its own track: for a vessel that has
* left the feed, so it can be found again.
* @param {string} id
* @param {{reference?: string, signal?: AbortSignal}} [options]
* @returns {Promise<{status: 'found', lat: number, lon: number,
* altitudeM: ?number, observedAtMs: number}|{status: 'none'}>}
*/
locate(id, { reference, signal } = {}) {
const atMs = followsClock(vesselState)
? vesselState.worldNow()
: undefined;
return locateOnTrack(
vesselState._source,
reference ??
recordFor(String(id ?? '').trim())?.reference ??
String(id ?? ''),
{ atMs, signal },
);
},
/**
* Return a subset of vessels for the universal detection overlay.
* Deterministic stride sampling distributes selections evenly across the
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff. Show more