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

+1
View File
@@ -126,6 +126,7 @@ export function createApplicationCatalog({
});
const satellites = createApplicationSatellites({
source: sources.satellites,
...(resolveAsset ? { resolveAsset } : {}),
});
const catalog = createLayerCatalog(
[
+4
View File
@@ -21,6 +21,8 @@ export { START_VIEW };
* `homeView` is where the title's logo goes back to (with the clock live): the
* start view unless given, for a host whose `startView` only carries a view
* across a rebuild.
* `startLayers` are the layer ids a bare address (one that carries no link)
* starts with: none by default; a host may pass `['flights', 'satellites']`.
* `services.cockpitSubjects` adds the application's own first-person subjects
* to the Cockpit (src/cockpitSubjectProviders.js).
*/
@@ -36,6 +38,7 @@ export function createApplicationControls({
localePicker = true,
startView = START_VIEW,
homeView = startView,
startLayers = [],
}) {
// Every boot starts from the same view, before share restoration flies on.
applyStartView(viewer, startView);
@@ -59,6 +62,7 @@ export function createApplicationControls({
initialShareCode,
localePicker,
homeView,
startLayers,
});
defer(() => styleManager.orbitController.stop());
defer(() => styleManager.hud.destroy());
+2 -1
View File
@@ -2,6 +2,7 @@ import { createCctvLayer } from '../../layers/cctv/index.js';
import * as credits from '../../data/dataCredits.js';
import * as sprites from '../../data/spriteOrder.js';
import * as activation from '../../cctvFocusRequest.js';
import { keyholeLabelAlphaFromGeometry } from '../../celestialRing.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { CITY_POIS } from '../../cityPois.js';
import * as picking from '../../data/pickRegistry.js';
@@ -17,7 +18,7 @@ export function createApplicationCctv({ surface, source }) {
credits,
sprites,
activation,
overlays,
overlays: { ...overlays, keyholeAlpha: keyholeLabelAlphaFromGeometry },
locations: { CITY_POIS },
picking,
terrain,
+4
View File
@@ -1,12 +1,16 @@
import {
clearOverlaySource,
getOverlayPaintRect,
getWorldOverlayDiagnostics,
hitTestWorldOverlay,
setOverlayEntries,
setOverlaySourceVisible,
} from '../../overlays/worldOverlay.js';
export const overlayHost = Object.freeze({
clearSource: clearOverlaySource,
getDiagnostics: getWorldOverlayDiagnostics,
hitTest: hitTestWorldOverlay,
paintRect: getOverlayPaintRect,
setEntries: setOverlayEntries,
setVisible: setOverlaySourceVisible,
});
+6 -1
View File
@@ -8,9 +8,14 @@ import * as render from '../../renderGovernor.js';
import * as layerState from '../../data/layerState.js';
/** Construct one layer using the application scene owners and a supplied source. */
export function createApplicationSatellites({ source }) {
export function createApplicationSatellites({
source,
resolveAsset = (url) =>
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
}) {
return createSatellitesLayer({
source,
resolveAsset,
services: {
picking,
focus,
+8 -2
View File
@@ -90,8 +90,14 @@ test('the ring renders its overlay in the viewer container', async (t) => {
['DIV', 'celestial-ring-outline'],
['CANVAS', 'celestial-ring-canvas celestial-sun-canvas'],
['CANVAS', 'celestial-ring-canvas celestial-moon-canvas'],
['SPAN', 'celestial-marker celestial-sun material-symbols-outlined'],
['SPAN', 'celestial-marker celestial-moon material-symbols-outlined'],
[
'SPAN',
'ui-icon material-symbols-outlined celestial-marker celestial-sun',
],
[
'SPAN',
'ui-icon material-symbols-outlined celestial-marker celestial-moon',
],
],
);
assert.equal(root.children[0].style.display, 'none');
+42 -11
View File
@@ -74,10 +74,14 @@ const voiceActions = fs.readFileSync(
test('Cockpit has one reset action beside its bottom exit path', () => {
assert.doesNotMatch(html, /id="cockpit-quick-entry"/);
assert.doesNotMatch(html, /id="cockpit-exit"/);
assert.match(
html,
/id="map-view-switch"[^>]*aria-label="Exit cockpit view"[^>]*aria-keyshortcuts="Escape"[\s\S]*?close_fullscreen[\s\S]*?EXIT COCKPIT/,
// The exit button's attributes, in whatever order the button renders them.
const exit = html.match(
/<button\b(?=[^>]*\sid="map-view-switch")([^>]*)>([\s\S]*?)<\/button>/,
);
assert.ok(exit, 'Cockpit exit is missing');
assert.match(exit[1], /\saria-label="Exit cockpit view"/);
assert.match(exit[1], /\saria-keyshortcuts="Escape"/);
assert.match(exit[2], /close_fullscreen[\s\S]*?EXIT COCKPIT/);
const topCenterActions = html.match(
/<nav id="top-center-actions"[\s\S]*?<\/nav>/,
);
@@ -108,9 +112,18 @@ test('Cockpit has one reset action beside its bottom exit path', () => {
/id="reset-globe-view"/,
'map-only reset must stay outside Cockpit',
);
assert.match(
viewSwitcher[0],
/id="cockpit-reset-globe"[^>]*type="button"[^>]*aria-label="Reset cockpit to full globe view"[^>]*hidden[\s\S]*?public[\s\S]*?RESET[\s\S]*?id="map-view-switch"/,
// The reset button's attributes, in whatever order the button renders them.
const reset = viewSwitcher[0].match(
/<button\b(?=[^>]*\sid="cockpit-reset-globe")([^>]*)>([\s\S]*?)<\/button>/,
);
assert.ok(reset, 'Cockpit Reset is missing from the view switcher');
assert.match(reset[1], /\stype="button"/);
assert.match(reset[1], /\saria-label="Reset cockpit to full globe view"/);
assert.match(reset[1], /\shidden(?=[\s>=]|$)/);
assert.match(reset[2], /public[\s\S]*?RESET/);
assert.ok(
viewSwitcher[0].indexOf('id="map-view-switch"') > reset.index,
'Cockpit Reset must sit before the exit button',
);
const actions = html.match(
@@ -194,12 +207,12 @@ test('Cockpit vision cycle exposes every map preset exactly once', () => {
test('Contacts uses the approved radar icon', () => {
const button = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
/<button\b[^>]*\bid="global-context-flights-btn"[\s\S]*?<\/button>/,
);
assert.ok(button, 'Contacts button is missing');
assert.match(
button[0],
/material-symbols-outlined" aria-hidden="true">radar<\/span>/,
/material-symbols-outlined"[^>]*aria-hidden="true">radar<\/span>/,
);
});
@@ -369,11 +382,11 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls',
assert.doesNotMatch(html, /data-cockpit-display-slot="presets"/);
assert.match(
html,
/id="clear-selected-layers"[^>]*aria-label="Clear selected data layers"/,
/<button\b(?=[^>]*\bid="clear-selected-layers")[^>]*aria-label="Clear selected data layers"/,
);
assert.match(
html,
/id="reset-globe-view"[^>]*aria-label="Reset to full globe view"/,
/<button\b(?=[^>]*\bid="reset-globe-view")[^>]*aria-label="Reset to full globe view"/,
);
assert.match(
css,
@@ -1144,6 +1157,15 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
mobileCockpit[1],
/body\.cockpit-mode \.cockpit-utility-controls[\s\S]*?bottom:\s*152px;/,
);
assert.match(
mobileCockpit[1],
/body\.cockpit-mode\.mobile-shell[^{]*?\.cockpit-utility-controls \{[^}]*?top:[^;]*?var\(--cockpit-visor-top\)/,
);
assert.match(
mobileCockpit[1],
/@media \(min-width: 390px\) and \(min-height: 240px\),\s*\(min-height: 450px\) \{\s*body\.cockpit-mode\.mobile-shell/,
);
assert.match(css, /\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/);
assert.match(
mobileCockpit[1],
/body\.cockpit-mode \.cockpit-utility-control\.is-expanded[\s\S]*?top:\s*96px;/,
@@ -1162,6 +1184,15 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
);
});
test('the unread Stories announcement waits until Cockpit closes', () => {
assert.match(css, /body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/);
const storiesView = fs.readFileSync(path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'), 'utf8');
assert.match(
storiesView,
/async function openExplore\(\) \{[^}]*?if \(await store\.controller\.open\(\)\) markPopSeen\(\);/,
);
});
test('cockpit route direction uses self-contained vector artwork, not a font ligature', () => {
const match = html.match(/<div id="cockpit-route-direction"[\s\S]*?<\/div>/);
assert.ok(match, 'cockpit route-direction markup is missing');
@@ -1231,7 +1262,7 @@ test('Cockpit Contact navigation omits the redundant Focus camera action', () =>
test('Global Context names its mixed contact cycle without changing the stable mode id', () => {
const match = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
/<button\b[^>]*\bid="global-context-flights-btn"[\s\S]*?<\/button>/,
);
assert.ok(match, 'Global Context contacts button is missing');
assert.match(match[0], />CONTACTS</);
+4 -4
View File
@@ -25,12 +25,12 @@ const css = readStylesheet(new URL('../style.css', import.meta.url));
test('Contacts stays in the keyboard sequence and Space Missions owns its rail item', () => {
const button = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
/<button\b[^>]*\bid="global-context-flights-btn"[\s\S]*?<\/button>/,
)?.[0];
assert.ok(button, 'Contacts control is missing');
assert.match(button, /role="tab"/);
assert.match(button, /tabindex="0"/);
const tag = contextView.match(/<button id="global-context-flights-btn"[^>]*>/)?.[0];
const tag = contextView.match(/<UiButton id="global-context-flights-btn"[^>]*>/)?.[0];
assert.ok(tag, 'Contacts control is missing from the view');
assert.doesNotMatch(tag, /:tabindex|:disabled|\sdisabled/);
assert.doesNotMatch(html, /id="global-context-missions-btn"/);
@@ -111,7 +111,7 @@ test('Context async action buttons remain focused while busy', () => {
assert.match(init, /if \(this\._installationsSearchBusy\) return;/);
assert.doesNotMatch(init, /\.disabled\s*=\s*true/);
const search = contextView.match(
/<button id="installations-search-btn"[^>]*>/,
/<UiButton id="installations-search-btn"[^>]*>/,
)?.[0];
assert.ok(search, 'nearby sites search is missing');
assert.doesNotMatch(search, /:disabled|\sdisabled/);
@@ -140,7 +140,7 @@ test('Context async action buttons remain focused while busy', () => {
'utf8',
);
const clearButton = globeActions.match(
/<button id="clear-selected-layers"[^>]*>/,
/<UiButton id="clear-selected-layers"[^>]*>/,
)?.[0];
assert.ok(clearButton, 'Clear selected layers button is missing');
assert.doesNotMatch(clearButton, /disabled(?!=")|:disabled=/);
+1
View File
@@ -335,6 +335,7 @@ test('the Google places route throttles by default and keeps its places[] contra
const overLimit = await request(handler, { url, method: 'GET' });
assert.equal(overLimit.status, 429);
assert.equal(overLimit.headers['retry-after'], '5');
assert.equal(overLimit.headers['cache-control'], 'no-store');
// Every error response on this route carries places[]; the client reads it
// unconditionally, so a throttled reply must not be the one shape that omits it.
assert.deepEqual(JSON.parse(overLimit.body).places, []);
+19 -6
View File
@@ -912,10 +912,12 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
'#command-dock:has(#location-bar:not(.collapsed))',
'#command-dock:has(#control-panel:not(.collapsed))',
];
assert.equal(
omnibarVar('--world-timeline-lift'),
'0px',
'the Omnibar layout holds the timeline lift at 0',
// The dock rises over the World Timeline by world-timeline.css's lift, as
// the plain dock does; the Omnibar scope leaves the lift alone.
assert.doesNotMatch(
fs.readFileSync(path.join(ROOT, 'src/ui/styles/omnibar-dock.css'), 'utf8'),
/--world-timeline-lift\s*:/,
'the Omnibar layout leaves the timeline lift to world-timeline.css',
);
for (const width of WIDTHS.filter((w) => w >= OMNIBAR_MIN_WIDTH)) {
for (const height of HEIGHTS) {
@@ -968,10 +970,21 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
credit.part.startsWith(OMNIBAR_SCOPE),
`the Omnibar owns the credit row at ${width}px`,
);
const dockBottom = omnibarPx(
// The dock rises over the World Timeline from the dock's floor, and
// the bar takes that floor: the floor is what clears the credit.
assert.equal(
dock.decl.value,
'var(--omnibar-dock-raised)',
`Omnibar dock bottom at ${width}px`,
);
assert.equal(
omnibarVar('--omnibar-dock-raised').replace(/\s+/g, ' '),
'calc( var(--omnibar-dock-bottom) + var(--world-timeline-lift, 0px) )',
);
const dockBottom = omnibarPx(
'var(--omnibar-dock-bottom)',
height,
'Omnibar dock bottom',
'Omnibar dock floor',
);
const creditTop =
omnibarPx(credit.decl.value, height, 'Omnibar credit bottom') +
+2
View File
@@ -50,6 +50,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
'surveillance:type': 'ALPR',
operator: 'Flock Safety',
'camera:type': 'fixed',
model: ' L6Q ',
'surveillance:zone': 'traffic',
'camera:direction': '270',
ref: 'ATX-001',
@@ -63,6 +64,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
longitude: -97.7431,
operator: 'Flock Safety',
manufacturer: null,
model: 'L6Q',
cameraType: 'fixed',
zone: 'traffic',
directionDeg: 270,
+174 -232
View File
@@ -5,7 +5,10 @@ import {
findQuery,
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { loadYouTubeApi } from './youtubeApi.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
import { h, render as renderVue } from 'vue';
import BhoteKoshiMediaCards from '../ui/bhoteKoshi/BhoteKoshiMediaCards.vue';
const YOUTUBE_HOSTS = new Set([
'youtube.com',
@@ -98,59 +101,7 @@ export function bhoteEventText(value) {
let _xWidgetsPromise = null;
let _facebookSdkPromise = null;
let _facebookEmbedSequence = 0;
const youtubeApis = new WeakMap();
function loadYouTubeApi(documentRef, globalRef) {
if (typeof globalRef.YT?.Player === 'function')
return Promise.resolve(globalRef.YT);
if (youtubeApis.has(documentRef)) return youtubeApis.get(documentRef);
const pending = new Promise((resolve, reject) => {
const previous = globalRef.onYouTubeIframeAPIReady;
let timer;
let settled = false;
const script = documentRef.createElement('script');
const finish = (error) => {
if (settled) return;
settled = true;
globalRef.clearTimeout(timer);
if (globalRef.onYouTubeIframeAPIReady === ready)
globalRef.onYouTubeIframeAPIReady = previous;
if (error) {
script.remove();
reject(error);
} else resolve(globalRef.YT);
};
const ready = () => {
try {
previous?.();
} finally {
finish(
typeof globalRef.YT?.Player === 'function'
? null
: new Error('YouTube API unavailable'),
);
}
};
globalRef.onYouTubeIframeAPIReady = ready;
script.src = 'https://www.youtube.com/iframe_api';
script.async = true;
script.addEventListener(
'error',
() => finish(new Error('YouTube API unavailable')),
{ once: true },
);
timer = globalRef.setTimeout(
() => finish(new Error('YouTube API timed out')),
5000,
);
documentRef.head.append(script);
}).catch((error) => {
youtubeApis.delete(documentRef);
throw error;
});
youtubeApis.set(documentRef, pending);
return pending;
}
let _cardSequence = 0;
/** A trimmed clip follows provider time, never time spent loading its iframe. */
export function createTrimmedYouTubePlayback({
@@ -682,32 +633,61 @@ export function createBhoteKoshiEmbeddedMedia({
let record = null;
let warmRecord = null;
let generation = 0;
// Text the cards show, kept as the calls that word it so a locale change
// words it again. A node is forgotten once it has left the page.
const worded = new Map();
function forgetDetached() {
for (const node of worded.keys())
if (!node.isConnected) worded.delete(node);
let destroyed = false;
// The cards in the root, in the order they were shown: the current one and
// any still leaving. Their text is kept as the calls that word it, so a
// locale change words it again.
const cards = [];
/** Render the cards and the YouTube preload into the root, synchronously. */
function render() {
if (destroyed) return;
const warmFrame = warmRecord?.frame;
renderVue(
h(BhoteKoshiMediaCards, {
warm: warmFrame
? {
key: warmRecord.key,
src: warmFrame.src,
title: warmFrame.title(),
}
: null,
cards: cards.map((current) => ({
id: current.id,
provider: current.source.provider,
portrait: current.portrait,
entering: current.entering,
leaving: current.leaving,
unavailable: current.unavailable,
label: current.label(),
title: current.title(),
status: current.status(),
url: current.source.url,
frame: current.frame && {
src: current.frame.src,
title: current.frame.title(),
onLoad: current.frame.onLoad,
},
bind: current.bind,
})),
}),
root,
);
}
function word(node, property, text) {
let properties = worded.get(node);
if (!properties) worded.set(node, (properties = new Map()));
properties.set(property, text);
writeWord(node, property, text());
}
function writeWord(node, property, value) {
if (property === 'textContent' || property === 'title')
node[property] = value;
else node.setAttribute(property, value);
}
const offLocale = onLocaleChange(() => {
forgetDetached();
for (const [node, properties] of worded)
for (const [property, text] of properties)
writeWord(node, property, text());
});
const offLocale = onLocaleChange(render);
const leavingRecords = new Set();
/** Word a card's status and draw it. */
function setStatus(current, text) {
current.status = text;
render();
}
/** Mark a card unavailable or not and draw it. */
function setUnavailable(current, unavailable) {
current.unavailable = unavailable;
render();
}
const prefersReducedMotion = () =>
globalRef.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ===
true;
@@ -848,9 +828,10 @@ export function createBhoteKoshiEmbeddedMedia({
if (current.exitTimer != null) globalRef.clearTimeout?.(current.exitTimer);
destroyFacebookSession(current.facebookSession);
current.youtubeSession?.destroy();
current.card?.remove?.();
const at = cards.indexOf(current);
if (at !== -1) cards.splice(at, 1);
leavingRecords.delete(current);
forgetDetached();
render();
}
const position = () => {
@@ -866,7 +847,8 @@ export function createBhoteKoshiEmbeddedMedia({
current.enterFrame = scheduleFrame(() => {
current.enterFrame = null;
if (token !== generation || record !== current) return;
current.card.classList.add('is-entering');
current.entering = true;
render();
});
}
}
@@ -888,9 +870,10 @@ export function createBhoteKoshiEmbeddedMedia({
removeRecord(current);
return;
}
current.card.classList.remove('is-entering');
current.card.classList.add('is-leaving');
current.entering = false;
current.leaving = true;
leavingRecords.add(current);
render();
current.exitTimer =
globalRef.setTimeout?.(
() => removeRecord(current),
@@ -900,11 +883,10 @@ export function createBhoteKoshiEmbeddedMedia({
function clearWarm(key = null) {
if (!warmRecord || (key && warmRecord.key !== key)) return;
if (warmRecord.facebookSession)
destroyFacebookSession(warmRecord.facebookSession);
else warmRecord.iframe?.remove?.();
const facebookSession = warmRecord.facebookSession;
warmRecord = null;
forgetDetached();
if (facebookSession) destroyFacebookSession(facebookSession);
else render();
}
function takeWarmFacebook(key, host) {
@@ -944,29 +926,26 @@ export function createBhoteKoshiEmbeddedMedia({
warmRecord = { key, facebookSession };
return true;
}
const iframe = documentRef.createElement('iframe');
iframe.className = 'bhote-embedded-media-warmup';
iframe.src = embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
});
word(iframe, 'title', () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
);
iframe.tabIndex = -1;
iframe.setAttribute('aria-hidden', 'true');
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
root.append(iframe);
warmRecord = { key, iframe };
warmRecord = {
key,
frame: {
src: embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
}),
title: () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
},
};
render();
return true;
}
async function mountX(current, token) {
word(current.status, 'textContent', () => t('LOADING X POST…'));
setStatus(current, () => t('LOADING X POST…'));
try {
const api = await xLoader(documentRef, globalRef);
if (token !== generation || record !== current) return;
@@ -986,14 +965,12 @@ export function createBhoteKoshiEmbeddedMedia({
throw new Error(
msg('The X post is unavailable or cannot be embedded.'),
);
word(current.status, 'textContent', () =>
t('X POST · PROVIDER CONTROLS'),
);
setStatus(current, () => t('X POST · PROVIDER CONTROLS'));
position();
} catch (error) {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(String(error?.message || msg('X embed unavailable'))),
}),
@@ -1010,16 +987,14 @@ export function createBhoteKoshiEmbeddedMedia({
session.shouldPlay = autoplay === true;
session.onReady = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('FACEBOOK · PROVIDER CONTROLS'),
);
current.card.classList.remove('is-unavailable');
current.status = () => t('FACEBOOK · PROVIDER CONTROLS');
setUnavailable(current, false);
position();
};
session.onError = (error) => {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(
String(error?.message || msg('Facebook embed unavailable')),
@@ -1030,9 +1005,7 @@ export function createBhoteKoshiEmbeddedMedia({
};
session.onPlaybackBlocked = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'),
);
setStatus(current, () => t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'));
};
if (session.ready) session.onReady();
else if (session.error) session.onError(session.error);
@@ -1078,104 +1051,69 @@ export function createBhoteKoshiEmbeddedMedia({
if (warmRecord && warmRecord.key !== warmKey) clearWarm();
hide({ preserveWarm: true });
const token = ++generation;
const card = documentRef.createElement('section');
const portraitClass = isPortraitMedia(media) ? ' is-portrait' : '';
card.className = `bhote-embedded-callout is-${source.provider}${portraitClass}`;
card.dataset.provider = source.provider;
word(card, 'aria-label', () =>
t('Embedded {provider} media for {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
const leader = documentRef.createElementNS(
'http://www.w3.org/2000/svg',
'svg',
);
leader.classList.add('bhote-embedded-callout-leader');
leader.setAttribute('aria-hidden', 'true');
leader.innerHTML =
'<path pathLength="1" fill="none" stroke="rgba(147,213,228,.72)" stroke-width="1.5"/><circle r="4" fill="#6be8ff" stroke="#ffffff" stroke-width="1.5"/>';
const player = documentRef.createElement('div');
player.className = 'bhote-embedded-callout-player ui-scroll';
const footer = documentRef.createElement('footer');
const title = documentRef.createElement('strong');
word(title, 'textContent', () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
);
const status = documentRef.createElement('small');
status.setAttribute('role', 'status');
word(status, 'textContent', () =>
t('{provider} · EMBEDDED SOURCE', {
provider: providerLabel(source.provider),
}),
);
const link = documentRef.createElement('a');
link.href = source.url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
word(link, 'textContent', () => t('OPEN ORIGINAL ↗'));
footer.append(title, status, link);
const body = documentRef.createElement('div');
body.className = 'bhote-embedded-callout-body';
// The card takes taps (its container and leader do not); Stories keeps that.
body.setAttribute('data-overlay-input', '');
body.append(player, footer);
card.append(leader, body);
root.append(card);
record = {
const providerName = () => providerLabel(source.provider);
const sourceName = () =>
observation?.title
? bhoteEventText(observation.title)
: t('witness source');
const current = {
id: ++_cardSequence,
key,
source,
anchor,
card,
leader,
player,
status,
portrait: isPortraitMedia(media),
entering: false,
leaving: false,
unavailable: false,
label: () =>
t('Embedded {provider} media for {source}', {
provider: providerName(),
source: sourceName(),
}),
title: () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
status: () =>
t('{provider} · EMBEDDED SOURCE', { provider: providerName() }),
frame: null,
frameElement: null,
card: null,
leader: null,
player: null,
entered: false,
};
if (source.provider === 'x') {
void mountX(record, token);
} else if (source.provider === 'facebook') {
bindFacebook(record, token, warmKey, autoplay);
} else {
const iframe = documentRef.createElement('iframe');
iframe.src = embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
});
const controlled =
// The elements the card's view draws: placed after each frame, filled by
// the provider.
current.bind = (name, element) => {
if (element) current[name] = element;
};
let controlled = false;
if (source.provider === 'youtube') {
const url = new URL(
embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
}),
);
controlled =
autoplay &&
Number.isFinite(Number(endAtSec)) &&
Number(endAtSec) > startAtSec;
if (controlled) {
const url = new URL(iframe.src);
url.searchParams.set('enablejsapi', '1');
if (globalRef.location?.origin)
url.searchParams.set('origin', globalRef.location.origin);
iframe.src = url.href;
}
word(iframe, 'title', () =>
t('{provider} media: {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
iframe.allow =
'autoplay; encrypted-media; picture-in-picture; fullscreen';
iframe.allowFullscreen = true;
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
iframe.addEventListener?.(
'load',
() => {
current.frame = {
src: url.href,
title: () =>
t('{provider} media: {source}', {
provider: providerName(),
source: sourceName(),
}),
onLoad: () => {
if (token !== generation || record?.key !== key) return;
clearWarm(warmKey);
if (
@@ -1184,38 +1122,41 @@ export function createBhoteKoshiEmbeddedMedia({
record.youtubeSession.getState().phase,
)
) {
word(status, 'textContent', () =>
t('{provider} · PROVIDER CONTROLS', {
provider: providerLabel(source.provider),
}),
setStatus(current, () =>
t('{provider} · PROVIDER CONTROLS', { provider: providerName() }),
);
}
position();
},
{ once: true },
);
player.append(iframe);
if (controlled) {
const current = record;
current.youtubeSession = createTrimmedYouTubePlayback({
iframe,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
word(status, 'textContent', () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
};
}
record = current;
cards.push(current);
render();
if (source.provider === 'x') {
void mountX(current, token);
} else if (source.provider === 'facebook') {
bindFacebook(current, token, warmKey, autoplay);
} else if (controlled) {
current.youtubeSession = createTrimmedYouTubePlayback({
iframe: current.frameElement,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
setStatus(current, () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
position();
return true;
@@ -1223,11 +1164,12 @@ export function createBhoteKoshiEmbeddedMedia({
function destroy() {
offLocale();
worded.clear();
hide({ immediate: true });
for (const current of [...leavingRecords]) removeRecord(current);
clearWarm();
removePostRender?.();
destroyed = true;
renderVue(null, root);
root.remove();
}
+171 -68
View File
@@ -1,3 +1,4 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
@@ -12,6 +13,31 @@ import {
} from './bhoteKoshiEmbeddedMedia.js';
import { bindRenderer } from '../render/rendererOf.js';
// The cards draw provider frames; the tests never load their pages, and the
// page's note that each one is not loaded is dropped.
window.happyDOM.settings.disableIframePageLoading = true;
const consoleError = console.error;
console.error = (error, ...rest) => {
if (!/Iframe page loading is disabled/.test(String(error?.message)))
consoleError(error, ...rest);
};
/**
* Embedded media in a fresh globe container of the page, and the overlay
* root it renders into.
*/
function domFixture(options = {}) {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const media = createBhoteKoshiEmbeddedMedia({
viewer: { container },
documentRef: document,
globalRef: {},
...options,
});
return { media, container, root: container.firstElementChild };
}
test('Pinokio fallback never creates provider DOM or loads SDKs', async () => {
const unexpected = () => { throw new Error('Provider resource allocated in Pinokio'); };
const media = createBhoteKoshiEmbeddedMedia({
@@ -186,31 +212,138 @@ test('trimmed YouTube teardown revokes pending SDK and player callbacks', async
});
test('pausing YouTube removes its frame and rejects a late load from the stopped generation', () => {
const nodes = [];
class Element extends EventTarget {
constructor(tag) { super(); this.tag = tag; this.children = []; this.dataset = {}; this.classList = { add() {}, remove() {} }; nodes.push(this); }
setAttribute() {}
append(...children) { for (const child of children) { child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {} });
const { media, container, root } = domFixture();
const options = { observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {}, autoplay: true };
assert.equal(media.show(options), true);
const frame = nodes.find((node) => node.tag === 'iframe');
const card = nodes.find((node) => node.tag === 'section');
assert.ok(card.parent);
const card = root.querySelector('section');
const frame = card.querySelector('iframe');
assert.ok(card.isConnected);
assert.equal(media.pause(), true);
assert.equal(card.parent, null);
assert.equal(card.isConnected, false);
frame.dispatchEvent(new Event('load'));
assert.equal(card.parent, null);
assert.equal(root.querySelector('section'), null);
assert.equal(media.show(options), true, 'an explicit replay creates a fresh player');
assert.notEqual(root.querySelector('section iframe'), frame);
media.destroy();
assert.equal(container.children.length, 0);
});
test('a card draws its provider, source, status and original link, and words them again in a new locale', async () => {
const { setLocale } = await import('../i18n/index.js');
const { media, root } = domFixture();
assert.equal(media.show({
observation: { title: 'Flood footage', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k', orientation: 'portrait' } },
anchor: {},
}), true);
const card = root.querySelector('section');
assert.equal(card.className, 'bhote-embedded-callout is-youtube is-portrait');
assert.equal(card.dataset.provider, 'youtube');
assert.equal(card.getAttribute('aria-label'), 'Embedded YOUTUBE media for Flood footage');
const leader = card.firstElementChild;
assert.equal(leader.namespaceURI, 'http://www.w3.org/2000/svg');
assert.equal(leader.getAttribute('class'), 'bhote-embedded-callout-leader');
assert.equal(leader.getAttribute('aria-hidden'), 'true');
assert.equal(leader.querySelector('path').getAttribute('pathLength'), '1');
assert.equal(leader.querySelector('circle').getAttribute('r'), '4');
const body = card.querySelector('.bhote-embedded-callout-body');
assert.equal(body.getAttribute('data-overlay-input'), '');
const player = body.firstElementChild;
assert.equal(player.className, 'bhote-embedded-callout-player ui-scroll');
const frame = player.firstElementChild;
assert.equal(frame.tagName, 'IFRAME');
assert.equal(new URL(frame.src).pathname, '/embed/DbqRexFxv3k');
assert.equal(frame.title, 'YOUTUBE media: Flood footage');
assert.equal(frame.getAttribute('allow'), 'autoplay; encrypted-media; picture-in-picture; fullscreen');
assert.equal(frame.hasAttribute('allowfullscreen'), true);
assert.equal(frame.getAttribute('referrerpolicy'), 'strict-origin-when-cross-origin');
const [title, status, link] = body.querySelector('footer').children;
assert.equal(title.tagName, 'STRONG');
assert.equal(title.textContent, 'FLOOD FOOTAGE');
assert.equal(status.getAttribute('role'), 'status');
assert.equal(status.textContent, 'YOUTUBE · EMBEDDED SOURCE');
assert.equal(link.href, 'https://www.youtube.com/watch?v=DbqRexFxv3k');
assert.equal(link.target, '_blank');
assert.equal(link.rel, 'noopener noreferrer');
assert.equal(link.textContent, 'OPEN ORIGINAL ↗');
frame.dispatchEvent(new Event('load'));
assert.equal(status.textContent, 'YOUTUBE · PROVIDER CONTROLS');
try {
await setLocale('es');
assert.notEqual(link.textContent, 'OPEN ORIGINAL ↗', 'the link is worded again');
assert.notEqual(status.textContent, 'YOUTUBE · PROVIDER CONTROLS', 'the status is worded again');
assert.ok(root.querySelector('section') === card, 'in place');
} finally {
await setLocale('en');
}
media.destroy();
});
test('an X post is built by the provider inside the card and its failure marks the card', async () => {
let fail = false;
const { media, root } = domFixture({
xLoader: async () => ({ widgets: { createTweet: async (id, target) => {
if (fail) return null;
target.append(Object.assign(document.createElement('div'), { className: 'twitter-tweet', textContent: id }));
return {};
} } }),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://x.com/Indowatchosint/status/2092640554568007958' } };
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const status = card.querySelector('[role="status"]');
assert.equal(status.textContent, 'LOADING X POST…');
await new Promise((resolve) => setTimeout(resolve));
assert.equal(card.querySelector('.bhote-embedded-callout-player .twitter-tweet').textContent, '2092640554568007958');
assert.equal(status.textContent, 'X POST · PROVIDER CONTROLS');
assert.equal(card.classList.contains('is-unavailable'), false);
media.hide({ immediate: true });
fail = true;
assert.equal(media.show({ observation, anchor: {} }), true);
await new Promise((resolve) => setTimeout(resolve));
const failed = root.querySelector('section');
assert.ok(failed.classList.contains('is-unavailable'));
assert.equal(failed.querySelector('[role="status"]').textContent, 'The X post is unavailable or cannot be embedded. OPEN ORIGINAL.');
media.destroy();
});
test('a warmed Facebook player moves into the card and stays through its redraws', async () => {
let ready;
const { media, root } = domFixture({
facebookLoader: async () => ({
Event: { subscribe(_name, callback) { ready = callback; }, unsubscribe() {} },
XFBML: { parse() {} },
}),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://www.facebook.com/reel/1571491657757829' } };
media.warm({ observation });
await Promise.resolve(); await Promise.resolve();
const host = root.querySelector('.bhote-embedded-media-warmup');
const embed = host.querySelector('.fb-video');
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const player = card.querySelector('.bhote-embedded-callout-player');
assert.ok(host.parentNode === player, 'the warmed player is carried over, not rebuilt');
assert.equal(host.className, 'bhote-facebook-player-host');
assert.equal(host.hasAttribute('aria-hidden'), false);
ready({ type: 'video', id: embed.id, instance: { mute() {}, play() {}, pause() {} } });
assert.equal(card.querySelector('[role="status"]').textContent, 'FACEBOOK · PROVIDER CONTROLS');
assert.ok(host.parentNode === player, 'a redraw keeps the provider player');
media.destroy();
});
test('a leaving card animates out and is removed after its exit', () => {
const timers = [];
const { media, root } = domFixture({ globalRef: { setTimeout: (fn) => timers.push(fn), clearTimeout() {} } });
media.show({ observation: { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {} });
const card = root.querySelector('section');
card.hidden = false;
media.hide();
assert.ok(card.isConnected);
assert.ok(card.classList.contains('is-leaving'));
assert.equal(card.classList.contains('is-entering'), false);
timers.forEach((fn) => fn());
assert.equal(card.isConnected, false);
media.destroy();
assert.equal(documentRef.body.children.length, 0);
});
test('resolves supported embedded callout providers from canonical public URLs', () => {
@@ -303,28 +436,8 @@ test('Mailung playback stops at source timestamp 0:07 without changing other cli
});
function preloadFixture(options = {}) {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
append(...children) {
for (const child of children) { child.remove(); child.parent = this; this.children.push(child); }
}
remove() {
if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);
this.parent = null;
}
}
const documentRef = {
body: new Element('body'),
createElement: tag => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {}, ...options });
return { media, root: documentRef.body.children[0] };
const { media, root } = domFixture(options);
return { media, root };
}
for (const operation of ['pause', 'hide', 'destroy']) {
@@ -343,16 +456,18 @@ test('camera updates retain a preload until the visible player loads', () => {
const observation = { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } };
media.warm({ observation });
const frame = root.children[0];
assert.equal(frame.className, 'bhote-embedded-media-warmup');
assert.equal(frame.getAttribute('aria-hidden'), 'true');
assert.equal(frame.tabIndex, -1);
assert.equal(frame.title, 'Preloading YOUTUBE media');
media.hide({ preserveWarm: true });
media.warm({ observation });
assert.equal(root.children[0], frame);
assert.ok(root.children[0] === frame);
assert.equal(media.show({ observation, anchor: {} }), true);
assert.equal(frame.parent, root, 'keep the preload while the visible player starts');
const card = root.children.find(node => node.tag === 'section');
const body = card.children.find(node => node.className === 'bhote-embedded-callout-body');
const player = body.children.find(node => node.className.split(' ').includes('bhote-embedded-callout-player'));
player.children.find(node => node.tag === 'iframe').dispatchEvent(new Event('load'));
assert.equal(frame.parent, null, 'visible player readiness releases the preload');
assert.ok(frame.parentNode === root, 'keep the preload while the visible player starts');
root.querySelector('section .bhote-embedded-callout-body > .bhote-embedded-callout-player > iframe')
.dispatchEvent(new Event('load'));
assert.equal(frame.isConnected, false, 'visible player readiness releases the preload');
media.destroy();
assert.equal(root.children.length, 0);
});
@@ -420,25 +535,9 @@ test('a media card stays between the panels when right-to-left swaps their sides
});
test('a shown card follows its anchor through the renderer ports', () => {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {}; this.style = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
querySelector() { return null; }
getBoundingClientRect() { return { left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 }; }
append(...children) { for (const child of children) { child.remove(); child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const listeners = new Set();
const viewer = { canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
const container = document.body.appendChild(document.createElement('div'));
const viewer = { container, canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
let pose = { position: { x: 0, y: 0, z: 0 }, direction: { x: 1, y: 0, z: 0 } };
const projected = [];
// The renderer's canvas, not the viewer's, places the card.
@@ -454,14 +553,18 @@ test('a shown card follows its anchor through the renderer ports', () => {
},
},
});
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef, globalRef: {} });
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef: document, globalRef: {} });
const root = container.firstElementChild;
root.getBoundingClientRect = () => ({ left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 });
assert.deepEqual([...listeners].map(([phase]) => phase), ['postRender']);
const anchor = { x: 10, y: 0, z: 0 };
assert.equal(media.show({ observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor }), true);
const card = documentRef.body.children[0].children.find((node) => node.tag === 'section');
const card = root.querySelector('section');
assert.equal(card.hidden, false);
assert.equal(projected.at(-1), anchor);
assert.equal(card.style.left, `${300 + 10 + 42}px`);
// The leader runs from the anchor to the card's near edge.
assert.equal(card.querySelector('path').getAttribute('d'), `M ${300 + 10 - 352} ${200 + 5 - parseFloat(card.style.top)} L 0 ${Math.max(16, Math.min(360 - 16, 200 + 5 - parseFloat(card.style.top)))}`);
// Behind the eye: hidden on the next drawn frame.
pose = { ...pose, direction: { x: -1, y: 0, z: 0 } };
for (const [, cb] of listeners) cb();
+3 -2
View File
@@ -989,9 +989,10 @@ function createPanelRecords(event) {
textContent: t('▶ PLAY SCENE'),
hidden: true,
}),
// `pressed` is the button's pressed state; the view renders it as one.
cinematicButton: panelRecord({
textContent: t('◉ CINEMATIC'),
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: panelRecord({ textContent: t('↺ FULL STORY') }),
corridorButton: panelRecord(),
@@ -2860,7 +2861,7 @@ export function createBhoteKoshiEventLayer({
'textContent',
_cinematicActive ? t('■ RELEASE CAMERA') : t('◉ CINEMATIC'),
);
setElementAttribute(button, 'aria-pressed', String(_cinematicActive));
setElementProperty(button, 'pressed', _cinematicActive);
return true;
}
+4
View File
@@ -101,6 +101,7 @@ function eventPanel() {
get textContent() { return record().textContent; },
get hidden() { return record().hidden; },
get disabled() { return record().disabled; },
get pressed() { return record().pressed; },
get value() { return typed ?? record().value; },
set value(value) { typed = value; },
getAttribute: (name) => record().attributes[name] ?? null,
@@ -2711,6 +2712,8 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
play.dispatch('click');
assert.equal(layer.getCinematicState().active, true);
assert.equal(layer.getPlaybackState().progress, 0);
const cinematicControl = panel.querySelector('[data-action="cinematic"]');
assert.equal(cinematicControl.pressed, true, 'the cinematic button is pressed while it owns the camera');
assert.equal(layer.getPlaybackState().playing, true);
assert.equal(
body.children.some((element) => element.id === 'bhote-koshi-story-strap'),
@@ -2720,6 +2723,7 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
panel.querySelector('[data-action="cinematic"]').dispatch('click');
assert.equal(layer.getCinematicState().active, false);
assert.equal(viewer._test.cameraTransforms.length, 2);
assert.equal(cinematicControl.pressed, false, 'releasing the camera unpresses the button');
animationCallbacks[1](91001);
assert.equal(play.textContent, '↺ REPLAY');
const cameraLookCount = viewer._test.cameraLooks.length;
+8 -1
View File
@@ -38,7 +38,7 @@ function presentation(patch = {}) {
playSceneButton: record({ textContent: '▶ PLAY SCENE', hidden: true }),
cinematicButton: record({
textContent: '◉ CINEMATIC',
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: record({ textContent: '↺ FULL STORY' }),
corridorButton: record(),
@@ -156,6 +156,10 @@ test('a later presentation updates the controls in place', async (t) => {
disabled: true,
attributes: { 'aria-label': 'Play Global context' },
});
next.refs.cinematicButton = record({
textContent: '■ RELEASE CAMERA',
pressed: true,
});
next.refs.progressInput = record({ value: '250', hidden: true });
next.refs.imagerySection = record({ hidden: true });
store.publish(next);
@@ -164,6 +168,9 @@ test('a later presentation updates the controls in place', async (t) => {
assert.equal(play.textContent, '▶ PLAY SHOT');
assert.equal(play.disabled, true);
assert.equal(play.getAttribute('aria-label'), 'Play Global context');
const cinematic = $('[data-action="cinematic"]');
assert.equal(cinematic.getAttribute('aria-pressed'), 'true');
assert.equal(cinematic.textContent, '■ RELEASE CAMERA');
assert.ok(
$('#bhote-koshi-event-panel').classList.contains('bhote-event-scene-beat'),
);
+1 -1
View File
@@ -1,4 +1,4 @@
import { toRadians } from '../geo/index.js';
import { toRadians } from '../geo/vector.js';
import { findCamera } from '../render/rendererOf.js';
/** The camera port's pose, or null when there is none to read. */
+15 -1
View File
@@ -85,7 +85,9 @@ import {
} from '../cctvFocusRequest.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
IDLE_CAMERA_COLOR,
IDLE_CAMERA_ICON,
LIVE_CAMERA_COLOR,
} from '../layers/cctv/policy.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
@@ -353,7 +355,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
}
});
test('camera icons are violet for video feeds, cyan for stills, amber when active', () => {
test('camera icons are violet for video feeds, green for stills, amber when active', () => {
const record = (id, feedType) => ({
camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 },
// Every catalog record is placed as it is made, and drawn there.
@@ -385,6 +387,18 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ
assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR);
assert.equal(icons.item(activeVideo.camera.id).scale, 1.25);
assert.equal(icons.item(idleVideo.camera.id).scale, 1);
const image = (record) => icons.item(record.camera.id).image;
const idleImage = image(idleStill);
assert.equal(idleImage, IDLE_CAMERA_ICON);
assert.equal(image(activeVideo), CAMERA_ICON);
assert.equal(image(idleVideo), CAMERA_ICON);
idleStill.camera.feedType = 'hls';
refreshCoverageStyles();
assert.equal(image(idleStill), CAMERA_ICON);
idleStill.camera.feedType = 'image';
refreshCoverageStyles();
assert.equal(image(idleStill), idleImage);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
+2
View File
@@ -86,6 +86,8 @@ const RETRY_BASE_MS = 15_000;
const RETRY_MAX_MS = 5 * 60 * 1000;
export const CCTV_OVERLAY_SOURCE_ID = 'cctv';
/** The source a CCTV count marker takes clicks as. */
export const CCTV_COUNT_CARD_SOURCE_ID = 'cctv-count';
export const CCTV_THUMBNAIL_ALTITUDE_SCALE = Object.freeze({
fullEnd: CCTV_CARD_SCALE_FULL_M,
midEnd: CCTV_CARD_SCALE_MID_M,
+238
View File
@@ -0,0 +1,238 @@
import { fromDegrees } from '../geo/ellipsoid.js';
/** Exact below 1,000, then K with one decimal below 10K. Uses Latin digits in every locale. */
export function formatCameraCount(count) {
if (count < 1000) return String(count);
const thousands =
count < 10000 ? Math.round(count / 100) / 10 : Math.round(count / 1000);
return `${thousands}K`;
}
/** An empty cell and its on-screen picker candidate. */
export function createCameraCell(key) {
return {
key,
count: 0,
latSum: 0,
lonSum: 0,
heightSum: 0,
south: Infinity,
north: -Infinity,
west: Infinity,
east: -Infinity,
low: Infinity,
high: -Infinity,
winner: null,
rank: Infinity,
};
}
/** Accumulate one horizon-visible mount in its ground cell. */
export function addCellCamera(cell, camera) {
const { lat, lon, absoluteHeightM: height = 0 } = camera;
cell.count++;
// Integer sums make the mean independent of catalog order, to about a centimetre.
cell.latSum += Math.round(lat * 1e7);
cell.lonSum += Math.round(lon * 1e7);
cell.heightSum += Math.round(height * 100);
cell.south = Math.min(cell.south, lat);
cell.north = Math.max(cell.north, lat);
cell.west = Math.min(cell.west, lon);
cell.east = Math.max(cell.east, lon);
cell.low = Math.min(cell.low, height);
cell.high = Math.max(cell.high, height);
}
const wrapLongitude = (lon) => ((((lon + 180) % 360) + 360) % 360) - 180;
/** Mean longitude and latitude of a cell's mounts, in degrees. */
export function cellLonLat(cell) {
return {
lon: wrapLongitude(cell.lonSum / (1e7 * cell.count)),
lat: cell.latSum / (1e7 * cell.count),
};
}
/**
* Geographic mean of the mounts. Its height is the drawn ground under it
* when the cell carries one (`groundM`), since a camera nobody has looked at
* yet may still hold a catalog height far from the terrain; otherwise the
* mean mount height.
*/
export function cellCenter(cell) {
const { lon, lat } = cellLonLat(cell);
return fromDegrees(
lon,
lat,
Number.isFinite(cell.groundM)
? cell.groundM
: cell.heightSum / (100 * cell.count),
);
}
/** Half the east-west and north-south ground extent of a cell's mounts, in metres. */
export function cellHalfExtents(cell) {
// The parallel nearest the equator bounds the width of every row.
const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180;
return {
halfWidthM: 0.5 * (cell.east - cell.west) * 111_320 * Math.cos(parallel),
halfHeightM: 0.5 * (cell.north - cell.south) * 111_320,
};
}
/** A padded sphere over the rectangle and every mount, centred at groundM
* when set, otherwise at the mid mount height. */
export function cellBounds(cell) {
const lat = (cell.north + cell.south) / 2;
const lon = wrapLongitude((cell.east + cell.west) / 2);
const height = Number.isFinite(cell.groundM)
? cell.groundM
: (cell.high + cell.low) / 2;
const { halfWidthM, halfHeightM } = cellHalfExtents(cell);
const halfWidth = Math.hypot(halfWidthM, halfHeightM);
const vertical = Math.max(cell.high - height, height - cell.low);
const radius = 1.2 * Math.hypot(halfWidth, vertical);
return { center: fromDegrees(lon, lat, height), radius: Math.max(1, radius) };
}
/** Add a whole ground cell to a marker, retaining the sums for a weighted mean. */
function addCell(target, cell) {
// Across the antimeridian a cell joins on the side of the group's mean.
const shift = target.count
? 360 *
Math.round(
(target.lonSum / target.count - cell.lonSum / cell.count) / 3.6e9,
)
: 0;
target.count += cell.count;
target.latSum += cell.latSum;
target.lonSum += cell.lonSum + shift * 1e7 * cell.count;
target.heightSum += cell.heightSum;
target.south = Math.min(target.south, cell.south);
target.north = Math.max(target.north, cell.north);
target.west = Math.min(target.west, cell.west + shift);
target.east = Math.max(target.east, cell.east + shift);
target.low = Math.min(target.low, cell.low);
target.high = Math.max(target.high, cell.high);
}
/** Visit the touching pills in this marker's bucket and its eight neighbors. */
function visitNeighbors(marker, grid, gap, visit) {
for (let col = -1; col <= 1; col++) {
for (let row = -1; row <= 1; row++) {
const bucket = grid.get(`${marker.col + col},${marker.row + row}`);
if (!bucket) continue;
for (const other of bucket) {
// Distance between the horizontal centre segments of the two pills.
const extra = marker.halfSegment + other.halfSegment;
const dx = Math.max(0, Math.abs(marker.x - other.x) - extra);
const dy = marker.y - other.y;
const reach = marker.radius + other.radius + gap;
if (dx * dx + dy * dy >= reach * reach) continue;
visit(other, dx * dx + dy * dy, reach);
}
}
}
}
/**
* Merge connected groups of overlapping horizontal pills. Each marker occupies
* one grid bucket. Even the widest pill can only touch its eight neighbors.
* A cell with one camera takes the footprint `sizeFor(1)` gives its icon and
* joins the nearest count it touches. Lone cameras never join each other
* or bridge two counts. A spread icon's `offsetPx` shifts its footprint sideways.
* A merged group lists its ground cells in `parts`.
* Ground cells stay intact for the camera picker and individual-icon pass.
*/
export function mergeCountCells(cells, project, sizeFor, gap) {
let columnWidth = 0;
let rowHeight = 0;
const markers = cells.map((cell) => {
const screen = project(cellCenter(cell));
const { width, height } = sizeFor(cell.count, cell);
columnWidth = Math.max(columnWidth, width + gap);
rowHeight = Math.max(rowHeight, height + gap);
// The view projector reuses its result object.
return {
cell,
x: screen ? screen.x + (cell.offsetPx ?? 0) : undefined,
y: screen?.y,
halfSegment: (width - height) / 2,
radius: height / 2,
};
});
const grid = new Map();
for (const marker of markers) {
if (!Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue;
marker.col = Math.floor(marker.x / columnWidth);
marker.row = Math.floor(marker.y / rowHeight);
const key = `${marker.col},${marker.row}`;
if (!grid.has(key)) grid.set(key, new Set());
marker.bucket = grid.get(key);
if (marker.cell.count > 1) marker.bucket.add(marker);
}
for (const marker of markers) {
if (marker.cell.count !== 1 || !marker.bucket) continue;
let best = Infinity;
visitNeighbors(marker, grid, gap, (other, distanceSquared, reach) => {
const clearance = Math.sqrt(distanceSquared) - reach;
if (clearance < best) {
best = clearance;
marker.nearest = other;
}
});
}
// Only counts were candidates for nearest. Now they can claim lone cameras.
for (const marker of markers)
if (marker.cell.count === 1) marker.bucket?.add(marker);
const members = [];
for (const seed of markers) {
if (seed.cell.count === 1 || !seed.bucket?.delete(seed)) continue;
members.length = 0;
members.push(seed);
for (const marker of members) {
if (marker.cell.count === 1) continue;
visitNeighbors(marker, grid, gap, (other) => {
if (other.cell.count === 1 && other.nearest !== marker) return;
other.bucket.delete(other);
members.push(other);
});
}
if (members.length === 1) {
seed.result = seed.cell;
} else {
const group = createCameraCell(seed.cell.key);
group.lone = [];
group.parts = [];
for (const { cell } of members) {
addCell(group, cell);
group.parts.push(...(cell.parts ?? [cell]));
if (cell.count === 1) group.lone.push(cell);
else if (cell.lone) group.lone.push(...cell.lone);
}
seed.result = group;
}
}
const groups = [];
for (const marker of markers) {
if (marker.result) groups.push(marker.result);
else if (!marker.bucket || marker.bucket.has(marker))
groups.push(marker.cell);
}
return groups;
}
/** Rebuild a group's count under its original key, keeping only the lone cameras in `keep`. */
export function withoutLoneCameras(group, keep = []) {
const counts = (group.parts ?? []).filter((cell) => cell.count > 1);
if (!counts.length) return null;
const core = createCameraCell(group.key);
core.parts = [...counts, ...keep];
if (keep.length) core.lone = [...keep];
for (const cell of core.parts) addCell(core, cell);
return core;
}
+216
View File
@@ -0,0 +1,216 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fromDegrees } from '../geo/ellipsoid.js';
import { distance } from '../geo/vector.js';
import { getLocale, setLocale } from '../i18n/index.js';
import {
createCameraCell,
addCellCamera,
cellCenter,
cellBounds,
formatCameraCount,
mergeCountCells,
} from './cctvCellCounts.js';
test('camera counts use Latin digits and K notation whatever the UI language', () => {
const previous = getLocale();
const examples = [
[2, '2'],
[999, '999'],
[1000, '1K'],
[1150, '1.2K'],
[1687, '1.7K'],
[9960, '10K'],
[10000, '10K'],
[12345, '12K'],
[12500, '13K'],
[1000000, '1000K'],
];
try {
setLocale('ar');
for (const [count, label] of examples)
assert.equal(formatCameraCount(count), label);
} finally {
setLocale(previous);
}
});
test('the marker mean weights every mount and the flight bounds cover the outlier', () => {
const cameras = [
{ lon: 12, lat: 52, absoluteHeightM: 30 },
{ lon: 12, lat: 52, absoluteHeightM: 40 },
{ lon: 12.003, lat: 52.006, absoluteHeightM: 50 },
];
const cell = createCameraCell();
for (const camera of cameras) addCellCamera(cell, camera);
const expected = fromDegrees(12.001, 52.002, 40);
assert.ok(distance(cellCenter(cell), expected) < 0.001);
const bounds = cellBounds(cell);
for (const { lon, lat, absoluteHeightM } of cameras) {
assert.ok(
distance(bounds.center, fromDegrees(lon, lat, absoluteHeightM)) <
bounds.radius,
);
}
});
function mergeCounts(sizes, counts, positions) {
const cells = counts.map((count, i) => ({
...createCameraCell(String(i)),
count,
}));
let i = 0;
const groups = mergeCountCells(
cells,
() => positions[i++],
(count) => sizes[count],
4,
);
return { cells, groups };
}
test('stadiums merge by their own radii and segment lengths across grid boundaries', () => {
const sizes = {
2: { width: 28, height: 28 },
7350: { width: 80, height: 48 },
};
const check = (counts, positions, expected) => {
const { groups } = mergeCounts(sizes, counts, positions);
assert.deepEqual(
groups.map((cell) => cell.count),
expected,
);
assert.equal(
groups.reduce((sum, cell) => sum + cell.count, 0),
counts[0] + counts[1],
);
};
const origin = { x: 35, y: 37 };
// Mixed radii sum to 38. At 42 pixels vertically the gap is exactly clear.
check([2, 7350], [origin, { x: 35, y: 78 }], [7352]);
check([2, 7350], [origin, { x: 35, y: 79 }], [2, 7350]);
// The large pill's centre segment extends 16 pixels towards the circle.
check([7350, 2], [origin, { x: 92, y: 37 }], [7352]);
check([7350, 2], [origin, { x: 92, y: 49 }], [7350, 2]);
check([2, 2], [origin, { x: 70, y: 37 }], [2, 2]);
// Large pills can reach across a row boundary at their full diameter.
check([7350, 7350], [origin, { x: 35, y: 88 }], [14700]);
});
test('a lone camera joins a count it touches, and lone cameras alone stay apart', () => {
const sizes = {
1: { width: 24, height: 24 },
9: { width: 40, height: 40 },
};
const check = (counts, positions, expected) => {
const { cells, groups } = mergeCounts(sizes, counts, positions);
assert.deepEqual(
groups.map((cell) => cell.count),
expected,
);
// A lone camera that stays apart is still its own cell object.
assert.deepEqual(
groups.filter((cell) => cell.count === 1),
cells.filter((cell) => groups.includes(cell) && cell.count === 1),
);
};
const at = (x, y = 100) => ({ x, y });
// Radii 20 and 12: the four-pixel gap is clear at 36 pixels.
check([9, 1], [at(100), at(135)], [10]);
check([9, 1], [at(100), at(136)], [9, 1]);
check([1, 9], [at(135), at(100)], [10]);
// Overlapping icons with no count beside them stay two icons.
check([1, 1], [at(100), at(110)], [1, 1]);
// A count takes every lone camera it touches, on either side.
check([1, 9, 1], [at(70), at(100), at(130)], [11]);
// A lone camera that only touches another lone camera is left alone.
check([1, 1, 9], [at(40), at(70), at(100)], [1, 10]);
});
test('cells merged across the antimeridian stay at the antimeridian', () => {
for (const lon of [179.9, 179.99, 179.999]) {
for (const reversed of [false, true]) {
const east = createCameraCell('e');
const west = createCameraCell('w');
for (let i = 0; i < 2; i++) {
addCellCamera(east, { lon, lat: 0, absoluteHeightM: 0 });
addCellCamera(west, { lon: -lon, lat: 0, absoluteHeightM: 0 });
}
const cells = reversed ? [west, east] : [east, west];
const screens = [
{ x: 100, y: 100 },
{ x: 120, y: 100 },
];
let i = 0;
const [group, ...rest] = mergeCountCells(
cells,
() => screens[i++],
() => ({ width: 40, height: 40 }),
4,
);
assert.equal(rest.length, 0);
assert.equal(group.count, 4);
const expected = fromDegrees(180, 0, 0);
assert.ok(distance(cellCenter(group), expected) < 1000, `${lon}: centre`);
const bounds = cellBounds(group);
assert.ok(bounds.radius < 15_000, `${lon}: radius ${bounds.radius}`);
for (const l of [lon, -lon])
assert.ok(
distance(bounds.center, fromDegrees(l, 0, 0)) <= bounds.radius,
);
}
}
});
test('flight bounds on drawn ground still contain every mount', () => {
// Flat ellipsoid terrain (Re:Earth terrain failed), mounts at 1,800 m.
const flat = createCameraCell('k');
addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 });
addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 });
flat.groundM = 0;
const fb = cellBounds(flat);
assert.ok(
distance(fromDegrees(10, 46, 1800), fb.center) <= fb.radius,
'flat',
);
// Ravine: mounts 200 m apart at 600 m, the floor at 0 m between them.
const east = 10 + 200 / (111_320 * Math.cos((46 * Math.PI) / 180));
const ravine = createCameraCell('r');
addCellCamera(ravine, { lon: 10, lat: 46, absoluteHeightM: 600 });
addCellCamera(ravine, { lon: east, lat: 46, absoluteHeightM: 600 });
ravine.groundM = 0;
const rb = cellBounds(ravine);
for (const lon of [10, east])
assert.ok(
distance(fromDegrees(lon, 46, 600), rb.center) <= rb.radius,
'ravine',
);
});
test('a lone camera between two counts joins one of them and does not merge them', () => {
const sizes = { 1: { width: 24, height: 24 }, 9: { width: 40, height: 40 } };
const run = (counts, xs) =>
mergeCounts(
sizes,
counts,
xs.map((x) => ({ x, y: 100 })),
)
.groups.map((cell) => cell.count)
.sort((a, b) => a - b);
assert.deepEqual(run([9, 9], [70, 130]), [9, 9]);
for (const [counts, xs] of [
[
[9, 1, 9],
[70, 100, 130],
],
[
[1, 9, 9],
[100, 70, 130],
],
[
[9, 9, 1],
[70, 130, 100],
],
])
assert.deepEqual(run(counts, xs), [9, 10], String(counts));
});
+155 -54
View File
@@ -12,6 +12,14 @@ import {
parseTarkteeDatexLocations,
} from '../../server/providers/cctv/sources.js';
/**
* Disarm the 30 s deadline, so a loader that only stops at that deadline
* fails at the test timeout instead of passing late.
*/
function withoutDeadline(t) {
t.mock.method(AbortSignal, 'timeout', () => new AbortController().signal);
}
/** Silence the loaders' progress and failure logging. */
function quiet(t) {
t.mock.method(console, 'log', () => {});
@@ -97,6 +105,29 @@ test('Tarktee DATEX image parser rejects non-official hosts', () => {
assert.equal(images.size, 0);
});
test('Tarktee DATEX requests wait 30 s, past the slow answers measured live', async (t) => {
const timeouts = [];
const timeout = AbortSignal.timeout;
t.mock.method(AbortSignal, 'timeout', (ms) => {
timeouts.push(ms);
return timeout.call(AbortSignal, ms);
});
t.mock.method(console, 'log', () => {});
t.mock.method(
globalThis,
'fetch',
async (url) =>
new Response(
String(url).includes('roadCameraLocations')
? SAMPLE_LOCATIONS_XML
: SAMPLE_IMAGES_XML,
),
);
const cameras = await loadTarkteeSourcesFromDatex();
assert.deepEqual(timeouts, [30_000]);
assert.equal(cameras.length, 1);
});
test('Tarktee loader deduplicates cameras sharing an image number before the cap', async (t) => {
quiet(t);
const dupLocationsXml = `<?xml version="1.0" encoding="UTF-8"?>
@@ -168,46 +199,6 @@ test('Tarktee loader refuses a redirect and cancels both response bodies', async
assert.equal(cancelled.images, true, 'sibling 200 body is also cancelled');
});
test('Tarktee loader cancels fulfilled bodies when either fetch rejects', async (t) => {
for (const failedUrl of [TARKTEE_LOCATIONS_URL, TARKTEE_IMAGES_URL]) {
for (const delayedSibling of [false, true]) {
await t.test(
`${failedUrl}, delayed sibling: ${delayedSibling}`,
async (t) => {
quiet(t);
let cancelled = false;
const response = new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('<xml/>'));
},
cancel() {
cancelled = true;
},
}),
);
t.mock.method(globalThis, 'fetch', async (url) => {
if (String(url) === failedUrl) throw new TypeError('fetch failed');
if (delayedSibling) await new Promise(setImmediate);
return response;
});
try {
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
assert.equal(
cancelled,
true,
'fulfilled sibling body is cancelled',
);
} finally {
await response.body.cancel();
}
},
);
}
}
});
test('Tarktee loader cancels the sibling body when one feed fails or overflows the byte cap', async (t) => {
quiet(t);
let siblingCancelled = false;
@@ -264,25 +255,135 @@ test('Tarktee loader cancels the sibling body when one feed fails or overflows t
);
});
test('Tarktee DATEX requests wait 30 s, past the slow answers measured live', async (t) => {
const timeouts = [];
const timeout = AbortSignal.timeout;
t.mock.method(AbortSignal, 'timeout', (ms) => {
timeouts.push(ms);
return timeout.call(AbortSignal, ms);
});
t.mock.method(console, 'log', () => {});
for (const failingUrl of [TARKTEE_LOCATIONS_URL, TARKTEE_IMAGES_URL]) {
for (const lateSibling of [false, true]) {
test(
`Tarktee cancels a ${lateSibling ? 'late' : 'received'} sibling when ${failingUrl} rejects before headers`,
{ timeout: 2000 },
async (t) => {
quiet(t);
withoutDeadline(t);
let cancelled = false;
let siblingSignal;
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
t.mock.method(globalThis, 'fetch', async (url, init) => {
if (String(url) === failingUrl)
throw new Error('headers unavailable');
siblingSignal = init.signal;
// A late transport answers once the sibling is aborted, or on release.
if (lateSibling)
await Promise.race([
gate,
new Promise((resolve) =>
init.signal.addEventListener('abort', resolve, { once: true }),
),
]);
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('<xml/>'));
},
cancel() {
cancelled = true;
},
}),
);
});
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
// Also exercise a response arriving after abort, as a queued transport
// completion can race the rejection owner even when fetch honors abort.
if (lateSibling) {
release();
await new Promise((resolve) => setImmediate(resolve));
}
assert.equal(cancelled, true, 'every obtained body must be cancelled');
assert.equal(
siblingSignal.aborted,
true,
'a pending transport is aborted immediately',
);
},
);
}
test(
`Tarktee aborts a pending sibling when ${failingUrl} rejects`,
{ timeout: 2000 },
async (t) => {
quiet(t);
withoutDeadline(t);
let aborted = false;
t.mock.method(globalThis, 'fetch', async (url, init) => {
if (String(url) === failingUrl) throw new Error('headers unavailable');
return new Promise((resolve, reject) => {
init.signal.addEventListener(
'abort',
() => {
aborted = true;
reject(init.signal.reason);
},
{ once: true },
);
});
});
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
assert.equal(aborted, true, 'do not wait for the 30-second deadline');
},
);
}
test('Tarktee cancels both lengthless streams when one exceeds the byte cap', async (t) => {
quiet(t);
const cancelled = [];
t.mock.method(
globalThis,
'fetch',
async (url) =>
new Response(
String(url).includes('roadCameraLocations')
? SAMPLE_LOCATIONS_XML
: SAMPLE_IMAGES_XML,
new ReadableStream({
start(controller) {
const oversized = String(url) === TARKTEE_LOCATIONS_URL;
controller.enqueue(
new Uint8Array(oversized ? TARKTEE_MAX_CATALOG_BYTES + 1 : 1),
);
},
cancel() {
cancelled.push(String(url));
},
}),
),
);
const cameras = await loadTarkteeSourcesFromDatex();
assert.deepEqual(timeouts, [30_000, 30_000]);
assert.equal(cameras.length, 1);
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
assert.deepEqual(
cancelled.sort(),
[TARKTEE_LOCATIONS_URL, TARKTEE_IMAGES_URL].sort(),
);
});
test(
'Tarktee aborts pending headers as soon as its sibling returns an HTTP error',
{ timeout: 2000 },
async (t) => {
quiet(t);
withoutDeadline(t);
let aborted = false;
t.mock.method(globalThis, 'fetch', async (url, init) => {
if (String(url) === TARKTEE_LOCATIONS_URL)
return new Response('unavailable', { status: 503 });
return new Promise((resolve, reject) => {
init.signal.addEventListener(
'abort',
() => {
aborted = true;
reject(init.signal.reason);
},
{ once: true },
);
});
});
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
assert.equal(aborted, true);
},
);
+112
View File
@@ -0,0 +1,112 @@
// A body-phase failure of one Tarktee DATEX feed must abort the sibling that is
// still waiting for headers instead of leaving it until the 30 s deadline.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import {
TARKTEE_IMAGES_URL,
TARKTEE_LOCATIONS_URL,
TARKTEE_MAX_CATALOG_BYTES,
} from '../../server/providers/cctv/constants.js';
import { loadTarkteeSourcesFromDatex } from '../../server/providers/cctv/sources.js';
/** The sibling sends its headers this late; the loader must not wait for it. */
const SIBLING_HEADER_DELAY_MS = 2000;
/** Generous bound for "at once" on a loaded CI machine. */
const FAIL_FAST_MS = 1000;
function startServer(handlers) {
const server = http.createServer((req, res) => handlers[req.url](req, res));
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => resolve(server));
});
}
/** Send the two DATEX URLs to the local server through the real fetch. */
function routeFetchTo(t, port) {
const realFetch = globalThis.fetch;
t.mock.method(globalThis, 'fetch', (url, init) => {
const path =
String(url) === TARKTEE_LOCATIONS_URL
? '/loc'
: String(url) === TARKTEE_IMAGES_URL
? '/img'
: null;
assert.ok(path, `unexpected url ${url}`);
return realFetch(`http://127.0.0.1:${port}${path}`, init);
});
}
/** The sibling answers late and reports whether it was cut off before headers. */
function slowSibling() {
const arrived = Promise.withResolvers();
const closed = Promise.withResolvers();
return {
arrived: arrived.promise,
closed: closed.promise,
handler(req, res) {
arrived.resolve();
const timer = setTimeout(() => {
res.writeHead(200, { 'content-type': 'application/xml' });
res.end('<d2LogicalModel/>');
}, SIBLING_HEADER_DELAY_MS);
res.on('close', () => {
clearTimeout(timer);
closed.resolve({ beforeHeaders: !res.headersSent });
});
},
};
}
const failingBodies = {
'declares a body over the byte cap': (req, res) => {
res.writeHead(200, {
'content-type': 'application/xml',
'content-length': String(TARKTEE_MAX_CATALOG_BYTES + 1),
});
res.write('<d2LogicalModel>');
},
'resets the connection mid-body': (req, res) => {
res.writeHead(200, { 'content-type': 'application/xml' });
res.write('<d2LogicalModel><payloadPublication>');
setTimeout(() => res.socket.destroy(), 20);
},
};
for (const [label, failingFeed] of Object.entries(failingBodies)) {
for (const [failing, pending] of [
['/loc', '/img'],
['/img', '/loc'],
]) {
test(`Tarktee aborts ${pending} pending headers when ${failing} ${label}`, { timeout: 10_000 }, async (t) => {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
const sibling = slowSibling();
const server = await startServer({
[failing]: (req, res) =>
sibling.arrived.then(() => failingFeed(req, res)),
[pending]: sibling.handler,
});
t.after(() => {
server.closeAllConnections();
server.close();
});
routeFetchTo(t, server.address().port);
const started = Date.now();
const cameras = await loadTarkteeSourcesFromDatex();
const elapsed = Date.now() - started;
assert.deepEqual(cameras, []);
assert.ok(
elapsed < FAIL_FAST_MS,
`loader waited ${elapsed} ms for the sibling's headers instead of aborting it`,
);
assert.deepEqual(
await sibling.closed,
{ beforeHeaders: true },
`${pending} was not aborted`,
);
});
}
}
@@ -0,0 +1,138 @@
// An explicit pick of the camera that a settled move just re-opened must end
// the opening pick. That pick goes through setActiveCamera's UNCHANGED path
// (same camera, already activated); if that path keeps the provisional flag,
// the next settled move (a pan, or the landing of NEAREST's own flight)
// switches the camera away from the one the user chose.
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import cctvLayer, {
_setCctvCoverageStateForTest,
_setCctvOverlayHostForTest,
reopenNearestCamera,
} from './cctv.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
const BASE = {
headingDeg: 41,
pitchDeg: -5,
fovDeg: 56,
rangeM: 210,
mountHeightM: 100,
groundElevationM: 0,
city: 'London',
};
function record(id, lat, lon) {
return {
camera: { ...BASE, id, name: `Camera ${id}`, lat, lon },
coverageEntities: [],
projection: null,
activationDone: true,
groundResolved: {},
groundSamples: {},
groundPrior: 0,
frustumGeometry: null,
frustumPositions: null,
probeClampRangeM: null,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 100),
};
}
function viewerAt(lat, lon) {
const viewer = {
isDestroyed: () => false,
eye: { lat, lon, height: 300 },
scene: {
canvas: { clientWidth: 1200, clientHeight: 800 },
cartesianToCanvasCoordinates: () => undefined,
primitives: { add: (p) => p, remove: () => true },
requestRender() {},
},
};
// The layer reads the eye and flies through the renderer's camera port.
viewer.draw = bindFakeDraw(viewer, {
camera: {
pose: () => ({ ...viewer.eye }),
on: () => () => {},
followed: null,
flyToBounds() {},
},
}).draw;
return viewer;
}
function moveViewer(viewer, lat, lon) {
viewer.eye = { lat, lon, height: 300 };
}
function withReopenedLayer(fn) {
_setCctvOverlayHostForTest({
setEntries() {},
setVisible() {},
clearSource() {},
});
// Activation builds the projection canvas and frame image.
const originalDocument = globalThis.document;
const originalImage = globalThis.Image;
globalThis.document = { createElement: () => ({ getContext: () => null }) };
globalThis.Image = class {};
try {
const trafalgar = record('a-trafalgar', 51.508, -0.128);
const cambridge = record('b-cambridge', 51.513, -0.129);
// enable() assigned the opening camera without activating it.
trafalgar.activationDone = false;
const viewer = viewerAt(51.5081, -0.1281);
_setCctvCoverageStateForTest({
viewer,
records: [trafalgar, cambridge],
activeCameraId: 'a-trafalgar',
enabled: true,
openingCameraProvisional: true,
});
// A settled move next to Cambridge Circus re-opens there, still as the
// opening pick.
moveViewer(viewer, 51.5131, -0.1291);
assert.equal(reopenNearestCamera(), true);
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
fn(viewer);
} finally {
globalThis.document = originalDocument;
globalThis.Image = originalImage;
_setCctvOverlayHostForTest();
_setCctvCoverageStateForTest({ enabled: false });
}
}
for (const [name, pick] of [
['NEAREST (focusNearest)', () => cctvLayer.focusNearest({ focus: false })],
['selectCamera', () => cctvLayer.selectCamera('b-cambridge')],
[
'setParams({ selectedCameraId })',
() => cctvLayer.setParams({ selectedCameraId: 'b-cambridge' }),
],
[
'focusNearestToPoint',
() => cctvLayer.focusNearestToPoint(51.513, -0.129, { focus: false }),
],
]) {
test(`an explicit ${name} pick of the re-opened camera ends the opening pick`, () => {
withReopenedLayer((viewer) => {
pick();
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
// A later settled move (a pan, or the landing of the pick's own flight)
// leaves the explicit choice alone.
moveViewer(viewer, 51.5081, -0.1281);
assert.equal(reopenNearestCamera(), false);
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
});
});
}
test('without a pick, the next settled move still follows the view', () => {
withReopenedLayer((viewer) => {
moveViewer(viewer, 51.5081, -0.1281);
assert.equal(reopenNearestCamera(), true);
assert.equal(cctvLayer.getUIState().activeCameraId, 'a-trafalgar');
});
});
+20 -17
View File
@@ -140,25 +140,28 @@ for (const [label, flag] of [
});
}
test('a failed catalog cancels the sibling request instead of waiting for the timeout', async (t) => {
t.mock.method(console, 'warn', () => {});
let siblingSignal;
t.mock.method(globalThis, 'fetch', async (url, options) => {
if (url === LITHUANIA_CAMERAS_URL) {
return new Response('', { status: 503 });
}
siblingSignal = options.signal;
// Never settles on its own; only an abort ends it.
return new Promise((_, reject) => {
options.signal.addEventListener('abort', () =>
reject(options.signal.reason),
);
for (const [failure, camerasResponse] of [
['failed', () => new Response('', { status: 503 })],
['malformed', () => new Response('<html>error page</html>')],
]) {
test(`a ${failure} catalog cancels the sibling request instead of waiting for the timeout`, async (t) => {
t.mock.method(console, 'warn', () => {});
let siblingSignal;
t.mock.method(globalThis, 'fetch', async (url, options) => {
if (url === LITHUANIA_CAMERAS_URL) return camerasResponse();
siblingSignal = options.signal;
// Never settles on its own; only an abort ends it.
return new Promise((_, reject) => {
options.signal.addEventListener('abort', () =>
reject(options.signal.reason),
);
});
});
assert.deepEqual(await loadLithuaniaSources(), []);
assert.equal(siblingSignal?.aborted, true);
assert.notEqual(siblingSignal.reason?.name, 'TimeoutError');
});
assert.deepEqual(await loadLithuaniaSources(), []);
assert.equal(siblingSignal?.aborted, true);
assert.notEqual(siblingSignal.reason?.name, 'TimeoutError');
});
}
test('a redirected catalog is reported as not followed', async (t) => {
const warnings = [];
+103 -2
View File
@@ -111,6 +111,7 @@ function mount(t, respond) {
austin: process.env.CCTV_FORCE_AUSTIN,
serverKey: process.env.GOOGLE_MAPS_SERVER_API_KEY,
browserKey: process.env.GOOGLE_MAPS_API_KEY,
rateLimit: process.env.GEV_RATELIMIT_GOOGLE_PER_MIN,
};
process.env.CCTV_SOURCES_JSON = JSON.stringify([
STILL,
@@ -125,6 +126,8 @@ function mount(t, respond) {
// than a network call this file does not model.
delete process.env.GOOGLE_MAPS_SERVER_API_KEY;
delete process.env.GOOGLE_MAPS_API_KEY;
// The default Google budget, whatever the shell sets.
delete process.env.GEV_RATELIMIT_GOOGLE_PER_MIN;
const nativeFetch = globalThis.fetch;
const requests = [];
globalThis.fetch = async (url, init = {}) => {
@@ -139,6 +142,7 @@ function mount(t, respond) {
['CCTV_FORCE_AUSTIN', before.austin],
['GOOGLE_MAPS_SERVER_API_KEY', before.serverKey],
['GOOGLE_MAPS_API_KEY', before.browserKey],
['GEV_RATELIMIT_GOOGLE_PER_MIN', before.rateLimit],
]) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
@@ -155,9 +159,9 @@ function mount(t, respond) {
});
assert.ok(handler, 'the CCTV provider must mount a middleware');
const call = async (path, headers = {}) => {
const call = async (path, headers = {}, socket) => {
const { res, done } = recordingResponse();
await handler({ url: path, headers, method: 'GET', on() {} }, res);
await handler({ url: path, headers, method: 'GET', on() {}, socket }, res);
await done;
return res;
};
@@ -528,3 +532,100 @@ test('a forwarded same-origin request reaches every CCTV route but not the Stree
assert.equal(direct.body, 'street-view');
assert.equal(streetViewCalls(), 1);
});
test('the Street View fallback frames catalog cameras only, from the catalog position', async (t) => {
const app = mount(t, ({ url }) =>
url.startsWith('https://maps.googleapis.com/')
? trackedUpstream({
headers: { 'content-type': 'image/jpeg' },
body: 'street-view',
}).response
: upstreamResponse({ status: 503 }),
);
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
const streetView = () =>
app.requests.filter(({ url }) =>
url.startsWith('https://maps.googleapis.com/'),
);
const unknown = await app.call('/frame/not-a-camera?lat=48.85&lon=2.29');
assert.equal(unknown.headers['X-CCTV-Source'], 'synthetic');
assert.deepEqual(streetView(), [], 'no Google call for an unknown id');
const steered = await app.call(
`/frame/${STILL.id}?lat=48.85&lon=2.29&heading=90&fov=74&pitch=-17`,
);
assert.equal(steered.headers['X-CCTV-Source'], 'streetview');
const sv = new URL(streetView()[0].url).searchParams;
assert.equal(sv.get('location'), `${STILL.lat},${STILL.lon}`);
assert.equal(sv.get('heading'), '90');
assert.equal(sv.get('fov'), '74');
assert.equal(sv.get('pitch'), '-17');
});
test('the Street View fallback spends a per-IP Google budget, and only with a key', async (t) => {
const app = mount(t, ({ url }) =>
url.startsWith('https://maps.googleapis.com/')
? trackedUpstream({
headers: { 'content-type': 'image/jpeg' },
body: 'street-view',
}).response
: upstreamResponse({ status: 503 }),
);
// Read when the first keyed fallback builds the limiter, so after mount().
process.env.GEV_RATELIMIT_GOOGLE_PER_MIN = '2';
const streetViewCalls = () =>
app.requests.filter(({ url }) =>
url.startsWith('https://maps.googleapis.com/'),
).length;
const first = { remoteAddress: '203.0.113.7' };
const frameSource = async (socket) =>
(await app.call(`/frame/${STILL.id}`, {}, socket)).headers['X-CCTV-Source'];
// Without a key nothing is spent.
for (let i = 0; i < 3; i++)
assert.equal(await frameSource(first), 'synthetic');
assert.equal(streetViewCalls(), 0);
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
// Neither an unknown id nor a forwarded request spends the window.
assert.equal(
(await app.call('/frame/not-a-camera', {}, first)).headers['X-CCTV-Source'],
'synthetic',
);
assert.equal(
(
await app.call(
`/frame/${STILL.id}`,
{ 'x-forwarded-for': '203.0.113.9' },
first,
)
).headers['X-CCTV-Source'],
'synthetic',
);
assert.deepEqual(
[
await frameSource(first),
await frameSource(first),
await frameSource(first),
],
['streetview', 'streetview', 'synthetic'],
);
assert.equal(streetViewCalls(), 2, 'no Google call over the budget');
// Another address has a budget of its own.
assert.equal(
await frameSource({ remoteAddress: '203.0.113.8' }),
'streetview',
);
assert.equal(streetViewCalls(), 3);
// Addresses within one IPv6 /64 share a budget.
const v6 = (remoteAddress) => frameSource({ remoteAddress });
assert.deepEqual(
[await v6('2001:db8::1'), await v6('2001:db8::2'), await v6('2001:db8::3')],
['streetview', 'streetview', 'synthetic'],
);
assert.equal(await v6('2001:db8:0:1::1'), 'streetview', 'another /64');
assert.equal(streetViewCalls(), 6);
});
@@ -0,0 +1,87 @@
// Real sockets: a client that closes its connection while the camera upstream
// is still pending must not get a Street View call outside its own budget.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { cctvProxy } from '../../server/providers/cctv.js';
const CAM = {
id: 'still-fixture',
name: 'Still fixture',
lat: 30.27,
lon: -97.74,
feedType: 'image',
url: 'https://cams.upstream.invalid/still.jpg',
};
test('a client that disconnects mid-fetch stays inside its own Street View budget', async (t) => {
const saved = { ...process.env };
process.env.CCTV_SOURCES_JSON = JSON.stringify([CAM]);
process.env.CCTV_SOURCES_FILE = 'absent-source-file.json';
process.env.CCTV_FORCE_AUSTIN = '0';
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
delete process.env.GOOGLE_MAPS_API_KEY;
process.env.GEV_RATELIMIT_GOOGLE_PER_MIN = '1';
const nativeFetch = globalThis.fetch;
let streetViewCalls = 0;
globalThis.fetch = async (url) => {
if (String(url).startsWith('https://maps.googleapis.com/')) {
streetViewCalls += 1;
return new Response('street-view', {
headers: { 'content-type': 'image/jpeg' },
});
}
await new Promise((r) => setTimeout(r, 400));
return new Response(null, { status: 503 });
};
let handler;
cctvProxy().configureServer({
middlewares: { use: (_r, fn) => (handler = fn) },
});
const server = http.createServer((req, res) => {
req.url = req.url.replace(/^\/api\/cctv/, '');
handler(req, res, () => res.end());
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => {
server.close();
globalThis.fetch = nativeFetch;
for (const k of Object.keys(process.env))
if (!(k in saved)) delete process.env[k];
Object.assign(process.env, saved);
});
const { port } = server.address();
const get = (abortAfterMs) =>
new Promise((resolve) => {
const req = http.get(
{
host: '127.0.0.1',
port,
path: `/api/cctv/frame/${CAM.id}`,
headers: { host: `localhost:${port}` },
agent: false,
},
(res) => {
res.resume();
res.on('end', () => resolve(res.headers['x-cctv-source']));
},
);
req.on('error', () => resolve('aborted'));
if (abortAfterMs)
setTimeout(() => {
req.destroy();
resolve('aborted');
}, abortAfterMs);
});
assert.equal(await get(), 'streetview');
assert.equal(await get(), 'synthetic', 'the cap of one is spent');
assert.equal(streetViewCalls, 1);
await get(50);
await new Promise((r) => setTimeout(r, 800));
assert.equal(
streetViewCalls,
1,
'an aborted request spent the key outside its own budget',
);
});
+254
View File
@@ -0,0 +1,254 @@
import { afterEach, beforeEach, test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import cctvLayer, {
_cctvIconsForTest,
_setCctvCoverageStateForTest,
refreshHorizonCulling,
} from './cctv.js';
const WIDTH = 800;
const HEIGHT = 600;
const bindings = [];
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 8,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
for (const unbind of bindings.splice(0)) unbind();
});
function recordsAt(lonLats, height = 10) {
return lonLats.map(([lon, lat], index) => {
const position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
return {
camera: {
id: `cam-${String(index).padStart(4, '0')}`,
name: `Camera ${index}`,
city: 'Test',
lat,
lon,
headingDeg: 0,
pitchDeg: -18,
fovDeg: 44,
rangeM: 145,
mountHeightM: 8,
absoluteHeightM: height,
},
position: { x: position.x, y: position.y, z: position.z },
groundSamples: {},
groundResolved: {},
coverageEntities: [],
projection: null,
};
});
}
const plain = ({ x, y, z }) => ({ x, y, z });
function lookingAt(eye, target, ports = {}) {
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(direction, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3());
return {
viewer: viewerWithAxes(eye, direction, right, up, ports),
direction,
right,
up,
};
}
function topDown(height, ports = {}) {
const eye = Cesium.Cartesian3.fromDegrees(0, 0, height);
return viewerWithAxes(
eye,
{ x: -1, y: 0, z: 0 },
{ x: 0, y: 1, z: 0 },
{ x: 0, y: 0, z: 1 },
ports,
);
}
function viewerWithAxes(eye, direction, right, up, ports) {
const carto = Cesium.Cartographic.fromCartesian(eye);
const { port } = fakeCameraPort({
pose: {
lon: Cesium.Math.toDegrees(carto.longitude),
lat: Cesium.Math.toDegrees(carto.latitude),
height: carto.height,
position: plain(eye),
direction: plain(direction),
up: plain(up),
right: plain(right),
fovy: Math.PI / 3,
aspectRatio: WIDTH / HEIGHT,
near: 0.1,
far: 5e8,
},
});
const viewer = {};
bindings.push(
bindRenderer(viewer, {
camera: port,
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
draw: fakeDrawPort(),
...ports,
}),
);
return viewer;
}
/** Pinhole projection, as the layer's projector. */
function project(view, eye, point) {
const d = Cesium.Cartesian3.subtract(point, eye, new Cesium.Cartesian3());
const z = Cesium.Cartesian3.dot(d, view.direction);
const t = Math.tan(Math.PI / 6);
const x = Cesium.Cartesian3.dot(d, view.right) / z / (t * (WIDTH / HEIGHT));
const y = Cesium.Cartesian3.dot(d, view.up) / z / t;
return { x: (0.5 + x / 2) * WIDTH, y: (0.5 - y / 2) * HEIGHT, z };
}
for (const [label, horizontalM, aboveM] of [
['100 m approach', 100, 4],
['800 m approach', 800, 50],
]) {
test(`a camera with a stale height is read even when it projects off the screen at ${label}`, () => {
const ground = 1872;
const records = recordsAt([
[0, 0],
[0, 0],
]);
// geoid fallback after a 429
for (const r of records)
r.groundPrior = { ellipsoid: 2, source: 'geoid-fallback' };
const mount = Cesium.Cartesian3.fromDegrees(0, 0, ground + 8);
const eye = Cesium.Cartesian3.fromDegrees(
0,
-horizontalM / 111_320,
ground + 8 + aboveM,
);
const reads = [];
const view = lookingAt(eye, mount, {
globe: { isGlobeVisible: () => true },
query: {
sampleHeightNow(point) {
reads.push(point);
return ground;
},
},
});
_setCctvCoverageStateForTest({ viewer: view.viewer, records });
const stale = project(view, eye, records[0].position);
const truth = project(view, eye, mount);
assert.ok(stale.y > HEIGHT * 2);
assert.ok(truth.y > 0 && truth.y < HEIGHT);
refreshHorizonCulling();
refreshHorizonCulling();
assert.equal(records[0].groundPrior.ellipsoid, ground);
assert.ok(reads.length > 0, 'the stale camera was never read');
});
}
test('cameras off the visible screen cannot spend the whole terrain read budget', () => {
// 300 cameras with no prior around the screen edge, tiles not loaded; the
// 301st at the screen centre over a loaded tile.
const lonLats = [];
for (let i = 0; i < 300; i++) {
const a = (i / 300) * 2 * Math.PI;
// ~ 0.8 screen widths out at 200 m altitude (screen ~ 307 m wide)
lonLats.push([
(Math.cos(a) * 250) / 111_320,
(Math.sin(a) * 190) / 111_320,
]);
}
lonLats.push([0, 0]);
const records = recordsAt(lonLats);
const perPass = [];
let reads;
const viewer = topDown(200, {
globe: { isGlobeVisible: () => true },
query: {
sampleHeightNow(point) {
reads.push(point);
return Math.abs(point.lon) < 1e-9 && Math.abs(point.lat) < 1e-9
? 40
: null;
},
},
});
_setCctvCoverageStateForTest({ viewer, records });
for (let pass = 0; pass < 3; pass++) {
reads = [];
refreshHorizonCulling();
perPass.push(reads.length);
}
const last = records.at(-1);
assert.equal(last.groundPrior?.ellipsoid, 40);
assert.ok(perPass.every((n) => n <= 300));
});
test("the active camera's icon moves beside a count that would cover it", () => {
const records = recordsAt([
[0, 0],
[0, 0],
[0, 0],
]);
const viewer = topDown(20_000);
_setCctvCoverageStateForTest({ viewer, records, activeCameraId: 'cam-0000' });
refreshHorizonCulling();
const icons = _cctvIconsForTest();
const [marker] = cctvLayer._cctvDrawnForTest().counts.markers;
const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 19_990;
const apartPx =
Cesium.Cartesian3.distance(marker.pos, icons.item('cam-0000').pos) /
metresPerPixel;
assert.ok(apartPx > marker.width / 2, 'the marker covers the active icon');
});
test('a lone camera just inside the grouping threshold joins the count beside it', () => {
const h = 740;
// mounts at 8 m mount height above a 0 m ground: positions at 10 m, eye at h+10
const records = recordsAt([
[0, 235 / 111_320],
[0, 255 / 111_320],
[0, 255 / 111_320],
]);
for (const r of records) r.groundPrior = { ellipsoid: 2, source: 'reearth' };
const viewer = topDown(h + 10);
_setCctvCoverageStateForTest({ viewer, records });
refreshHorizonCulling();
const icons = _cctvIconsForTest();
const markers = cctvLayer._cctvDrawnForTest().counts.markers;
assert.deepEqual(
markers.map((marker) => marker.cell.count),
[3],
);
assert.equal(
icons.item('cam-0000').show,
false,
'the near singleton still draws beside the count',
);
});
File diff suppressed because it is too large. Load diff
+27 -3
View File
@@ -166,6 +166,30 @@ export const DATA_CREDITS = [
'(<a href="https://celestrak.org" target="_blank" rel="noopener">celestrak.org</a>), ' +
'Dr. T.S. Kelso',
},
{
key: 'nasa-iss-model',
html:
'ISS model: ' +
'<a href="https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/" target="_blank" rel="noopener">NASA 3D Resources</a> (JSC IGOAL)',
},
{
key: 'tiangong-model',
html:
"Tiangong model: made for God's Eye View; dimensions from " +
'<a href="https://doi.org/10.34133/space.0035" target="_blank" rel="noopener">Wang, Zhang &amp; Wang 2023</a> ' +
'(CC BY 4.0) and eoPortal',
},
{
key: 'nasa-iss-telemetry',
html: 'ISS joint telemetry (where switched on): NASA ISSLive, via Lightstreamer',
},
{
key: 'nasa-iss-live',
html:
'ISS live video (LIVE section): NASA, via YouTube ' +
'(<a href="https://www.youtube.com/watch?v=ROboUHfPUrU" target="_blank" rel="noopener">exterior cameras</a>, ' +
'<a href="https://www.youtube.com/watch?v=M3HKLzjvKPc" target="_blank" rel="noopener">live video and audio</a>)',
},
{
key: 'ucs-satellite-database',
html:
@@ -303,9 +327,9 @@ export const DATA_CREDITS = [
key: 'ontario-511-cctv',
html:
'CCTV cameras &amp; frames (Ontario): ' +
'<a href="https://511on.ca/" target="_blank" rel="noopener">Ontario 511</a> ' +
'(<a href="https://www.ontario.ca/page/open-government-licence-ontario" target="_blank" rel="noopener">Open Government Licence - Ontario</a>) ' +
'· provided as is, without warranty; actual road conditions may differ',
'<a href="https://511on.ca/" target="_blank" rel="noopener">Ontario 511</a>. ' +
'Contains information licensed under the <a href="https://www.ontario.ca/page/open-government-licence-ontario" target="_blank" rel="noopener">Open Government Licence – Ontario</a>. ' +
'Provided as is, without warranty; actual road conditions may differ.',
},
{
key: 'fintraffic-cctv',
+12
View File
@@ -173,6 +173,18 @@ test('the NYC camera credit carries NYC DOT’s requested disclaimer', () => {
assert.match(credit.html, /observe posted signage/);
});
test('the Ontario 511 camera credit carries the licence attribution statement', () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'ontario-511-cctv');
assert.ok(credit, 'Ontario 511 camera frames must be credited');
assert.ok(
credit.html.includes(
'Contains information licensed under the <a href="https://www.ontario.ca/page/open-government-licence-ontario"',
),
);
assert.match(credit.html, />Open Government Licence – Ontario<\/a>/);
assert.match(credit.html, /Provided as is, without warranty/);
});
test("the Houston camera credit names TranStar's terms and the permission they require", () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'houston-cctv');
assert.ok(credit, 'Houston TranStar camera frames must be credited');
+1 -1
View File
@@ -32,7 +32,7 @@ export function createInfrastructureLayers(services) {
name: 'Dams',
color: '#0088ff', // Blue
icon: '▰',
source: 'USACE',
source: 'OpenStreetMap / OpenInfraMap',
osmDerived: true,
labels: true,
labelMax: 900,
+79 -2
View File
@@ -6,6 +6,7 @@ import { createInfrastructureLayers } from 'gods-eye-view/infrastructure';
import { createLocalGeoJsonLayer } from 'gods-eye-view/infrastructure/geojson';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { parseGeojsonLines } from '../sources/infrastructureData.js';
function services() {
const records = new Map();
@@ -34,6 +35,20 @@ function services() {
};
}
// Added from the OSM API, not the OpenInfraMap extract: [id, name, OSM
// object, version]. Both must stay polygons: the Dams layer skips
// LineStrings.
const OSM_API_DAMS = [
[262532166, 'Acaray', 'way/262532166', 7],
[-5671745, 'Represa Yacyretá-Apipé', 'relation/5671745', 2],
];
const DAMS = parseGeojsonLines(
readFileSync(
new URL('./local_data/dams/dams.geojsonl', import.meta.url),
'utf8',
),
);
test('package exports import without an application, DOM, fetch, or timers', () => {
const result = spawnSync(
process.execPath,
@@ -66,7 +81,11 @@ test('infrastructure factory preserves identity and creates independent state wi
first.map(({ id, name, source }) => ({ id, name, source })),
[
{ id: 'local-datacenters', name: 'Datacenters', source: 'Local' },
{ id: 'local-dams', name: 'Dams', source: 'USACE' },
{
id: 'local-dams',
name: 'Dams',
source: 'OpenStreetMap / OpenInfraMap',
},
],
);
first.forEach((layer, index) => {
@@ -84,7 +103,7 @@ test('infrastructure factory preserves identity and creates independent state wi
test('dataset URLs still name the complete bundled sources', () => {
for (const [file, count] of [
['datacenters', 4352],
['dams', 704],
['dams', 706],
]) {
const lines = readFileSync(
new URL(`./local_data/${file}/${file}.geojsonl`, import.meta.url),
@@ -96,6 +115,64 @@ test('dataset URLs still name the complete bundled sources', () => {
}
});
test('Acaray and Yacyretá appear once each with OSM provenance', () => {
for (const [id, name, object, version] of OSM_API_DAMS) {
const matches = DAMS.filter((feature) => feature.id === id);
assert.equal(matches.length, 1);
const { properties } = matches[0];
assert.equal(properties.name, name);
assert.equal(properties.osm_id, id);
assert.equal(properties.source_version, version);
assert.equal(
properties.source_url,
`https://www.openstreetmap.org/${object}`,
);
assert.equal(properties.retrieved_at, '2026-10-15');
}
});
test('Acaray and Yacyretá each get a stem, a selection context and an analyst record', async (t) => {
const added = DAMS.filter((feature) =>
OSM_API_DAMS.some(([id]) => id === feature.id),
);
t.mock.method(globalThis, 'fetch', async () => ({
ok: true,
text: async () =>
added.map((feature) => JSON.stringify(feature)).join('\n'),
}));
const host = services();
const layer = createLocalGeoJsonLayer(
{
id: 'local-dams',
name: 'Dams',
osmDerived: true,
color: '#0088ff',
url: '/dams.geojsonl',
},
host,
);
const viewer = {
scene: { screenSpaceCameraController: { enableInputs: true } },
};
const fake = bindFakeGroundRenderer(viewer);
fakeInput(viewer);
t.after(() => layer.destroy(viewer));
await layer.enable(viewer);
const names = OSM_API_DAMS.map(([, name]) => name).sort();
assert.equal(fake.set('stems').items.size, 2, 'both dams get a stem');
assert.deepEqual(
[...host.records.values()].map((record) => record.label).sort(),
names,
);
assert.deepEqual(
layer
.getAnalystRecords()
.map((record) => record.name)
.sort(),
names,
);
});
test('two viewers use their supplied contexts and dispose independently', async (t) => {
t.mock.method(globalThis, 'fetch', async () => ({
ok: true,
+43
View File
@@ -3231,3 +3231,46 @@ test('an application with every layer registered keeps every requested layer', a
]);
coordinator.destroy();
});
test('start layers turn on when nothing names any, and are never written as the user choice', async () => {
const storage = memoryStorage();
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
storage,
});
const results = await coordinator.start({
allowLocalState: false,
startLayerIds: ['earthquakes', 'traffic', 'not-a-layer'],
});
assert.equal(coordinator.source, 'start');
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [
'earthquakes',
'traffic',
]);
assert.equal(manager.isEnabled('earthquakes'), true);
assert.equal(manager.isEnabled('traffic'), true);
assert.equal(
results.every((result) => result.persistenceWrite === false),
true,
);
assert.deepEqual(storage.writes, []);
coordinator.destroy();
});
test('a shared layer payload wins over start layers', async () => {
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
storage: memoryStorage(),
});
const shared = createDefaultLayerState();
shared.enabledLayerIds = ['radio'];
await coordinator.start({
shareLayerState: shared,
allowLocalState: false,
startLayerIds: ['earthquakes'],
});
assert.equal(coordinator.source, 'share');
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['radio']);
assert.equal(manager.isEnabled('earthquakes'), false);
coordinator.destroy();
});
+8 -1
View File
@@ -103,6 +103,7 @@ export class LayerStateCoordinator {
shareLayerState = null,
allowLocalState = true,
shareCreatedAtMs = null,
startLayerIds = [],
} = {}) {
if (this._destroyed)
throw new Error('Layer-state coordinator is destroyed');
@@ -125,7 +126,13 @@ export class LayerStateCoordinator {
selected = this._normalize(stored);
this._source = 'local';
}
} else {
}
if (!selected && startLayerIds.length) {
// The layers the application starts with when nothing names any:
// restored passively, so they are never written as the user's choice.
selected = this._normalize({ enabledLayerIds: startLayerIds });
this._source = 'start';
} else if (!selected && !allowLocalState) {
// A valid historical camera/style share with no v2 layer payload keeps
// the exact legacy default-layer behavior. It must not inherit an
// unrelated recipient's saved local layer preferences.
+83
View File
@@ -0,0 +1,83 @@
import { msg } from '../i18n/marker.js';
/**
* Live streams the app can show for a selected object: a fixed list, each
* entry a broadcast on a platform's own player (YouTube today), attached to
* the subjects it shows by key. Any layer can name its selected subject's
* keys (`getLiveSubjectKeys`), and the LIVE section in Context offers the
* streams that match; the satellites layer names the ISS as `station:iss`
* whichever of the station's catalog entries is selected.
*
* These are broadcasts in the platform's embedded player, not camera feeds:
* the CCTV layer is for those. A stream's id changes when its broadcaster
* restarts it, so each entry is one line to update.
*/
/** Where YouTube's embedded player is served from: the privacy-enhanced host. */
export const YOUTUBE_EMBED_HOST = 'https://www.youtube-nocookie.com';
/** @typedef {{id: string, platform: 'youtube', videoId: string, title: string,
* owner: string, ownerUrl: string, subjects: readonly string[],
* note: string}} LiveStream */
/** @type {readonly LiveStream[]} */
export const LIVE_STREAMS = Object.freeze([
Object.freeze({
id: 'iss-exterior',
platform: 'youtube',
videoId: 'ROboUHfPUrU',
title: msg('Exterior cameras'),
owner: 'NASA',
ownerUrl: 'https://www.youtube.com/@NASA',
subjects: Object.freeze(['station:iss']),
note: msg('NASA video, via YouTube'),
}),
Object.freeze({
id: 'iss-crew',
platform: 'youtube',
videoId: 'M3HKLzjvKPc',
title: msg('Live video and space-to-ground audio'),
owner: 'NASA',
ownerUrl: 'https://www.youtube.com/@NASA',
subjects: Object.freeze(['station:iss']),
note: msg('NASA video, via YouTube'),
}),
]);
/**
* The streams attached to any of `subjectKeys`, in list order.
* @param {Iterable<string>|null|undefined} subjectKeys
* @param {readonly LiveStream[]} [streams]
* @returns {LiveStream[]}
*/
export function liveStreamsFor(subjectKeys, streams = LIVE_STREAMS) {
const keys = new Set(subjectKeys ?? []);
if (!keys.size) return [];
return streams.filter((stream) =>
stream.subjects.some((subject) => keys.has(subject)),
);
}
/** The video's own page, for the "Open on YouTube" link. */
export function youtubeWatchUrl(videoId) {
return `https://www.youtube.com/watch?v=${encodeURIComponent(videoId)}`;
}
/**
* The parameters the live player is created with: starts on creation (the
* player is built only when the viewer presses Play), muted so the browser
* lets it start once the player API has loaded, inline on phones, no related
* videos, and the page's origin so the player API may be spoken to.
* @param {string} origin The page's origin.
* @returns {Record<string, string|number>}
*/
export function youtubeLivePlayerVars(origin) {
return {
autoplay: 1,
mute: 1,
playsinline: 1,
rel: 0,
enablejsapi: 1,
...(origin ? { origin } : {}),
};
}
+80
View File
@@ -0,0 +1,80 @@
// src/data/liveStreams.test.mjs — the fixed list of live streams and how a
// selected object's keys pick from it.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
LIVE_STREAMS,
YOUTUBE_EMBED_HOST,
liveStreamsFor,
youtubeLivePlayerVars,
youtubeWatchUrl,
} from './liveStreams.js';
test('every listed stream is a complete YouTube entry with a distinct id', () => {
assert.ok(LIVE_STREAMS.length >= 2, 'the ISS has two streams');
const ids = new Set(LIVE_STREAMS.map((stream) => stream.id));
assert.equal(ids.size, LIVE_STREAMS.length);
for (const stream of LIVE_STREAMS) {
assert.equal(stream.platform, 'youtube');
assert.match(stream.videoId, /^[\w-]{11}$/, `${stream.id} video id`);
assert.ok(stream.title.length > 0);
assert.ok(stream.owner.length > 0);
assert.match(stream.ownerUrl, /^https:\/\/www\.youtube\.com\//);
assert.ok(stream.subjects.length > 0, `${stream.id} names a subject`);
assert.ok(Object.isFrozen(stream), 'entries cannot be edited at run time');
}
});
test('the ISS streams attach to the station key, in list order', () => {
const found = liveStreamsFor(['station:iss']);
assert.deepEqual(
found.map((stream) => stream.id),
['iss-exterior', 'iss-crew'],
);
});
test('a key no stream names, or no keys at all, finds nothing', () => {
assert.deepEqual(liveStreamsFor(['satellites:25544']), []);
assert.deepEqual(liveStreamsFor([]), []);
assert.deepEqual(liveStreamsFor(null), []);
assert.deepEqual(liveStreamsFor(undefined), []);
});
test('a subject known by several keys gets the union, each stream once', () => {
const streams = [
{ id: 'a', subjects: ['x'] },
{ id: 'b', subjects: ['y', 'x'] },
{ id: 'c', subjects: ['z'] },
];
assert.deepEqual(
liveStreamsFor(new Set(['x', 'y']), streams).map((s) => s.id),
['a', 'b'],
);
});
test('the watch link is the video page on YouTube proper', () => {
assert.equal(
youtubeWatchUrl('ROboUHfPUrU'),
'https://www.youtube.com/watch?v=ROboUHfPUrU',
);
assert.equal(
youtubeWatchUrl('a b&c'),
'https://www.youtube.com/watch?v=a%20b%26c',
);
});
test('the player is created on the privacy-enhanced host, muted, with the API on', () => {
assert.equal(YOUTUBE_EMBED_HOST, 'https://www.youtube-nocookie.com');
const vars = youtubeLivePlayerVars('http://localhost:5190');
assert.equal(vars.autoplay, 1);
assert.equal(vars.mute, 1);
assert.equal(vars.playsinline, 1);
assert.equal(vars.rel, 0);
assert.equal(vars.enablejsapi, 1);
assert.equal(vars.origin, 'http://localhost:5190');
assert.equal(
'origin' in youtubeLivePlayerVars(undefined),
false,
'no origin is passed when the page has none',
);
});
+14 -1
View File
@@ -4,7 +4,7 @@ Extracted from local decoded OpenInfraMap/PostGIS layers.
Filters: `waterway=dam`, `man_made=dam`, or `building=dam`.
Feature count: 704
Feature count: 706
Runtime output: `dams.geojsonl`
@@ -15,3 +15,16 @@ this derived database.
The public-release snapshot removes contact-oriented fields and note values
that contain email or phone identifiers. The runtime layer does not display or
depend on those fields.
## OSM API additions
Two dams come from the public OpenStreetMap API rather than the extract:
- Acaray: [way 262532166](https://www.openstreetmap.org/way/262532166), its closed outline of nine nodes.
- Represa Yacyretá-Apipé: [relation 5671745](https://www.openstreetmap.org/relation/5671745), its eight outer ways joined into one closed outline.
Both are under the same ODbL 1.0; the relation keeps the extract's negative ID (-5671745).
Keep both as polygons: the Dams layer skips LineStrings.
The layer puts a polygon's marker at the centre of its bounding sphere. The Yacyretá outline is L-shaped, so its
marker sits about 1.6 km from the outline, over the reservoir.
+2
View File
@@ -702,3 +702,5 @@
{"id":1415605139,"type":"Feature","geometry":{"type":"LineString","coordinates":[[169.362055788,-45.423612051],[169.360158461,-45.423276272],[169.358642426,-45.4229907],[169.357633077,-45.422794061],[169.356944755,-45.42275366],[169.356044036,-45.422764473]]},"properties":{"id":2377429,"line":"","tags":{"power":"minor_line","voltage":"11000","operator":"Aurora Energy","waterway":"dam","operator:wikidata":"Q4822522"},"type":"minor_line","osm_id":1415605139,"tunnel":false,"disused":"","voltage":"11000","circuits":null,"location":"","frequency":"","construction":"","source_layer":"osm_power_line"}}
{"id":405007988,"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[51.592068922,43.199413946],[51.59684602,43.199885177],[51.59724064,43.197759191],[51.593578084,43.197397847],[51.59272137,43.197675623],[51.592397577,43.197643772],[51.592068922,43.199413946]]]},"properties":{"id":33090,"name":"","tags":{"man_made":"wastewater_plant","waterway":"dam"},"type":"wastewater_plant","osm_id":405007988,"source_layer":"osm_wastewater_plant"}}
{"id":-19953989,"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[14.292237283,46.169084857],[14.292230326,46.169090389],[14.292224878,46.169096341],[14.292219346,46.169103549],[14.292216999,46.169113188],[14.292215322,46.169122744],[14.29221658,46.169131796],[14.292221273,46.169138334],[14.292231918,46.169148225],[14.29223963,46.169150823]],[[14.292171736,46.168911268],[14.292167462,46.168929289],[14.29216654,46.168975893],[14.292183555,46.169023083],[14.292186321,46.169030124],[14.292204593,46.169025933],[14.292237283,46.169084857]],[[14.293466824,46.169211843],[14.293464394,46.169201869],[14.293090644,46.16923657],[14.293067678,46.169224248],[14.293022583,46.169223662],[14.292636178,46.169247718],[14.292563842,46.169209496],[14.292558394,46.169207988],[14.292478766,46.169186446],[14.292457643,46.169185021],[14.292426882,46.169183429],[14.29241347,46.169186446],[14.292388492,46.169203545],[14.292448842,46.169220477],[14.292470384,46.169226428],[14.292521681,46.169242772],[14.292532661,46.169225673],[14.292546659,46.169229529],[14.29256468,46.169234558],[14.292535679,46.169293483],[14.292533499,46.169297925],[14.292576582,46.169300859],[14.292619162,46.169286191],[14.293023422,46.169262554],[14.293072791,46.169259536],[14.293092321,46.169248388],[14.293466824,46.169211843]],[[14.292535679,46.169293483],[14.29249905,46.169285185],[14.292510198,46.169267248],[14.292313977,46.169211927],[14.292318755,46.169203042],[14.29232546,46.169190721],[14.292333256,46.169176472],[14.292290089,46.169164653],[14.292276175,46.169192062],[14.292257986,46.169227769],[14.29231163,46.169241767],[14.292303919,46.169254842],[14.292294196,46.169271439],[14.292207024,46.169244868],[14.292170647,46.169314522],[14.29248589,46.169394736],[14.292518496,46.169328436],[14.292526123,46.169312845],[14.292533499,46.169297925],[14.292535679,46.169293483]],[[14.292426882,46.169183429],[14.292448172,46.169103549],[14.292476838,46.169107153],[14.292457643,46.169185021],[14.292426882,46.169183429]],[[14.292237283,46.169084857],[14.292246922,46.169084941],[14.292247257,46.169081086],[14.292319845,46.169084857],[14.292448172,46.169103549],[14.292476838,46.169107153],[14.292575074,46.169109333],[14.292575493,46.169095838],[14.292480777,46.169093156],[14.292326383,46.169069099],[14.292247341,46.169065747],[14.292242228,46.169055269],[14.292266117,46.169050324],[14.292263099,46.169041858],[14.292231835,46.169048899],[14.292217418,46.169022161],[14.292267374,46.16901336],[14.292264943,46.169006235],[14.292183555,46.169023083],[14.292186321,46.169030124],[14.292204593,46.169025933],[14.292237283,46.169084857]]]},"properties":{"name":"HE Podlubnik - Centrala","tags":{"name":"HE Podlubnik - Centrala","type":"site","power":"plant","alt_name":"HE Škofja Loka","operator":"Elektro Gorenjska","waterway":"dam","start_date":"1969","plant:method":"run-of-the-river","plant:source":"hydro","plant:output:electricity":"330KW"},"osm_id":-19953989,"output":"330KW","source":"hydro","construction":"","source_layer":"power_plant_relation_by_geom_type"}}
{"type":"Feature","id":-5671745,"geometry":{"type":"Polygon","coordinates":[[[-56.7356385,-27.4830326],[-56.7356372,-27.4836817],[-56.7356918,-27.4837745],[-56.7356509,-27.4838875],[-56.7355326,-27.4837665],[-56.7354735,-27.4836131],[-56.7353507,-27.4835526],[-56.7353552,-27.4830522],[-56.7354053,-27.483032],[-56.7354041,-27.4829378],[-56.7350345,-27.4826704],[-56.7321442,-27.4826598],[-56.7319588,-27.4828659],[-56.7018972,-27.4827418],[-56.7018797,-27.4821358],[-56.706089,-27.4821869],[-56.7060921,-27.4821089],[-56.7063455,-27.482095],[-56.7063734,-27.4821649],[-56.7090948,-27.482163],[-56.7091818,-27.4821095],[-56.7093995,-27.4820799],[-56.7094201,-27.4821854],[-56.7106196,-27.4821876],[-56.7109955,-27.4820628],[-56.7121754,-27.4820408],[-56.7121751,-27.4817168],[-56.712209,-27.4817165],[-56.7122144,-27.4803221],[-56.7121755,-27.4803209],[-56.7121781,-27.4793322],[-56.7122425,-27.4793286],[-56.7122439,-27.4791204],[-56.7121688,-27.479118],[-56.7121795,-27.4788039],[-56.7122371,-27.4788007],[-56.7122492,-27.4788015],[-56.7122948,-27.4790038],[-56.7123002,-27.4793441],[-56.7123005,-27.4796668],[-56.7124411,-27.4796679],[-56.7125759,-27.4796689],[-56.7125765,-27.47935],[-56.7125805,-27.4792477],[-56.7125939,-27.4790371],[-56.7126422,-27.4788016],[-56.7126649,-27.4788009],[-56.7127186,-27.4788051],[-56.7127213,-27.4791216],[-56.7126462,-27.4791276],[-56.7126516,-27.4793274],[-56.7127079,-27.4793263],[-56.7127072,-27.4803126],[-56.7126744,-27.4803132],[-56.712673,-27.4817118],[-56.7127239,-27.481713],[-56.7127247,-27.4820404],[-56.7132439,-27.4820594],[-56.7135349,-27.4821853],[-56.716431,-27.4821918],[-56.7166924,-27.4821402],[-56.7169096,-27.482192],[-56.7354167,-27.4822992],[-56.7432767,-27.4822775],[-56.7432829,-27.4821624],[-56.7433092,-27.4820925],[-56.7433441,-27.4820092],[-56.743387,-27.4819117],[-56.7433977,-27.481826],[-56.7434058,-27.481362],[-56.743385,-27.4806888],[-56.7435047,-27.4806879],[-56.7435053,-27.480804],[-56.7517581,-27.4808023],[-56.7519858,-27.4807842],[-56.7522074,-27.4807224],[-56.7529074,-27.4805122],[-56.7530675,-27.4804512],[-56.753188,-27.4804018],[-56.7536873,-27.4801667],[-56.7539035,-27.480035],[-56.7540186,-27.4799455],[-56.7546428,-27.4793125],[-56.7548624,-27.4789803],[-56.755134,-27.4784449],[-56.7553243,-27.4776504],[-56.7553385,-27.4775558],[-56.7553453,-27.4773839],[-56.7553663,-27.453364],[-56.756278,-27.4533505],[-56.7566902,-27.4545407],[-56.7565699,-27.4671653],[-56.7566153,-27.4769172],[-56.7565098,-27.4782975],[-56.7561882,-27.4791614],[-56.7557343,-27.4797995],[-56.7548315,-27.4808659],[-56.7541622,-27.4813087],[-56.753515,-27.4815729],[-56.7529038,-27.4817915],[-56.7522708,-27.4819086],[-56.7486914,-27.4820093],[-56.7480953,-27.4820155],[-56.7478466,-27.4820264],[-56.747675,-27.4820455],[-56.7475127,-27.4820919],[-56.7469953,-27.4823096],[-56.7450435,-27.4829093],[-56.7443696,-27.4830283],[-56.7436163,-27.4830891],[-56.7434021,-27.483068],[-56.7396907,-27.4830592],[-56.7396861,-27.4833826],[-56.7394399,-27.4833826],[-56.739439,-27.4830604],[-56.7356385,-27.4830326]]]},"properties":{"name":"Represa Yacyretá-Apipé","tags":{"name":"Represa Yacyretá-Apipé","type":"multipolygon","waterway":"dam"},"osm_id":-5671745,"source_layer":"osm_relation","source_url":"https://www.openstreetmap.org/relation/5671745","source_version":2,"retrieved_at":"2026-10-15"}}
{"type":"Feature","id":262532166,"geometry":{"type":"Polygon","coordinates":[[[-54.6285064,-25.4587626],[-54.628456,-25.4586556],[-54.6286513,-25.458535],[-54.6287352,-25.4587382],[-54.6292971,-25.459876],[-54.6290649,-25.4599721],[-54.6285037,-25.4588762],[-54.6285459,-25.4588065],[-54.6285064,-25.4587626]]]},"properties":{"name":"Acaray","tags":{"name":"Acaray","waterway":"dam","wikidata":"Q3433454"},"osm_id":262532166,"source_layer":"osm_way","source_url":"https://www.openstreetmap.org/way/262532166","source_version":7,"retrieved_at":"2026-10-15"}}
+102
View File
@@ -0,0 +1,102 @@
import { fromDegreesInto } from '../geo/ellipsoid.js';
/**
* Finding a selected vessel or aircraft again once it has left the screen or
* its layer's feed: where its own track has it at a time, and whether a point
* is on screen at all.
*/
/**
* The newest point of a track at or before `atMs` (any time when `atMs` is
* not given), from a live source's `getTrack` records
* (`{observedAtMs, latitude, longitude, baroAltitudeM?}`).
* @param {Array<object>} points
* @param {number} [atMs]
* @returns {{lat: number, lon: number, altitudeM: ?number, observedAtMs: number}|null}
*/
export function readingAt(points, atMs) {
let best = null;
for (const point of points ?? []) {
const lat = Number(point?.latitude);
const lon = Number(point?.longitude);
const observedAtMs = point?.observedAtMs;
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
if (!Number.isFinite(observedAtMs)) continue;
if (Number.isFinite(atMs) && observedAtMs > atMs) continue;
if (best && best.observedAtMs >= observedAtMs) continue;
const altitude = Number(point.baroAltitudeM ?? point.altitudeM);
best = {
lat,
lon,
altitudeM: Number.isFinite(altitude) ? altitude : null,
observedAtMs,
};
}
return best;
}
/**
* Where a source's track has a vessel or aircraft at `atMs` (now, when not
* given): `{status: 'found', lat, lon, altitudeM, observedAtMs, atMs}`, or
* `{status: 'none'}` when the track has no point at or before the time, the
* source keeps no tracks or the lookup fails.
* @param {{getTrack?: Function}|null} source
* @param {string} reference The track reference the layer's records carry.
* @param {{atMs?: number, signal?: AbortSignal}} [options]
*/
export async function locateOnTrack(source, reference, { atMs, signal } = {}) {
if (typeof source?.getTrack !== 'function' || !reference)
return { status: 'none' };
try {
const track = await source.getTrack(
reference,
Number.isFinite(atMs) ? { signal, atMs } : { signal },
);
const reading = readingAt(track?.records, atMs);
// The time it was looked up for, so its reading's age can be told.
const at = Number.isFinite(atMs) ? atMs : Date.now();
return reading
? { status: 'found', ...reading, atMs: at }
: { status: 'none' };
} catch (error) {
if (signal?.aborted) throw error;
return { status: 'none' };
}
}
/** Mean Earth radius (m), for the horizon test. */
const EARTH_RADIUS_M = 6_371_000;
/**
* Whether a point is in the camera's view: in front of it, inside its field
* of view and on the near side of the globe.
* @param {{position: {x, y, z}, direction: {x, y, z}, up: {x, y, z},
* right: {x, y, z}, fovy: number, aspectRatio: number}} pose
* @param {number} lat
* @param {number} lon
* @param {number} [heightM]
* @returns {boolean}
*/
export function onScreen(pose, lat, lon, heightM = 0) {
if (!pose?.position || !Number.isFinite(lat) || !Number.isFinite(lon))
return false;
const p = fromDegreesInto(lon, lat, Math.max(0, heightM || 0), {
x: 0,
y: 0,
z: 0,
});
const c = pose.position;
const v = { x: p.x - c.x, y: p.y - c.y, z: p.z - c.z };
const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const ahead = dot(v, pose.direction);
if (!(ahead > 0)) return false;
const tanY = Math.tan(pose.fovy / 2);
const tanX = tanY * (pose.aspectRatio || 1);
if (Math.abs(dot(v, pose.right) / ahead) > tanX) return false;
if (Math.abs(dot(v, pose.up) / ahead) > tanY) return false;
// Behind the globe: the camera is below the point's horizon plane. Judged
// on a sphere through the point, which is close enough for a button.
const length = Math.hypot(p.x, p.y, p.z) || EARTH_RADIUS_M;
const normal = { x: p.x / length, y: p.y / length, z: p.z / length };
return dot({ x: c.x - p.x, y: c.y - p.y, z: c.z - p.z }, normal) > 0;
}
+114
View File
@@ -0,0 +1,114 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { locateOnTrack, onScreen, readingAt } from './locate.js';
import { fromDegreesInto } from '../geo/ellipsoid.js';
const point = (observedAtMs, latitude, longitude, extra = {}) => ({
observedAtMs,
latitude,
longitude,
...extra,
});
test('the reading at a time is the newest point at or before it', () => {
const track = [
point(3_000, 3, 30),
point(1_000, 1, 10, { baroAltitudeM: 900 }),
point(2_000, 2, 20),
point(Number.NaN, 9, 90),
point(4_000, Number.NaN, 40),
];
assert.deepEqual(readingAt(track, 2_500), {
lat: 2,
lon: 20,
altitudeM: null,
observedAtMs: 2_000,
});
assert.equal(readingAt(track, 1_000).altitudeM, 900, 'at its own time');
assert.equal(readingAt(track).observedAtMs, 3_000, 'no time: the newest');
assert.equal(readingAt(track, 500), null, 'before its first point');
assert.equal(readingAt([], 500), null);
});
test('a track lookup asks for the time and reads the point at it', async () => {
const asked = [];
const source = {
async getTrack(reference, options) {
asked.push([reference, options.atMs]);
return { records: [point(1_000, 1, 10), point(5_000, 5, 50)] };
},
};
assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 2_000 }), {
status: 'found',
lat: 1,
lon: 10,
altitudeM: null,
observedAtMs: 1_000,
atMs: 2_000,
});
assert.deepEqual(asked, [['vessel:a', 2_000]]);
assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 500 }), {
status: 'none',
});
const live = await locateOnTrack(source, 'vessel:a');
assert.equal(live.observedAtMs, 5_000, 'live: its newest point');
assert.equal(asked.at(-1)[1], undefined, 'live asks for no time');
});
test('a source without tracks, or one that fails, finds nothing', async () => {
assert.deepEqual(await locateOnTrack({}, 'a'), { status: 'none' });
assert.deepEqual(await locateOnTrack(null, 'a'), { status: 'none' });
const failing = {
getTrack: async () => {
throw new Error('down');
},
};
assert.deepEqual(await locateOnTrack(failing, 'a'), { status: 'none' });
assert.deepEqual(
await locateOnTrack({ getTrack: async () => ({ records: [] }) }, ''),
{ status: 'none' },
'no reference',
);
});
/** A camera 1000 km above a point, looking straight down. */
function poseAbove(lat, lon) {
const at = fromDegreesInto(lon, lat, 0, { x: 0, y: 0, z: 0 });
const length = Math.hypot(at.x, at.y, at.z);
const up = { x: at.x / length, y: at.y / length, z: at.z / length };
const position = {
x: at.x + up.x * 1e6,
y: at.y + up.y * 1e6,
z: at.z + up.z * 1e6,
};
const direction = { x: -up.x, y: -up.y, z: -up.z };
// North-ish screen up, east right: any pair at right angles will do.
const east = {
x: -Math.sin((lon * Math.PI) / 180),
y: Math.cos((lon * Math.PI) / 180),
z: 0,
};
const north = {
x: up.y * east.z - up.z * east.y,
y: up.z * east.x - up.x * east.z,
z: up.x * east.y - up.y * east.x,
};
return {
position,
direction,
up: north,
right: east,
fovy: Math.PI / 3,
aspectRatio: 1.5,
};
}
test('a point is on screen in view, and not out of view or behind the globe', () => {
const pose = poseAbove(10, 20);
assert.equal(onScreen(pose, 10, 20), true, 'under the camera');
assert.equal(onScreen(pose, 11, 21), true, 'near it');
assert.equal(onScreen(pose, 30, 20), false, 'outside the view');
assert.equal(onScreen(pose, -10, -160), false, 'the far side of the globe');
assert.equal(onScreen(pose, Number.NaN, 20), false, 'no position');
assert.equal(onScreen(null, 10, 20), false, 'no camera');
});
+36 -4
View File
@@ -154,6 +154,24 @@ export function pickContact(query, position, options = {}) {
let _overlayHitTest = null;
/** @type {WeakMap<object, {sourceId: string, entryId: string}|null>} */
const clickCards = new WeakMap();
const _clickClaims = new Map();
/**
* Register a target drawn outside the world overlay's entries, such as a CCTV
* count. A claim runs once per click where no card or label is painted above
* it and must not call `clickCard`.
* @param {string} layerId
* @param {(click: object) => ({sourceId: string, entryId: string}|null)} claim
*/
export function registerClickClaim(layerId, claim) {
if (!layerId || typeof claim !== 'function') return;
_clickClaims.set(layerId, claim);
}
/** Remove a layer's claim when it is disabled or destroyed. */
export function unregisterClickClaim(layerId) {
_clickClaims.delete(layerId);
}
/**
* Sets (or with null, clears) the hit test that names the card or label
@@ -166,8 +184,8 @@ export function setClickCardHitTest(hitTest) {
}
/**
* The topmost interactive card or label painted at a click, read once per
* click so every handler of it sees the same one whatever ran first.
* The topmost interactive card or label painted at a click, or a target a
* layer claims (`registerClickClaim`). All handlers share one result per click.
* @param {{screenPosition?: {x: number, y: number}}|null|undefined} click
* @returns {{sourceId: string, entryId: string}|null}
*/
@@ -179,14 +197,28 @@ export function clickCard(click) {
try {
card = _overlayHitTest?.(at?.x, at?.y) ?? null;
} catch {
// a broken hit test must never break click handling
clickCards.set(click, null);
return null;
}
if (!card) {
// A claim that reads this click again cannot re-enter the claims loop.
clickCards.set(click, null);
for (const claim of _clickClaims.values()) {
try {
card = claim(click) ?? null;
} catch {
card = null;
}
if (card) break;
}
}
clickCards.set(click, card);
return card;
}
/**
* True when another layer's card or label is painted on top at a click. The
* True when another layer has the top card, label, or claimed target
* (`registerClickClaim`) at a click. The
* card on top takes the click: a scene item under it does not act, and is
* not empty space either, so the layer leaves its selection alone.
* @param {object} click The shared dispatcher event.
+41
View File
@@ -20,6 +20,8 @@ import {
clickCard,
isUnderOtherCard,
setClickCardHitTest,
registerClickClaim,
unregisterClickClaim,
} from './pickRegistry.js';
// ---------------------------------------------------------------------------
@@ -237,3 +239,42 @@ test("the card on top is read once per click, and only another layer's card coun
setClickCardHitTest(null);
}
});
test('a click claim is the card on top only where no card or label is painted', () => {
const event = (x) => ({ screenPosition: { x, y: 5 } });
let calls = 0;
registerClickClaim('counts', (click) => {
calls++;
return click.screenPosition.x === 4
? { sourceId: 'counts', entryId: 'k' }
: null;
});
try {
registerClickClaim('counts', null);
const click = event(4);
assert.equal(isUnderOtherCard(click), true);
assert.equal(isUnderOtherCard(click, ['counts']), false);
assert.equal(calls, 1);
assert.equal(clickCard(event(9)), null);
const quake = { sourceId: 'quake-card', entryId: 'q1' };
setClickCardHitTest(() => quake);
assert.deepEqual(clickCard(event(4)), quake);
assert.equal(calls, 2);
setClickCardHitTest(() => {
throw new Error('broken overlay hit test');
});
assert.equal(clickCard(event(4)), null);
assert.equal(calls, 2);
setClickCardHitTest(null);
unregisterClickClaim('counts');
assert.equal(clickCard(event(4)), null);
registerClickClaim('counts', () => {
throw new Error('broken claim');
});
assert.equal(clickCard(event(4)), null);
} finally {
unregisterClickClaim('counts');
setClickCardHitTest(null);
}
});
+68
View File
@@ -0,0 +1,68 @@
/**
* YouTube's IFrame Player API, loaded once per document: the only in-page
* way to learn a player's state (playing, ended) and errors (video gone,
* embedding refused), which the live-stream player needs to tell an offline
* stream from one still loading. The page's script-src allows
* `https://www.youtube.com`.
*/
const youtubeApis = new WeakMap();
/**
* Load the API, or return the one already there.
* @param {Document} documentRef
* @param {object} globalRef The window: `YT`, `onYouTubeIframeAPIReady`,
* timers.
* @returns {Promise<object>} The `YT` namespace.
*/
export function loadYouTubeApi(documentRef, globalRef) {
if (typeof globalRef.YT?.Player === 'function')
return Promise.resolve(globalRef.YT);
if (youtubeApis.has(documentRef)) return youtubeApis.get(documentRef);
const pending = new Promise((resolve, reject) => {
const previous = globalRef.onYouTubeIframeAPIReady;
let timer;
let settled = false;
const script = documentRef.createElement('script');
const finish = (error) => {
if (settled) return;
settled = true;
globalRef.clearTimeout(timer);
if (globalRef.onYouTubeIframeAPIReady === ready)
globalRef.onYouTubeIframeAPIReady = previous;
if (error) {
script.remove();
reject(error);
} else resolve(globalRef.YT);
};
const ready = () => {
try {
previous?.();
} finally {
finish(
typeof globalRef.YT?.Player === 'function'
? null
: new Error('YouTube API unavailable'),
);
}
};
globalRef.onYouTubeIframeAPIReady = ready;
script.src = 'https://www.youtube.com/iframe_api';
script.async = true;
script.addEventListener(
'error',
() => finish(new Error('YouTube API unavailable')),
{ once: true },
);
timer = globalRef.setTimeout(
() => finish(new Error('YouTube API timed out')),
5000,
);
documentRef.head.append(script);
}).catch((error) => {
youtubeApis.delete(documentRef);
throw error;
});
youtubeApis.set(documentRef, pending);
return pending;
}
+84
View File
@@ -0,0 +1,84 @@
// src/data/youtubeApi.test.mjs — YouTube's IFrame API loader, with the page
// faked: one load per document, and a load that fails is not kept, so the
// LIVE section's Try again loads the API afresh.
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadYouTubeApi } from './youtubeApi.js';
/** A document whose head records the scripts put in it. */
function fakePage() {
const scripts = [];
const timers = [];
const documentRef = {
createElement(tag) {
const listeners = {};
return {
tag,
removed: false,
addEventListener(name, listener) {
listeners[name] = listener;
},
fire(name) {
listeners[name]?.();
},
remove() {
this.removed = true;
},
};
},
head: {
append(node) {
scripts.push(node);
},
},
};
const globalRef = {
setTimeout(callback, delay) {
timers.push({ callback, delay, cleared: false });
return timers.length;
},
clearTimeout(id) {
if (timers[id - 1]) timers[id - 1].cleared = true;
},
};
return { documentRef, globalRef, scripts, timers };
}
class Player {}
test('the API loads once per document, and a loaded one is reused', async () => {
const { documentRef, globalRef, scripts } = fakePage();
const first = loadYouTubeApi(documentRef, globalRef);
assert.equal(loadYouTubeApi(documentRef, globalRef), first);
assert.equal(scripts.length, 1);
assert.equal(scripts[0].src, 'https://www.youtube.com/iframe_api');
globalRef.YT = { Player };
globalRef.onYouTubeIframeAPIReady();
assert.equal(await first, globalRef.YT);
assert.equal(await loadYouTubeApi(documentRef, globalRef), globalRef.YT);
assert.equal(scripts.length, 1);
});
test('a script that fails to load is removed, and the next call loads afresh', async () => {
const { documentRef, globalRef, scripts } = fakePage();
const failed = loadYouTubeApi(documentRef, globalRef);
scripts[0].fire('error');
await assert.rejects(failed, /YouTube API unavailable/);
assert.equal(scripts[0].removed, true);
const again = loadYouTubeApi(documentRef, globalRef);
assert.notEqual(again, failed);
assert.equal(scripts.length, 2);
globalRef.YT = { Player };
globalRef.onYouTubeIframeAPIReady();
assert.equal(await again, globalRef.YT);
});
test('a load slower than 5 s fails, and the next call loads afresh', async () => {
const { documentRef, globalRef, scripts, timers } = fakePage();
const slow = loadYouTubeApi(documentRef, globalRef);
assert.equal(timers[0].delay, 5000);
timers[0].callback();
await assert.rejects(slow, /YouTube API timed out/);
loadYouTubeApi(documentRef, globalRef);
assert.equal(scripts.length, 2);
});
+124
View File
@@ -0,0 +1,124 @@
import { loadYouTubeApi } from './youtubeApi.js';
import { YOUTUBE_EMBED_HOST, youtubeLivePlayerVars } from './liveStreams.js';
/**
* One live stream in YouTube's embedded player, with its state read back
* through the player API: `loading` until the video plays, `playing`, and
* `offline` once the player says the video has ended, cannot be found or
* never starts. The player cannot say "this broadcast is off air" in so
* many words: a live stream that is off air is reported as a video that
* cannot play, or that never reaches playing, so both read as offline here.
* An API that does not load (blocked, or slower than its 5 s) is offline too,
* reason `api`: Try again loads it afresh. Embedding refused by the video's
* owner is `unavailable`, which no retry will change.
*/
/** A stream that has not started playing this long after its player was ready is offline. */
export const LIVE_START_TIMEOUT_MS = 25_000;
/** YouTube's player states. */
const ENDED = 0;
const PLAYING = 1;
/** Error codes: embedding not allowed on this page. */
const EMBED_REFUSED = new Set([101, 150]);
/**
* @param {{host: HTMLElement, videoId: string, documentRef?: Document,
* globalRef?: object, loadApi?: typeof loadYouTubeApi,
* onChange: (state: {state: 'loading'|'playing'|'offline'|'unavailable',
* reason: string|null}) => void}} options `host` is emptied and given the
* player's iframe.
* @returns {{destroy: () => void}}
*/
export function createYouTubeLivePlayer({
host,
videoId,
documentRef = globalThis.document,
globalRef = globalThis,
loadApi = loadYouTubeApi,
onChange,
}) {
let destroyed = false;
let player = null;
let timer = null;
let current = null;
const set = (state, reason = null) => {
if (destroyed || current === state) return;
current = state;
onChange({ state, reason });
};
const clearTimer = () => {
if (timer !== null) globalRef.clearTimeout(timer);
timer = null;
};
const armTimer = () => {
clearTimer();
timer = globalRef.setTimeout(() => {
timer = null;
if (current === 'loading') set('offline', 'timeout');
}, LIVE_START_TIMEOUT_MS);
};
set('loading');
host.replaceChildren();
const mount = documentRef.createElement('div');
host.append(mount);
loadApi(documentRef, globalRef).then(
(YT) => {
if (destroyed) return;
try {
player = new YT.Player(mount, {
host: YOUTUBE_EMBED_HOST,
videoId,
playerVars: youtubeLivePlayerVars(globalRef.location?.origin),
events: {
onReady: () => {
if (!destroyed) armTimer();
},
onStateChange: (event) => {
if (destroyed) return;
if (event?.data === PLAYING) {
clearTimer();
set('playing');
} else if (event?.data === ENDED) {
clearTimer();
set('offline', 'ended');
}
},
onError: (event) => {
if (destroyed) return;
clearTimer();
const code = Number(event?.data);
if (EMBED_REFUSED.has(code)) set('unavailable', `error-${code}`);
else set('offline', `error-${code}`);
},
},
});
// The API may never call onReady for a video it cannot load.
armTimer();
} catch {
set('offline', 'player');
}
},
() => {
if (!destroyed) set('offline', 'api');
},
);
return {
destroy() {
if (destroyed) return;
destroyed = true;
clearTimer();
try {
player?.destroy?.();
} catch {
// A player half-created has nothing to destroy.
}
player = null;
host.replaceChildren();
},
};
}
+188
View File
@@ -0,0 +1,188 @@
// src/data/youtubeLivePlayer.test.mjs — one live stream in YouTube's player,
// with the player API faked: its states and errors read back as the LIVE
// section's loading / playing / offline / unavailable.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
LIVE_START_TIMEOUT_MS,
createYouTubeLivePlayer,
} from './youtubeLivePlayer.js';
import { YOUTUBE_EMBED_HOST } from './liveStreams.js';
/** A stand-in for the panel's host element: counts what is put in it. */
function fakeHost() {
return {
children: [],
replaceChildren() {
this.children = [];
},
append(...nodes) {
this.children.push(...nodes);
},
};
}
/**
* The player as YouTube's API builds it: records its options and lets the
* test fire its events.
*/
function fakeApi() {
const players = [];
class Player {
constructor(mount, options) {
this.mount = mount;
this.options = options;
this.destroyed = 0;
players.push(this);
}
fire(name, data) {
this.options.events[name]?.({ data, target: this });
}
destroy() {
this.destroyed += 1;
}
}
return { YT: { Player }, players };
}
function fixture({ apiFails = false } = {}) {
const api = fakeApi();
const timers = [];
const globalRef = {
location: { origin: 'http://localhost:5190' },
setTimeout(callback, delay) {
const id = timers.length + 1;
timers.push({ id, callback, delay, cleared: false });
return id;
},
clearTimeout(id) {
const timer = timers.find((entry) => entry.id === id);
if (timer) timer.cleared = true;
},
};
const documentRef = { createElement: (tag) => ({ tag }) };
const states = [];
const host = fakeHost();
const player = createYouTubeLivePlayer({
host,
videoId: 'ROboUHfPUrU',
documentRef,
globalRef,
loadApi: () =>
apiFails ? Promise.reject(new Error('blocked')) : Promise.resolve(api.YT),
onChange: (state) => states.push(state),
});
// Let the API promise settle and the player be built.
const settle = () => new Promise((resolve) => setImmediate(resolve));
const pending = () => timers.filter((timer) => !timer.cleared);
return { api, timers, pending, states, host, player, settle };
}
test('the player is built on the privacy host with the live parameters, once the API loads', async () => {
const { api, states, host, settle } = fixture();
assert.deepEqual(states, [{ state: 'loading', reason: null }]);
assert.equal(host.children.length, 1, 'a mount for the iframe is placed');
await settle();
assert.equal(api.players.length, 1);
const { options } = api.players[0];
assert.equal(options.host, YOUTUBE_EMBED_HOST);
assert.equal(options.videoId, 'ROboUHfPUrU');
assert.equal(options.playerVars.enablejsapi, 1);
assert.equal(options.playerVars.mute, 1);
assert.equal(options.playerVars.origin, 'http://localhost:5190');
});
test('playing clears the start timer; the same state is not reported twice', async () => {
const { api, pending, states, settle } = fixture();
await settle();
const [player] = api.players;
player.fire('onReady');
assert.equal(pending().length, 1, 'one start timer is running');
assert.equal(pending()[0].delay, LIVE_START_TIMEOUT_MS);
player.fire('onStateChange', 1);
player.fire('onStateChange', 1);
assert.equal(pending().length, 0, 'the timer went when playback began');
assert.deepEqual(states.at(-1), { state: 'playing', reason: null });
assert.equal(states.length, 2);
});
test('a video that ends, or errors for any other reason, reads as offline', async () => {
const ended = fixture();
await ended.settle();
ended.api.players[0].fire('onStateChange', 0);
assert.deepEqual(ended.states.at(-1), { state: 'offline', reason: 'ended' });
const errored = fixture();
await errored.settle();
errored.api.players[0].fire('onError', 100);
assert.deepEqual(errored.states.at(-1), {
state: 'offline',
reason: 'error-100',
});
assert.equal(errored.pending().length, 0, 'the start timer is cleared');
});
test('embedding refused by the owner is unavailable, which no retry would change', async () => {
for (const code of [101, 150]) {
const { api, states, settle } = fixture();
await settle();
api.players[0].fire('onError', code);
assert.deepEqual(states.at(-1), {
state: 'unavailable',
reason: `error-${code}`,
});
}
});
test('a stream that never starts playing is offline when the start timer runs out', async () => {
const { api, pending, states, settle } = fixture();
await settle();
api.players[0].fire('onReady');
const [timer] = pending();
timer.callback();
assert.deepEqual(states.at(-1), { state: 'offline', reason: 'timeout' });
// Buffering states before the timer do not count as playing.
assert.equal(
states.some((entry) => entry.state === 'playing'),
false,
);
});
test('a timer that fires after playback began changes nothing', async () => {
const { api, timers, states, settle } = fixture();
await settle();
api.players[0].fire('onReady');
api.players[0].fire('onStateChange', 1);
for (const timer of timers) timer.callback();
assert.deepEqual(states.at(-1), { state: 'playing', reason: null });
});
test('an API that does not load reads as offline, which Try again can change', async () => {
const { states, settle } = fixture({ apiFails: true });
await settle();
assert.deepEqual(states.at(-1), { state: 'offline', reason: 'api' });
});
test('destroy empties the host, destroys the player and silences later events', async () => {
const { api, host, pending, player, states, settle } = fixture();
await settle();
const built = api.players[0];
built.fire('onReady');
player.destroy();
player.destroy();
assert.equal(built.destroyed, 1);
assert.equal(host.children.length, 0);
assert.equal(pending().length, 0);
const before = states.length;
built.fire('onStateChange', 1);
built.fire('onError', 150);
assert.equal(states.length, before, 'nothing is reported after destroy');
});
test('destroy before the API loads builds no player', async () => {
const { api, player, states, settle } = fixture();
player.destroy();
await settle();
assert.equal(api.players.length, 0);
assert.deepEqual(states, [{ state: 'loading', reason: null }]);
});
+29
View File
@@ -144,3 +144,32 @@ export function followOffsetFitting(sphere, at, view = {}) {
2 - 1 / Math.max(1, Math.hypot(at.x, at.y, at.z) / WGS84.radii.x);
return offsetFromHeadingPitchRange(0, (-Math.PI / 4) * factor, range);
}
/**
* The heading, pitch and roll that turn the east-north-up frame at `origin`
* onto `axes`: three unit vectors in the Earth-fixed frame that are a
* body's own x, y and z axes there (a right-handed set). The inverse of the
* renderer's placing of a model by `{heading, pitch, roll}` at a position
* (Cesium's `headingPitchRollToFixedFrame`): heading turns about down,
* pitch about the turned east axis, roll about the body's own x. Radians.
* @param {{x: number, y: number, z: number}} origin
* @param {{x: {x: number, y: number, z: number},
* y: {x: number, y: number, z: number},
* z: {x: number, y: number, z: number}}} axes
* @returns {{heading: number, pitch: number, roll: number}}
*/
export function headingPitchRollOfAxes(origin, axes) {
const enu = eastNorthUp(origin);
// M = ENUᵀ · [x y z]: the body's axes on the local east, north, up.
const m00 = dot(enu.x, axes.x);
const m10 = dot(enu.y, axes.x);
const m20 = dot(enu.z, axes.x);
const m21 = dot(enu.z, axes.y);
const m22 = dot(enu.z, axes.z);
// M = Rz(-heading) · Ry(-pitch) · Rx(roll).
return {
heading: -Math.atan2(m10, m00),
pitch: Math.asin(Math.max(-1, Math.min(1, m20))),
roll: Math.atan2(m21, m22),
};
}
+30
View File
@@ -134,6 +134,7 @@ test('a bad or keyless geocode request never reaches Google', async () => {
]) {
const response = await invokeRoute(routes.get(path), { url });
assert.equal(response.statusCode, 400);
assert.equal(response.headers['cache-control'], 'no-store');
assert.deepEqual(response.body.results, []);
assert.equal(response.body.status, 'REQUEST_DENIED');
}
@@ -144,6 +145,7 @@ test('a bad or keyless geocode request never reaches Google', async () => {
url: '/?address=Austin&lat=30&lon=-97',
});
assert.equal(rejected.statusCode, 405);
assert.equal(rejected.headers['cache-control'], 'no-store');
}
// Keyless is an empty capability, not an outage: a 200 the browser adapters
@@ -167,6 +169,33 @@ test('a bad or keyless geocode request never reaches Google', async () => {
assert.deepEqual(upstream, []);
});
test('only a Geocoding answer is kept by the browser', async () => {
// Google can report a denied key or exhausted quota with HTTP 200.
for (const [httpStatus, status, cacheControl] of [
[200, 'OK', 'private, max-age=300'],
[200, 'ZERO_RESULTS', 'private, max-age=300'],
[200, 'REQUEST_DENIED', 'no-store'],
[200, 'OVER_QUERY_LIMIT', 'no-store'],
[200, 'OVER_DAILY_LIMIT', 'no-store'],
[200, 'UNKNOWN_ERROR', 'no-store'],
[503, 'ZERO_RESULTS', 'no-store'],
]) {
const routes = installRoutes({
fetchImpl: async () =>
Response.json({ status, results: [] }, { status: httpStatus }),
});
for (const path of ['/api/google/geocode', '/api/google/reverse-geocode']) {
const label = `${path} ${httpStatus} ${status}`;
const response = await invokeRoute(routes.get(path), {
url: '/?address=Austin&lat=30&lon=-97',
});
assert.equal(response.statusCode, httpStatus, label);
assert.equal(response.body.status, status, label);
assert.equal(response.headers['cache-control'], cacheControl, label);
}
}
});
test('an upstream failure reaches the browser as fixed public text', async () => {
const routes = installRoutes({
fetchImpl: async () => {
@@ -178,6 +207,7 @@ test('an upstream failure reaches the browser as fixed public text', async () =>
url: '/?address=Austin&lat=30&lon=-97',
});
assert.equal(response.statusCode, 502);
assert.equal(response.headers['cache-control'], 'no-store');
assert.deepEqual(response.body, {
status: 'UNKNOWN_ERROR',
results: [],
+111 -1
View File
@@ -4739,5 +4739,115 @@
"Select a map item to see its details.": "اختر عنصرًا على الخريطة لرؤية تفاصيله.",
"Bilawal on {site}": "بلال على {site}",
"Bilawal's website": "موقع بلال الإلكتروني",
"BACK": "رجوع"
"BACK": "رجوع",
"Finding it…": "جارٍ البحث عنه…",
"No reading at this time": "لا توجد قراءة في هذا الوقت",
"Last reading · {age}": "آخر قراءة · {age}",
"Find it": "اعثر عليه",
"Underneath": "تحت",
"Open on YouTube": "فتح على YouTube",
"Video plays from YouTube, which sees your IP address.": "يُشغَّل الفيديو من YouTube، الذي يرى عنوان IP الخاص بك.",
"Automatic": "تلقائي",
"Manual": "يدوي",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "الألواح والمشعّات تتبع الشمس، والأطباق تتجه نحو أقمار الترحيل، والأذرع تتحرك للتوضيح فقط. محسوبة، وليست قياسات حية.",
"Overhead": "فوق المحطة",
"Ahead": "أمام",
"Behind": "خلف",
"Port side": "الجانب الأيسر",
"Starboard side": "الجانب الأيمن",
"Night (shadow)": "ليل (ظل)",
"Sun position": "موضع الشمس",
"Follow the Sun": "اتبع الشمس",
"Fast orbit (40 s)": "مدار سريع (40 ث)",
"Solar arrays": "الألواح الشمسية",
"Demonstration: the real arrays stay extended.": "للتوضيح: الألواح الحقيقية تبقى مفرودة.",
"Retract": "طيّ",
"Extend": "فرد",
"Radiators": "المشعّات",
"Demonstration: the real radiators can fold but stay extended.": "للتوضيح: المشعّات الحقيقية قابلة للطي لكنها تبقى مفرودة.",
"Dishes": "الأطباق",
"Relay satellites": "أقمار الترحيل",
"Up": "أعلى",
"Forward": "أمام",
"Sideways": "جانبًا",
"Shoulder roll": "دوران الكتف",
"Shoulder yaw": "انعراج الكتف",
"Shoulder pitch": "ميل الكتف",
"Elbow": "المرفق",
"Wrist pitch": "ميل المعصم",
"Wrist yaw": "انعراج المعصم",
"Wrist roll": "دوران المعصم",
"Canadarm2 (degrees)": "Canadarm2 (درجات)",
"Resume sway": "استئناف الحركة التلقائية",
"Zoom to the ISS": "تقريب إلى المحطة الدولية",
"Now: in sunlight": "الآن: في ضوء الشمس",
"Now: in the Earth's shadow": "الآن: في ظل الأرض",
"{label} · STATION VIEW": "{label} · منظر المحطة",
"STATION VIEW · {name}": "منظر المحطة · {name}",
"Previous station view": "منظر المحطة السابق",
"Next station view": "منظر المحطة التالي",
"OBSERVATION MODULE · ISS": "وحدة رصد · محطة الفضاء الدولية",
"European Space Agency (ESA)": "وكالة الفضاء الأوروبية (ESA)",
"7 WINDOWS": "7 نوافذ",
"LAUNCHED 8 FEB 2010 · STS-130": "أُطلقت 8 فبراير 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "ترانكويليتي · المنفذ المواجه للأرض",
"LABORATORY MODULE · ISS": "وحدة مختبر · محطة الفضاء الدولية",
"Japan Aerospace Exploration Agency (JAXA)": "وكالة استكشاف الفضاء اليابانية (JAXA)",
"2 WINDOWS": "نافذتان",
"LAUNCHED 31 MAY 2008 · STS-124": "أُطلقت 31 مايو 2008 · STS-124",
"HARMONY · PORT SIDE": "هارموني · الجانب الأيسر",
"Return to the default view": "العودة إلى العرض الافتراضي",
"ON AIR": "على الهواء",
"Starting…": "جارٍ البدء…",
"Stream is offline": "البث غير متاح حاليًا",
"LIVE VIDEO": "فيديو مباشر",
"STREAM ATTACHED TO THE SUBJECT": "بث مرتبط بالعنصر",
"Live video": "الفيديو المباشر",
"Show Live Video": "عرض الفيديو المباشر",
"This stream cannot play here": "لا يمكن تشغيل هذا البث هنا",
"Expand Live section": "توسيع قسم البث المباشر",
"Collapse Live section": "طيّ قسم البث المباشر",
"Expand Live": "توسيع البث المباشر",
"Collapse Live": "طيّ البث المباشر",
"Live streams for the selected object": "البث المباشر للعنصر المحدد",
"Stream": "البث",
"Previous stream": "البث السابق",
"Next stream": "البث التالي",
"Try again": "حاول مرة أخرى",
"Exterior cameras": "الكاميرات الخارجية",
"Live video and space-to-ground audio": "فيديو مباشر وصوت الاتصال بين الفضاء والأرض",
"NASA video, via YouTube": "فيديو ناسا، عبر يوتيوب",
"Controls for the selected space station": "عناصر التحكم في المحطة الفضائية المحددة",
"Expand Station section": "توسيع قسم المحطة",
"Collapse Station section": "طيّ قسم المحطة",
"Expand Station": "توسيع المحطة",
"Collapse Station": "طيّ المحطة",
"Manual · telemetry paused": "يدوي · القياسات متوقفة مؤقتًا",
"Telemetry · updated {ago} ago": "القياسات · آخر تحديث قبل {ago}",
"No signal since {time} · computed values": "لا إشارة منذ {time} · قيم محسوبة",
"No signal · computed values": "لا إشارة · قيم محسوبة",
"Telemetry unavailable · last update {ago} ago · computed values": "القياسات غير متاحة · آخر تحديث قبل {ago} · قيم محسوبة",
"Telemetry unavailable · computed values": "القياسات غير متاحة · قيم محسوبة",
"Telemetry not enabled on this server · computed values": "القياسات غير مفعّلة على هذا الخادم · قيم محسوبة",
"No public telemetry · computed values": "لا توجد قياسات عامة · قيم محسوبة",
"Zoom to Tiangong": "تقريب إلى تيانغونغ",
"Tianhe arm (degrees)": "ذراع تيانهه (درجات)",
"Tianhe wings (degrees)": "أجنحة تيانخه (درجات)",
"Lab wings (degrees)": "أجنحة المختبرين (درجات)",
"Port wing": "الجناح الأيسر",
"Starboard wing": "الجناح الأيمن",
"Wentian forward · alpha": "ونتيان الأمامي · ألفا",
"Wentian forward · beta": "ونتيان الأمامي · بيتا",
"Wentian aft · alpha": "ونتيان الخلفي · ألفا",
"Wentian aft · beta": "ونتيان الخلفي · بيتا",
"Mengtian forward · alpha": "منغتيان الأمامي · ألفا",
"Mengtian forward · beta": "منغتيان الأمامي · بيتا",
"Mengtian aft · alpha": "منغتيان الخلفي · ألفا",
"Mengtian aft · beta": "منغتيان الخلفي · بيتا",
"Wentian arm (degrees)": "ذراع ونتيان (درجات)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "الألواح تتبع الشمس، والهوائي يتجه نحو أقمار التتابع، والأذرع تتمايل للتوضيح. محسوب: الصين لا تنشر قياسات حية.",
"Telemetry reads while the model is on screen": "تُقرأ القياسات أثناء ظهور النموذج على الشاشة",
"Connecting to telemetry…": "جارٍ الاتصال بالقياسات…",
"{seconds} s": "{seconds} ث",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط."
}
+111 -1
View File
@@ -4315,5 +4315,115 @@
"Select a map item to see its details.": "Wähle ein Kartenelement aus, um seine Details zu sehen.",
"Bilawal on {site}": "Bilawal auf {site}",
"Bilawal's website": "Bilawals Website",
"BACK": "ZURÜCK"
"BACK": "ZURÜCK",
"Finding it…": "Wird gesucht…",
"No reading at this time": "Zu dieser Zeit kein Messwert",
"Last reading · {age}": "Letzter Stand · {age}",
"Find it": "Finden",
"Underneath": "Darunter",
"Open on YouTube": "Auf YouTube öffnen",
"Video plays from YouTube, which sees your IP address.": "Das Video wird von YouTube abgespielt, das Ihre IP-Adresse sieht.",
"Automatic": "Automatisch",
"Manual": "Manuell",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Solarflügel und Radiatoren folgen der Sonne, die Antennen richten sich auf Relaissatelliten aus und die Arme bewegen sich zur Veranschaulichung. Berechnet, keine Live-Telemetrie.",
"Overhead": "Über der Station",
"Ahead": "Voraus",
"Behind": "Dahinter",
"Port side": "Backbord",
"Starboard side": "Steuerbord",
"Night (shadow)": "Nacht (Schatten)",
"Sun position": "Sonnenstand",
"Follow the Sun": "Der Sonne folgen",
"Fast orbit (40 s)": "Schneller Umlauf (40 s)",
"Solar arrays": "Solarflügel",
"Demonstration: the real arrays stay extended.": "Demonstration: Die echten Solarflügel bleiben ausgefahren.",
"Retract": "Einfahren",
"Extend": "Ausfahren",
"Radiators": "Radiatoren",
"Demonstration: the real radiators can fold but stay extended.": "Demonstration: Die echten Radiatoren lassen sich falten, bleiben aber ausgefahren.",
"Dishes": "Antennen",
"Relay satellites": "Relaissatelliten",
"Up": "Nach oben",
"Forward": "Nach vorn",
"Sideways": "Zur Seite",
"Shoulder roll": "Schulter-Rollen",
"Shoulder yaw": "Schulter-Gieren",
"Shoulder pitch": "Schulter-Nicken",
"Elbow": "Ellbogen",
"Wrist pitch": "Handgelenk-Nicken",
"Wrist yaw": "Handgelenk-Gieren",
"Wrist roll": "Handgelenk-Rollen",
"Canadarm2 (degrees)": "Canadarm2 (Grad)",
"Resume sway": "Bewegung fortsetzen",
"Zoom to the ISS": "Auf die ISS zoomen",
"Now: in sunlight": "Jetzt: im Sonnenlicht",
"Now: in the Earth's shadow": "Jetzt: im Erdschatten",
"STATION VIEW · {name}": "STATIONSANSICHT · {name}",
"Previous station view": "Vorherige Stationsansicht",
"Next station view": "Nächste Stationsansicht",
"OBSERVATION MODULE · ISS": "BEOBACHTUNGSMODUL · ISS",
"European Space Agency (ESA)": "Europäische Weltraumorganisation (ESA)",
"7 WINDOWS": "7 FENSTER",
"LAUNCHED 8 FEB 2010 · STS-130": "GESTARTET 8. FEB. 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · ERDZUGEWANDTER PORT",
"LABORATORY MODULE · ISS": "LABORMODUL · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Japanische Raumfahrtagentur (JAXA)",
"2 WINDOWS": "2 FENSTER",
"LAUNCHED 31 MAY 2008 · STS-124": "GESTARTET 31. MAI 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · BACKBORDSEITE",
"Return to the default view": "Zur Standardansicht zurückkehren",
"{label} · STATION VIEW": "{label} · STATIONSANSICHT",
"ON AIR": "ON AIR",
"Starting…": "Startet…",
"Stream is offline": "Der Stream ist offline",
"LIVE VIDEO": "LIVE-VIDEO",
"STREAM ATTACHED TO THE SUBJECT": "STREAM ZUM OBJEKT",
"Live video": "Live-Video",
"Show Live Video": "Live-Video anzeigen",
"This stream cannot play here": "Dieser Stream kann hier nicht abgespielt werden",
"Expand Live section": "Live-Bereich ausklappen",
"Collapse Live section": "Live-Bereich einklappen",
"Expand Live": "Live ausklappen",
"Collapse Live": "Live einklappen",
"Live streams for the selected object": "Livestreams zum ausgewählten Objekt",
"Stream": "Stream",
"Previous stream": "Vorheriger Stream",
"Next stream": "Nächster Stream",
"Try again": "Erneut versuchen",
"Exterior cameras": "Außenkameras",
"Live video and space-to-ground audio": "Livevideo und Funkverkehr mit dem Boden",
"NASA video, via YouTube": "NASA-Video, über YouTube",
"Controls for the selected space station": "Steuerung der ausgewählten Raumstation",
"Expand Station section": "Stationsbereich ausklappen",
"Collapse Station section": "Stationsbereich einklappen",
"Expand Station": "Station ausklappen",
"Collapse Station": "Station einklappen",
"Manual · telemetry paused": "Manuell · Telemetrie pausiert",
"Telemetry · updated {ago} ago": "Telemetrie · aktualisiert vor {ago}",
"No signal since {time} · computed values": "Kein Signal seit {time} · berechnete Werte",
"No signal · computed values": "Kein Signal · berechnete Werte",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetrie nicht verfügbar · letzte Aktualisierung vor {ago} · berechnete Werte",
"Telemetry unavailable · computed values": "Telemetrie nicht verfügbar · berechnete Werte",
"Telemetry not enabled on this server · computed values": "Telemetrie auf diesem Server nicht aktiviert · berechnete Werte",
"No public telemetry · computed values": "Keine öffentliche Telemetrie · berechnete Werte",
"Zoom to Tiangong": "Auf Tiangong zoomen",
"Tianhe arm (degrees)": "Tianhe-Arm (Grad)",
"Tianhe wings (degrees)": "Tianhe-Flügel (Grad)",
"Lab wings (degrees)": "Labor-Flügel (Grad)",
"Port wing": "Backbordflügel",
"Starboard wing": "Steuerbordflügel",
"Wentian forward · alpha": "Wentian vorn · Alpha",
"Wentian forward · beta": "Wentian vorn · Beta",
"Wentian aft · alpha": "Wentian hinten · Alpha",
"Wentian aft · beta": "Wentian hinten · Beta",
"Mengtian forward · alpha": "Mengtian vorn · Alpha",
"Mengtian forward · beta": "Mengtian vorn · Beta",
"Mengtian aft · alpha": "Mengtian hinten · Alpha",
"Mengtian aft · beta": "Mengtian hinten · Beta",
"Wentian arm (degrees)": "Wentian-Arm (Grad)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Solarflügel folgen der Sonne, die Antenne richtet sich auf Relaissatelliten und die Arme schwenken zur Veranschaulichung. Berechnet: China veröffentlicht keine Live-Telemetrie.",
"Telemetry reads while the model is on screen": "Telemetrie wird gelesen, solange das Modell zu sehen ist",
"Connecting to telemetry…": "Verbindung zur Telemetrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Solarflügel, Radiatoren und eine Antenne folgen der Live-Telemetrie der NASA. Die andere Antenne steht still und die Arme bewegen sich zur Veranschaulichung."
}
+111 -1
View File
@@ -4421,5 +4421,115 @@
"Select a map item to see its details.": "Selecciona un elemento del mapa para ver sus detalles.",
"Bilawal on {site}": "Bilawal en {site}",
"Bilawal's website": "Sitio web de Bilawal",
"BACK": "ATRÁS"
"BACK": "ATRÁS",
"Finding it…": "Buscando…",
"No reading at this time": "Sin lectura a esta hora",
"Last reading · {age}": "Última lectura · {age}",
"Find it": "Encontrar",
"Underneath": "Abajo",
"Open on YouTube": "Abrir en YouTube",
"Video plays from YouTube, which sees your IP address.": "El vídeo se reproduce desde YouTube, que ve tu dirección IP.",
"Automatic": "Automático",
"Manual": "Manual",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Los paneles y radiadores siguen al Sol, las antenas apuntan a los satélites de retransmisión y los brazos se mueven a modo de ilustración. Calculado, no es telemetría en vivo.",
"Overhead": "Arriba",
"Ahead": "Delante",
"Behind": "Detrás",
"Port side": "Babor",
"Starboard side": "Estribor",
"Night (shadow)": "Noche (sombra)",
"Sun position": "Posición del Sol",
"Follow the Sun": "Seguir al Sol",
"Fast orbit (40 s)": "Órbita rápida (40 s)",
"Solar arrays": "Paneles solares",
"Demonstration: the real arrays stay extended.": "Demostración: los paneles reales permanecen desplegados.",
"Retract": "Recoger",
"Extend": "Desplegar",
"Radiators": "Radiadores",
"Demonstration: the real radiators can fold but stay extended.": "Demostración: los radiadores reales pueden plegarse, pero permanecen desplegados.",
"Dishes": "Antenas",
"Relay satellites": "Satélites de retransmisión",
"Up": "Arriba",
"Forward": "Adelante",
"Sideways": "De lado",
"Shoulder roll": "Alabeo del hombro",
"Shoulder yaw": "Guiñada del hombro",
"Shoulder pitch": "Cabeceo del hombro",
"Elbow": "Codo",
"Wrist pitch": "Cabeceo de la muñeca",
"Wrist yaw": "Guiñada de la muñeca",
"Wrist roll": "Alabeo de la muñeca",
"Canadarm2 (degrees)": "Canadarm2 (grados)",
"Resume sway": "Reanudar movimiento",
"Zoom to the ISS": "Acercar a la ISS",
"Now: in sunlight": "Ahora: a la luz del Sol",
"Now: in the Earth's shadow": "Ahora: a la sombra de la Tierra",
"{label} · STATION VIEW": "{label} · VISTA DE LA ESTACIÓN",
"STATION VIEW · {name}": "VISTA DE LA ESTACIÓN · {name}",
"Previous station view": "Vista anterior de la estación",
"Next station view": "Siguiente vista de la estación",
"OBSERVATION MODULE · ISS": "MÓDULO DE OBSERVACIÓN · ISS",
"European Space Agency (ESA)": "Agencia Espacial Europea (ESA)",
"7 WINDOWS": "7 VENTANAS",
"LAUNCHED 8 FEB 2010 · STS-130": "LANZADO EL 8 FEB 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · PUERTO ORIENTADO A LA TIERRA",
"LABORATORY MODULE · ISS": "MÓDULO LABORATORIO · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Agencia Japonesa de Exploración Aeroespacial (JAXA)",
"2 WINDOWS": "2 VENTANAS",
"LAUNCHED 31 MAY 2008 · STS-124": "LANZADO EL 31 MAY 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · LADO DE BABOR",
"Return to the default view": "Volver a la vista predeterminada",
"ON AIR": "EN EL AIRE",
"Starting…": "Iniciando…",
"Stream is offline": "La transmisión está fuera de línea",
"LIVE VIDEO": "VÍDEO EN VIVO",
"STREAM ATTACHED TO THE SUBJECT": "TRANSMISIÓN VINCULADA AL OBJETO",
"Live video": "Vídeo en vivo",
"Show Live Video": "Mostrar Vídeo en vivo",
"This stream cannot play here": "Esta transmisión no se puede reproducir aquí",
"Expand Live section": "Expandir la sección En directo",
"Collapse Live section": "Contraer la sección En directo",
"Expand Live": "Expandir En directo",
"Collapse Live": "Contraer En directo",
"Live streams for the selected object": "Transmisiones en directo del objeto seleccionado",
"Stream": "Transmisión",
"Previous stream": "Transmisión anterior",
"Next stream": "Siguiente transmisión",
"Try again": "Reintentar",
"Exterior cameras": "Cámaras exteriores",
"Live video and space-to-ground audio": "Vídeo en directo y audio espacio-tierra",
"NASA video, via YouTube": "Vídeo de la NASA, vía YouTube",
"Controls for the selected space station": "Controles de la estación espacial seleccionada",
"Expand Station section": "Expandir la sección Estación",
"Collapse Station section": "Contraer la sección Estación",
"Expand Station": "Expandir Estación",
"Collapse Station": "Contraer Estación",
"Manual · telemetry paused": "Manual · telemetría en pausa",
"Telemetry · updated {ago} ago": "Telemetría · actualizada hace {ago}",
"No signal since {time} · computed values": "Sin señal desde las {time} · valores calculados",
"No signal · computed values": "Sin señal · valores calculados",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetría no disponible · última actualización hace {ago} · valores calculados",
"Telemetry unavailable · computed values": "Telemetría no disponible · valores calculados",
"Telemetry not enabled on this server · computed values": "Telemetría no activada en este servidor · valores calculados",
"No public telemetry · computed values": "Sin telemetría pública · valores calculados",
"Zoom to Tiangong": "Acercar a Tiangong",
"Tianhe arm (degrees)": "Brazo de Tianhe (grados)",
"Tianhe wings (degrees)": "Alas de Tianhe (grados)",
"Lab wings (degrees)": "Alas de los laboratorios (grados)",
"Port wing": "Ala de babor",
"Starboard wing": "Ala de estribor",
"Wentian forward · alpha": "Wentian delantera · alfa",
"Wentian forward · beta": "Wentian delantera · beta",
"Wentian aft · alpha": "Wentian trasera · alfa",
"Wentian aft · beta": "Wentian trasera · beta",
"Mengtian forward · alpha": "Mengtian delantera · alfa",
"Mengtian forward · beta": "Mengtian delantera · beta",
"Mengtian aft · alpha": "Mengtian trasera · alfa",
"Mengtian aft · beta": "Mengtian trasera · beta",
"Wentian arm (degrees)": "Brazo de Wentian (grados)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Los paneles siguen al Sol, la antena apunta a los satélites de retransmisión y los brazos se mueven a modo de ilustración. Calculado: China no publica telemetría en directo.",
"Telemetry reads while the model is on screen": "La telemetría se lee mientras el modelo está en pantalla",
"Connecting to telemetry…": "Conectando con la telemetría…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Los paneles, los radiadores y una antena siguen la telemetría en vivo de la NASA. La otra antena permanece quieta y los brazos se mueven a modo de ilustración."
}
+111 -1
View File
@@ -4421,5 +4421,115 @@
"Select a map item to see its details.": "Sélectionnez un élément de la carte pour voir ses détails.",
"Bilawal on {site}": "Bilawal sur {site}",
"Bilawal's website": "Site web de Bilawal",
"BACK": "RETOUR"
"BACK": "RETOUR",
"Finding it…": "Recherche…",
"No reading at this time": "Aucune donnée à cette heure",
"Last reading · {age}": "Dernière donnée · {age}",
"Find it": "Retrouver",
"Underneath": "En dessous",
"Open on YouTube": "Ouvrir sur YouTube",
"Video plays from YouTube, which sees your IP address.": "La vidéo est lue depuis YouTube, qui voit votre adresse IP.",
"Automatic": "Automatique",
"Manual": "Manuel",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Les panneaux et les radiateurs suivent le Soleil, les antennes visent les satellites relais et les bras bougent à titre d'illustration. Calculé, pas de télémétrie en direct.",
"Overhead": "Au-dessus",
"Ahead": "Devant",
"Behind": "Derrière",
"Port side": "Bâbord",
"Starboard side": "Tribord",
"Night (shadow)": "Nuit (ombre)",
"Sun position": "Position du Soleil",
"Follow the Sun": "Suivre le Soleil",
"Fast orbit (40 s)": "Orbite rapide (40 s)",
"Solar arrays": "Panneaux solaires",
"Demonstration: the real arrays stay extended.": "Démonstration : les vrais panneaux restent déployés.",
"Retract": "Rétracter",
"Extend": "Déployer",
"Radiators": "Radiateurs",
"Demonstration: the real radiators can fold but stay extended.": "Démonstration : les vrais radiateurs peuvent se replier mais restent déployés.",
"Dishes": "Antennes",
"Relay satellites": "Satellites relais",
"Up": "Vers le haut",
"Forward": "Vers l'avant",
"Sideways": "Sur le côté",
"Shoulder roll": "Roulis d'épaule",
"Shoulder yaw": "Lacet d'épaule",
"Shoulder pitch": "Tangage d'épaule",
"Elbow": "Coude",
"Wrist pitch": "Tangage du poignet",
"Wrist yaw": "Lacet du poignet",
"Wrist roll": "Roulis du poignet",
"Canadarm2 (degrees)": "Canadarm2 (degrés)",
"Resume sway": "Reprendre le mouvement",
"Zoom to the ISS": "Zoomer sur l'ISS",
"Now: in sunlight": "En ce moment : au soleil",
"Now: in the Earth's shadow": "En ce moment : dans l'ombre de la Terre",
"STATION VIEW · {name}": "VUE DE LA STATION · {name}",
"Previous station view": "Vue précédente de la station",
"Next station view": "Vue suivante de la station",
"OBSERVATION MODULE · ISS": "MODULE D'OBSERVATION · ISS",
"European Space Agency (ESA)": "Agence spatiale européenne (ESA)",
"7 WINDOWS": "7 HUBLOTS",
"LAUNCHED 8 FEB 2010 · STS-130": "LANCÉ LE 8 FÉV. 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · PORT ORIENTÉ VERS LA TERRE",
"LABORATORY MODULE · ISS": "MODULE LABORATOIRE · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Agence japonaise d'exploration aérospatiale (JAXA)",
"2 WINDOWS": "2 HUBLOTS",
"LAUNCHED 31 MAY 2008 · STS-124": "LANCÉ LE 31 MAI 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · CÔTÉ BÂBORD",
"Return to the default view": "Revenir à la vue par défaut",
"{label} · STATION VIEW": "{label} · VUE DE LA STATION",
"ON AIR": "À L’ANTENNE",
"Starting…": "Démarrage…",
"Stream is offline": "Le flux est hors ligne",
"LIVE VIDEO": "VIDÉO EN DIRECT",
"STREAM ATTACHED TO THE SUBJECT": "FLUX ATTACHÉ À L’OBJET",
"Live video": "Vidéo en direct",
"Show Live Video": "Afficher la vidéo en direct",
"This stream cannot play here": "Ce flux ne peut pas être lu ici",
"Expand Live section": "Déplier la section Direct",
"Collapse Live section": "Replier la section Direct",
"Expand Live": "Déplier Direct",
"Collapse Live": "Replier Direct",
"Live streams for the selected object": "Flux en direct de l’objet sélectionné",
"Stream": "Flux",
"Previous stream": "Flux précédent",
"Next stream": "Flux suivant",
"Try again": "Réessayer",
"Exterior cameras": "Caméras extérieures",
"Live video and space-to-ground audio": "Vidéo en direct et audio espace-sol",
"NASA video, via YouTube": "Vidéo de la NASA, via YouTube",
"Controls for the selected space station": "Commandes de la station spatiale sélectionnée",
"Expand Station section": "Déplier la section Station",
"Collapse Station section": "Replier la section Station",
"Expand Station": "Déplier Station",
"Collapse Station": "Replier Station",
"Manual · telemetry paused": "Manuel · télémétrie en pause",
"Telemetry · updated {ago} ago": "Télémétrie · mise à jour il y a {ago}",
"No signal since {time} · computed values": "Pas de signal depuis {time} · valeurs calculées",
"No signal · computed values": "Pas de signal · valeurs calculées",
"Telemetry unavailable · last update {ago} ago · computed values": "Télémétrie indisponible · dernière mise à jour il y a {ago} · valeurs calculées",
"Telemetry unavailable · computed values": "Télémétrie indisponible · valeurs calculées",
"Telemetry not enabled on this server · computed values": "Télémétrie non activée sur ce serveur · valeurs calculées",
"No public telemetry · computed values": "Pas de télémétrie publique · valeurs calculées",
"Zoom to Tiangong": "Zoomer sur Tiangong",
"Tianhe arm (degrees)": "Bras de Tianhe (degrés)",
"Tianhe wings (degrees)": "Ailes de Tianhe (degrés)",
"Lab wings (degrees)": "Ailes des laboratoires (degrés)",
"Port wing": "Aile bâbord",
"Starboard wing": "Aile tribord",
"Wentian forward · alpha": "Wentian avant · alpha",
"Wentian forward · beta": "Wentian avant · bêta",
"Wentian aft · alpha": "Wentian arrière · alpha",
"Wentian aft · beta": "Wentian arrière · bêta",
"Mengtian forward · alpha": "Mengtian avant · alpha",
"Mengtian forward · beta": "Mengtian avant · bêta",
"Mengtian aft · alpha": "Mengtian arrière · alpha",
"Mengtian aft · beta": "Mengtian arrière · bêta",
"Wentian arm (degrees)": "Bras de Wentian (degrés)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Les panneaux suivent le Soleil, l'antenne vise les satellites relais et les bras oscillent à titre d'illustration. Calculé : la Chine ne publie pas de télémétrie en direct.",
"Telemetry reads while the model is on screen": "La télémétrie est lue tant que le modèle est à l'écran",
"Connecting to telemetry…": "Connexion à la télémétrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Les panneaux, les radiateurs et une antenne suivent la télémétrie en direct de la NASA. L'autre antenne reste immobile et les bras bougent à titre d'illustration."
}
+111 -1
View File
@@ -4421,5 +4421,115 @@
"Bilawal on YouTube": "בילוואל ב־YouTube",
"The studio behind GEV": "הסטודיו שמאחורי GEV",
"Open source. Self-host, fork, add a layer.": "קוד פתוח. אירוח עצמאי, יצירת עותק והוספת שכבה.",
"ENTER GOD MODE": "כניסה למצב אלוהים"
"ENTER GOD MODE": "כניסה למצב אלוהים",
"Finding it…": "מחפש…",
"No reading at this time": "אין קריאה בזמן הזה",
"Last reading · {age}": "קריאה אחרונה · {age}",
"Find it": "מצא",
"Underneath": "מתחת",
"Open on YouTube": "פתיחה ב-YouTube",
"Video plays from YouTube, which sees your IP address.": "הווידאו זורם מ-YouTube, שרואה את כתובת ה-IP שלך.",
"Automatic": "אוטומטי",
"Manual": "ידני",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "הלוחות והרדיאטורים עוקבים אחר השמש, הצלחות מכוונות ללווייני ממסר והזרועות נעות להמחשה בלבד. מחושב, לא טלמטריה חיה.",
"Overhead": "מעל",
"Ahead": "מלפנים",
"Behind": "מאחור",
"Port side": "צד שמאל",
"Starboard side": "צד ימין",
"Night (shadow)": "לילה (צל)",
"Sun position": "מיקום השמש",
"Follow the Sun": "מעקב אחר השמש",
"Fast orbit (40 s)": "הקפה מהירה (40 שנ')",
"Solar arrays": "לוחות סולאריים",
"Demonstration: the real arrays stay extended.": "הדגמה: הלוחות האמיתיים נשארים פרושים.",
"Retract": "קיפול",
"Extend": "פריסה",
"Radiators": "רדיאטורים",
"Demonstration: the real radiators can fold but stay extended.": "הדגמה: הרדיאטורים האמיתיים יכולים להתקפל אך נשארים פרושים.",
"Dishes": "צלחות",
"Relay satellites": "לווייני ממסר",
"Up": "למעלה",
"Forward": "קדימה",
"Sideways": "הצידה",
"Shoulder roll": "גלגול כתף",
"Shoulder yaw": "סבסוב כתף",
"Shoulder pitch": "עלרוד כתף",
"Elbow": "מרפק",
"Wrist pitch": "עלרוד שורש כף היד",
"Wrist yaw": "סבסוב שורש כף היד",
"Wrist roll": "גלגול שורש כף היד",
"Canadarm2 (degrees)": "Canadarm2 (מעלות)",
"Resume sway": "חידוש התנועה",
"Zoom to the ISS": "התקרבות לתחנת החלל",
"Now: in sunlight": "כעת: באור השמש",
"Now: in the Earth's shadow": "כעת: בצל כדור הארץ",
"{label} · STATION VIEW": "{label} · תצוגת התחנה",
"STATION VIEW · {name}": "תצוגת התחנה · {name}",
"Previous station view": "תצוגת התחנה הקודמת",
"Next station view": "תצוגת התחנה הבאה",
"OBSERVATION MODULE · ISS": "מודול תצפית · תחנת החלל",
"European Space Agency (ESA)": "סוכנות החלל האירופית (ESA)",
"7 WINDOWS": "7 חלונות",
"LAUNCHED 8 FEB 2010 · STS-130": "שוגר ב-8 בפברואר 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "טרנקוויליטי · פתח הפונה לכדור הארץ",
"LABORATORY MODULE · ISS": "מודול מעבדה · תחנת החלל",
"Japan Aerospace Exploration Agency (JAXA)": "סוכנות חקר החלל היפנית (JAXA)",
"2 WINDOWS": "2 חלונות",
"LAUNCHED 31 MAY 2008 · STS-124": "שוגר ב-31 במאי 2008 · STS-124",
"HARMONY · PORT SIDE": "הרמוני · צד שמאל",
"Return to the default view": "חזרה לתצוגת ברירת המחדל",
"ON AIR": "בשידור",
"Starting…": "מתחיל…",
"Stream is offline": "השידור אינו פעיל",
"LIVE VIDEO": "וידאו חי",
"STREAM ATTACHED TO THE SUBJECT": "שידור המשויך לפריט",
"Live video": "וידאו חי",
"Show Live Video": "הצגת וידאו חי",
"This stream cannot play here": "לא ניתן להפעיל שידור זה כאן",
"Expand Live section": "הרחבת מקטע השידור החי",
"Collapse Live section": "כיווץ מקטע השידור החי",
"Expand Live": "הרחבת שידור חי",
"Collapse Live": "כיווץ שידור חי",
"Live streams for the selected object": "שידורים חיים של הפריט שנבחר",
"Stream": "שידור",
"Previous stream": "השידור הקודם",
"Next stream": "השידור הבא",
"Try again": "ניסיון חוזר",
"Exterior cameras": "מצלמות חיצוניות",
"Live video and space-to-ground audio": "וידאו חי ושמע חלל–קרקע",
"NASA video, via YouTube": "וידאו של נאס״א, דרך יוטיוב",
"Controls for the selected space station": "בקרות לתחנת החלל שנבחרה",
"Expand Station section": "הרחבת מקטע התחנה",
"Collapse Station section": "כיווץ מקטע התחנה",
"Expand Station": "הרחבת התחנה",
"Collapse Station": "כיווץ התחנה",
"Manual · telemetry paused": "ידני · הטלמטריה מושהית",
"Telemetry · updated {ago} ago": "טלמטריה · עודכנה לפני {ago}",
"No signal since {time} · computed values": "אין אות מאז {time} · ערכים מחושבים",
"No signal · computed values": "אין אות · ערכים מחושבים",
"Telemetry unavailable · last update {ago} ago · computed values": "הטלמטריה אינה זמינה · עדכון אחרון לפני {ago} · ערכים מחושבים",
"Telemetry unavailable · computed values": "הטלמטריה אינה זמינה · ערכים מחושבים",
"Telemetry not enabled on this server · computed values": "הטלמטריה אינה מופעלת בשרת זה · ערכים מחושבים",
"No public telemetry · computed values": "אין טלמטריה ציבורית · ערכים מחושבים",
"Zoom to Tiangong": "התקרבות לטיאנגונג",
"Tianhe arm (degrees)": "זרוע טיאנהה (מעלות)",
"Tianhe wings (degrees)": "כנפי טיאנחה (מעלות)",
"Lab wings (degrees)": "כנפי המעבדות (מעלות)",
"Port wing": "כנף שמאל",
"Starboard wing": "כנף ימין",
"Wentian forward · alpha": "ונטיאן קדמי · אלפא",
"Wentian forward · beta": "ונטיאן קדמי · בטא",
"Wentian aft · alpha": "ונטיאן אחורי · אלפא",
"Wentian aft · beta": "ונטיאן אחורי · בטא",
"Mengtian forward · alpha": "מנגטיאן קדמי · אלפא",
"Mengtian forward · beta": "מנגטיאן קדמי · בטא",
"Mengtian aft · alpha": "מנגטיאן אחורי · אלפא",
"Mengtian aft · beta": "מנגטיאן אחורי · בטא",
"Wentian arm (degrees)": "זרוע ונטיאן (מעלות)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "הלוחות עוקבים אחר השמש, האנטנה מכוונת ללווייני ממסר והזרועות נעות לצורכי הדגמה. מחושב: סין אינה מפרסמת טלמטריה חיה.",
"Telemetry reads while the model is on screen": "הטלמטריה נקראת כל עוד הדגם מוצג על המסך",
"Connecting to telemetry…": "מתחבר לטלמטריה…",
"{seconds} s": "{seconds} שנ׳",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד."
}
+111 -1
View File
@@ -4421,5 +4421,115 @@
"Select a map item to see its details.": "Seleziona un elemento della mappa per vederne i dettagli.",
"Bilawal on {site}": "Bilawal su {site}",
"Bilawal's website": "Sito web di Bilawal",
"BACK": "INDIETRO"
"BACK": "INDIETRO",
"Finding it…": "Ricerca in corso…",
"No reading at this time": "Nessun dato a quest'ora",
"Last reading · {age}": "Ultimo dato · {age}",
"Find it": "Trova",
"Underneath": "Sotto",
"Open on YouTube": "Apri su YouTube",
"Video plays from YouTube, which sees your IP address.": "Il video viene riprodotto da YouTube, che vede il tuo indirizzo IP.",
"Automatic": "Automatico",
"Manual": "Manuale",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Pannelli e radiatori seguono il Sole, le antenne puntano ai satelliti di collegamento e i bracci si muovono a scopo illustrativo. Calcolato, non telemetria in diretta.",
"Overhead": "Sopra",
"Ahead": "Davanti",
"Behind": "Dietro",
"Port side": "Babordo",
"Starboard side": "Tribordo",
"Night (shadow)": "Notte (ombra)",
"Sun position": "Posizione del Sole",
"Follow the Sun": "Segui il Sole",
"Fast orbit (40 s)": "Orbita veloce (40 s)",
"Solar arrays": "Pannelli solari",
"Demonstration: the real arrays stay extended.": "Dimostrazione: i pannelli reali restano dispiegati.",
"Retract": "Ritira",
"Extend": "Dispiega",
"Radiators": "Radiatori",
"Demonstration: the real radiators can fold but stay extended.": "Dimostrazione: i radiatori reali possono ripiegarsi ma restano dispiegati.",
"Dishes": "Antenne",
"Relay satellites": "Satelliti di collegamento",
"Up": "In alto",
"Forward": "In avanti",
"Sideways": "Di lato",
"Shoulder roll": "Rollio spalla",
"Shoulder yaw": "Imbardata spalla",
"Shoulder pitch": "Beccheggio spalla",
"Elbow": "Gomito",
"Wrist pitch": "Beccheggio polso",
"Wrist yaw": "Imbardata polso",
"Wrist roll": "Rollio polso",
"Canadarm2 (degrees)": "Canadarm2 (gradi)",
"Resume sway": "Riprendi movimento",
"Zoom to the ISS": "Zoom sulla ISS",
"Now: in sunlight": "Ora: alla luce del Sole",
"Now: in the Earth's shadow": "Ora: nell'ombra della Terra",
"STATION VIEW · {name}": "VISTA DELLA STAZIONE · {name}",
"Previous station view": "Vista precedente della stazione",
"Next station view": "Vista successiva della stazione",
"OBSERVATION MODULE · ISS": "MODULO DI OSSERVAZIONE · ISS",
"European Space Agency (ESA)": "Agenzia Spaziale Europea (ESA)",
"7 WINDOWS": "7 FINESTRINI",
"LAUNCHED 8 FEB 2010 · STS-130": "LANCIATO L’8 FEB 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · PORTELLONE RIVOLTO ALLA TERRA",
"LABORATORY MODULE · ISS": "MODULO LABORATORIO · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Agenzia Giapponese per l’Esplorazione Aerospaziale (JAXA)",
"2 WINDOWS": "2 FINESTRINI",
"LAUNCHED 31 MAY 2008 · STS-124": "LANCIATO IL 31 MAG 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · LATO DI BABORDO",
"Return to the default view": "Torna alla vista predefinita",
"{label} · STATION VIEW": "{label} · VISTA DELLA STAZIONE",
"ON AIR": "IN ONDA",
"Starting…": "Avvio…",
"Stream is offline": "La diretta è offline",
"LIVE VIDEO": "VIDEO LIVE",
"STREAM ATTACHED TO THE SUBJECT": "DIRETTA COLLEGATA ALL’OGGETTO",
"Live video": "Video live",
"Show Live Video": "Mostra Video live",
"This stream cannot play here": "Questa diretta non può essere riprodotta qui",
"Expand Live section": "Espandi la sezione Live",
"Collapse Live section": "Comprimi la sezione Live",
"Expand Live": "Espandi Live",
"Collapse Live": "Comprimi Live",
"Live streams for the selected object": "Dirette dell’oggetto selezionato",
"Stream": "Diretta",
"Previous stream": "Diretta precedente",
"Next stream": "Diretta successiva",
"Try again": "Riprova",
"Exterior cameras": "Telecamere esterne",
"Live video and space-to-ground audio": "Video in diretta e audio spazio-terra",
"NASA video, via YouTube": "Video NASA, tramite YouTube",
"Controls for the selected space station": "Controlli della stazione spaziale selezionata",
"Expand Station section": "Espandi la sezione Stazione",
"Collapse Station section": "Comprimi la sezione Stazione",
"Expand Station": "Espandi Stazione",
"Collapse Station": "Comprimi Stazione",
"Manual · telemetry paused": "Manuale · telemetria in pausa",
"Telemetry · updated {ago} ago": "Telemetria · aggiornata {ago} fa",
"No signal since {time} · computed values": "Nessun segnale dalle {time} · valori calcolati",
"No signal · computed values": "Nessun segnale · valori calcolati",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetria non disponibile · ultimo aggiornamento {ago} fa · valori calcolati",
"Telemetry unavailable · computed values": "Telemetria non disponibile · valori calcolati",
"Telemetry not enabled on this server · computed values": "Telemetria non attivata su questo server · valori calcolati",
"No public telemetry · computed values": "Nessuna telemetria pubblica · valori calcolati",
"Zoom to Tiangong": "Zoom su Tiangong",
"Tianhe arm (degrees)": "Braccio di Tianhe (gradi)",
"Tianhe wings (degrees)": "Ali di Tianhe (gradi)",
"Lab wings (degrees)": "Ali dei laboratori (gradi)",
"Port wing": "Ala di sinistra",
"Starboard wing": "Ala di dritta",
"Wentian forward · alpha": "Wentian anteriore · alfa",
"Wentian forward · beta": "Wentian anteriore · beta",
"Wentian aft · alpha": "Wentian posteriore · alfa",
"Wentian aft · beta": "Wentian posteriore · beta",
"Mengtian forward · alpha": "Mengtian anteriore · alfa",
"Mengtian forward · beta": "Mengtian anteriore · beta",
"Mengtian aft · alpha": "Mengtian posteriore · alfa",
"Mengtian aft · beta": "Mengtian posteriore · beta",
"Wentian arm (degrees)": "Braccio di Wentian (gradi)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "I pannelli seguono il Sole, l'antenna punta ai satelliti di collegamento e i bracci oscillano a scopo illustrativo. Calcolato: la Cina non pubblica telemetria in tempo reale.",
"Telemetry reads while the model is on screen": "La telemetria viene letta finché il modello è sullo schermo",
"Connecting to telemetry…": "Connessione alla telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Pannelli, radiatori e un'antenna seguono la telemetria in diretta della NASA. L'altra antenna resta ferma e i bracci si muovono a scopo illustrativo."
}
+111 -1
View File
@@ -4209,5 +4209,115 @@
"Select a map item to see its details.": "地図上の項目を選択すると詳細が表示されます。",
"Bilawal on {site}": "{site}のBilawal",
"Bilawal's website": "Bilawalのウェブサイト",
"BACK": "戻る"
"BACK": "戻る",
"Finding it…": "検索中…",
"No reading at this time": "この時刻のデータなし",
"Last reading · {age}": "最終データ・{age}",
"Find it": "探す",
"Underneath": "真下",
"Open on YouTube": "YouTubeで開く",
"Video plays from YouTube, which sees your IP address.": "動画は YouTube から再生され、YouTube にはあなたの IP アドレスが見えます。",
"Automatic": "自動",
"Manual": "手動",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "太陽電池パネルとラジエーターは太陽を追い、アンテナは中継衛星を向き、アームは説明用にゆっくり動きます。計算による表示で、実際のテレメトリではありません。",
"Overhead": "真上",
"Ahead": "前方",
"Behind": "後方",
"Port side": "左舷",
"Starboard side": "右舷",
"Night (shadow)": "夜(影)",
"Sun position": "太陽の位置",
"Follow the Sun": "太陽を追う",
"Fast orbit (40 s)": "高速周回(40秒)",
"Solar arrays": "太陽電池パネル",
"Demonstration: the real arrays stay extended.": "デモ表示:実際のパネルは展開したままです。",
"Retract": "収納",
"Extend": "展開",
"Radiators": "ラジエーター",
"Demonstration: the real radiators can fold but stay extended.": "デモ表示:実際のラジエーターは折りたためますが、展開したままです。",
"Dishes": "アンテナ",
"Relay satellites": "中継衛星",
"Up": "上",
"Forward": "前",
"Sideways": "横",
"Shoulder roll": "肩ロール",
"Shoulder yaw": "肩ヨー",
"Shoulder pitch": "肩ピッチ",
"Elbow": "肘",
"Wrist pitch": "手首ピッチ",
"Wrist yaw": "手首ヨー",
"Wrist roll": "手首ロール",
"Canadarm2 (degrees)": "Canadarm2(度)",
"Resume sway": "自動の動きに戻す",
"Zoom to the ISS": "ISSにズーム",
"Now: in sunlight": "現在:日なた",
"Now: in the Earth's shadow": "現在:地球の影の中",
"STATION VIEW · {name}": "ステーションビュー · {name}",
"Previous station view": "前のステーションビュー",
"Next station view": "次のステーションビュー",
"OBSERVATION MODULE · ISS": "観測モジュール · ISS",
"European Space Agency (ESA)": "欧州宇宙機関(ESA)",
"7 WINDOWS": "窓 7 枚",
"LAUNCHED 8 FEB 2010 · STS-130": "2010年2月8日打ち上げ · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "トランクウィリティー · 地球側ポート",
"LABORATORY MODULE · ISS": "実験モジュール · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "宇宙航空研究開発機構(JAXA)",
"2 WINDOWS": "窓 2 枚",
"LAUNCHED 31 MAY 2008 · STS-124": "2008年5月31日打ち上げ · STS-124",
"HARMONY · PORT SIDE": "ハーモニー · 左舷側",
"Return to the default view": "既定のビューに戻す",
"{label} · STATION VIEW": "{label} · ステーションビュー",
"ON AIR": "オンエア",
"Starting…": "開始しています…",
"Stream is offline": "ストリームはオフラインです",
"LIVE VIDEO": "ライブ映像",
"STREAM ATTACHED TO THE SUBJECT": "対象に紐づくライブ配信",
"Live video": "ライブ映像",
"Show Live Video": "ライブ映像を表示",
"This stream cannot play here": "このストリームはここでは再生できません",
"Expand Live section": "ライブセクションを展開",
"Collapse Live section": "ライブセクションを折りたたむ",
"Expand Live": "ライブを展開",
"Collapse Live": "ライブを折りたたむ",
"Live streams for the selected object": "選択中のオブジェクトのライブ配信",
"Stream": "ストリーム",
"Previous stream": "前のストリーム",
"Next stream": "次のストリーム",
"Try again": "再試行",
"Exterior cameras": "船外カメラ",
"Live video and space-to-ground audio": "ライブ映像と地上との交信音声",
"NASA video, via YouTube": "NASAの映像、YouTube経由",
"Controls for the selected space station": "選択中の宇宙ステーションの操作",
"Expand Station section": "ステーションセクションを展開",
"Collapse Station section": "ステーションセクションを折りたたむ",
"Expand Station": "ステーションを展開",
"Collapse Station": "ステーションを折りたたむ",
"Manual · telemetry paused": "手動 · テレメトリ一時停止",
"Telemetry · updated {ago} ago": "テレメトリ · {ago}前に更新",
"No signal since {time} · computed values": "{time}から信号なし · 計算値",
"No signal · computed values": "信号なし · 計算値",
"Telemetry unavailable · last update {ago} ago · computed values": "テレメトリ利用不可 · 最終更新は{ago}前 · 計算値",
"Telemetry unavailable · computed values": "テレメトリ利用不可 · 計算値",
"Telemetry not enabled on this server · computed values": "このサーバーではテレメトリが無効 · 計算値",
"No public telemetry · computed values": "公開テレメトリなし · 計算値",
"Zoom to Tiangong": "天宮にズーム",
"Tianhe arm (degrees)": "天和アーム(度)",
"Tianhe wings (degrees)": "天和の翼(度)",
"Lab wings (degrees)": "実験モジュールの翼(度)",
"Port wing": "左舷の翼",
"Starboard wing": "右舷の翼",
"Wentian forward · alpha": "問天 前方 · アルファ",
"Wentian forward · beta": "問天 前方 · ベータ",
"Wentian aft · alpha": "問天 後方 · アルファ",
"Wentian aft · beta": "問天 後方 · ベータ",
"Mengtian forward · alpha": "夢天 前方 · アルファ",
"Mengtian forward · beta": "夢天 前方 · ベータ",
"Mengtian aft · alpha": "夢天 後方 · アルファ",
"Mengtian aft · beta": "夢天 後方 · ベータ",
"Wentian arm (degrees)": "問天アーム(度)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "太陽電池パネルは太陽を追い、アンテナは中継衛星に向き、アームは説明のために揺れます。計算値:中国はライブテレメトリを公開していません。",
"Telemetry reads while the model is on screen": "テレメトリはモデルが画面にある間に読み取られます",
"Connecting to telemetry…": "テレメトリに接続中…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。"
}
+111 -1
View File
@@ -4421,5 +4421,115 @@
"Select a map item to see its details.": "Selecione um item do mapa para ver seus detalhes.",
"Bilawal on {site}": "Bilawal no {site}",
"Bilawal's website": "Site de Bilawal",
"BACK": "VOLTAR"
"BACK": "VOLTAR",
"Finding it…": "A procurar…",
"No reading at this time": "Sem leitura nesta hora",
"Last reading · {age}": "Última leitura · {age}",
"Find it": "Encontrar",
"Underneath": "Embaixo",
"Open on YouTube": "Abrir no YouTube",
"Video plays from YouTube, which sees your IP address.": "O vídeo é reproduzido a partir do YouTube, que vê o seu endereço IP.",
"Automatic": "Automático",
"Manual": "Manual",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Painéis e radiadores seguem o Sol, as antenas apontam para os satélites de retransmissão e os braços se movem de forma ilustrativa. Calculado, não é telemetria ao vivo.",
"Overhead": "Em cima",
"Ahead": "À frente",
"Behind": "Atrás",
"Port side": "Bombordo",
"Starboard side": "Estibordo",
"Night (shadow)": "Noite (sombra)",
"Sun position": "Posição do Sol",
"Follow the Sun": "Seguir o Sol",
"Fast orbit (40 s)": "Órbita acelerada (40 s)",
"Solar arrays": "Painéis solares",
"Demonstration: the real arrays stay extended.": "Demonstração: os painéis reais ficam abertos.",
"Retract": "Recolher",
"Extend": "Expandir",
"Radiators": "Radiadores",
"Demonstration: the real radiators can fold but stay extended.": "Demonstração: os radiadores reais podem dobrar, mas ficam abertos.",
"Dishes": "Antenas",
"Relay satellites": "Satélites de retransmissão",
"Up": "Para cima",
"Forward": "Para frente",
"Sideways": "Para o lado",
"Shoulder roll": "Ombro (giro)",
"Shoulder yaw": "Ombro (guinada)",
"Shoulder pitch": "Ombro (arfagem)",
"Elbow": "Cotovelo",
"Wrist pitch": "Pulso (arfagem)",
"Wrist yaw": "Pulso (guinada)",
"Wrist roll": "Pulso (giro)",
"Canadarm2 (degrees)": "Canadarm2 (graus)",
"Resume sway": "Retomar movimento",
"Zoom to the ISS": "Aproximar da ISS",
"Now: in sunlight": "Agora: na luz do Sol",
"Now: in the Earth's shadow": "Agora: na sombra da Terra",
"STATION VIEW · {name}": "VISTA DA ESTAÇÃO · {name}",
"Previous station view": "Vista anterior da estação",
"Next station view": "Próxima vista da estação",
"OBSERVATION MODULE · ISS": "MÓDULO DE OBSERVAÇÃO · ISS",
"European Space Agency (ESA)": "Agência Espacial Europeia (ESA)",
"7 WINDOWS": "7 JANELAS",
"LAUNCHED 8 FEB 2010 · STS-130": "LANÇADO EM 8 FEV 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · PORTA VOLTADA PARA A TERRA",
"LABORATORY MODULE · ISS": "MÓDULO LABORATÓRIO · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Agência de Exploração Aeroespacial do Japão (JAXA)",
"2 WINDOWS": "2 JANELAS",
"LAUNCHED 31 MAY 2008 · STS-124": "LANÇADO EM 31 MAI 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · LADO BOMBORDO",
"Return to the default view": "Voltar à vista padrão",
"{label} · STATION VIEW": "{label} · VISTA DA ESTAÇÃO",
"ON AIR": "NO AR",
"Starting…": "A iniciar…",
"Stream is offline": "A transmissão está offline",
"LIVE VIDEO": "VÍDEO AO VIVO",
"STREAM ATTACHED TO THE SUBJECT": "TRANSMISSÃO VINCULADA AO OBJETO",
"Live video": "Vídeo ao vivo",
"Show Live Video": "Mostrar vídeo ao vivo",
"This stream cannot play here": "Esta transmissão não pode ser reproduzida aqui",
"Expand Live section": "Expandir a secção Ao vivo",
"Collapse Live section": "Recolher a secção Ao vivo",
"Expand Live": "Expandir Ao vivo",
"Collapse Live": "Recolher Ao vivo",
"Live streams for the selected object": "Transmissões ao vivo do objeto selecionado",
"Stream": "Transmissão",
"Previous stream": "Transmissão anterior",
"Next stream": "Próxima transmissão",
"Try again": "Tentar novamente",
"Exterior cameras": "Câmaras exteriores",
"Live video and space-to-ground audio": "Vídeo ao vivo e áudio espaço-terra",
"NASA video, via YouTube": "Vídeo da NASA, via YouTube",
"Controls for the selected space station": "Controlos da estação espacial selecionada",
"Expand Station section": "Expandir a secção Estação",
"Collapse Station section": "Recolher a secção Estação",
"Expand Station": "Expandir Estação",
"Collapse Station": "Recolher Estação",
"Manual · telemetry paused": "Manual · telemetria em pausa",
"Telemetry · updated {ago} ago": "Telemetria · atualizada há {ago}",
"No signal since {time} · computed values": "Sem sinal desde as {time} · valores calculados",
"No signal · computed values": "Sem sinal · valores calculados",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetria indisponível · última atualização há {ago} · valores calculados",
"Telemetry unavailable · computed values": "Telemetria indisponível · valores calculados",
"Telemetry not enabled on this server · computed values": "Telemetria não ativada neste servidor · valores calculados",
"No public telemetry · computed values": "Sem telemetria pública · valores calculados",
"Zoom to Tiangong": "Aproximar de Tiangong",
"Tianhe arm (degrees)": "Braço de Tianhe (graus)",
"Tianhe wings (degrees)": "Asas de Tianhe (graus)",
"Lab wings (degrees)": "Asas dos laboratórios (graus)",
"Port wing": "Asa de bombordo",
"Starboard wing": "Asa de estibordo",
"Wentian forward · alpha": "Wentian dianteira · alfa",
"Wentian forward · beta": "Wentian dianteira · beta",
"Wentian aft · alpha": "Wentian traseira · alfa",
"Wentian aft · beta": "Wentian traseira · beta",
"Mengtian forward · alpha": "Mengtian dianteira · alfa",
"Mengtian forward · beta": "Mengtian dianteira · beta",
"Mengtian aft · alpha": "Mengtian traseira · alfa",
"Mengtian aft · beta": "Mengtian traseira · beta",
"Wentian arm (degrees)": "Braço de Wentian (graus)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Os painéis seguem o Sol, a antena aponta para os satélites de retransmissão e os braços oscilam a título ilustrativo. Calculado: a China não publica telemetria em direto.",
"Telemetry reads while the model is on screen": "A telemetria é lida enquanto o modelo está no ecrã",
"Connecting to telemetry…": "A ligar à telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Painéis, radiadores e uma antena seguem a telemetria ao vivo da NASA. A outra antena fica parada e os braços se movem de forma ilustrativa."
}
+111 -1
View File
@@ -4527,5 +4527,115 @@
"Select a map item to see its details.": "Выберите объект на карте, чтобы увидеть подробности.",
"Bilawal on {site}": "Билал на {site}",
"Bilawal's website": "Сайт Билала",
"BACK": "НАЗАД"
"BACK": "НАЗАД",
"Finding it…": "Поиск…",
"No reading at this time": "Нет данных на это время",
"Last reading · {age}": "Последние данные · {age}",
"Find it": "Найти",
"Underneath": "Снизу",
"Open on YouTube": "Открыть на YouTube",
"Video plays from YouTube, which sees your IP address.": "Видео воспроизводится с YouTube, который видит ваш IP-адрес.",
"Automatic": "Автоматически",
"Manual": "Вручную",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Панели и радиаторы следят за Солнцем, антенны наводятся на спутники-ретрансляторы, а манипуляторы движутся для иллюстрации. Расчёт, а не телеметрия в реальном времени.",
"Overhead": "Сверху",
"Ahead": "Спереди",
"Behind": "Сзади",
"Port side": "Левый борт",
"Starboard side": "Правый борт",
"Night (shadow)": "Ночь (тень)",
"Sun position": "Положение Солнца",
"Follow the Sun": "Следить за Солнцем",
"Fast orbit (40 s)": "Быстрый виток (40 с)",
"Solar arrays": "Солнечные батареи",
"Demonstration: the real arrays stay extended.": "Демонстрация: настоящие батареи остаются раскрытыми.",
"Retract": "Сложить",
"Extend": "Раскрыть",
"Radiators": "Радиаторы",
"Demonstration: the real radiators can fold but stay extended.": "Демонстрация: настоящие радиаторы складываются, но остаются раскрытыми.",
"Dishes": "Антенны",
"Relay satellites": "Спутники-ретрансляторы",
"Up": "Вверх",
"Forward": "Вперёд",
"Sideways": "В сторону",
"Shoulder roll": "Плечо: крен",
"Shoulder yaw": "Плечо: рыскание",
"Shoulder pitch": "Плечо: тангаж",
"Elbow": "Локоть",
"Wrist pitch": "Запястье: тангаж",
"Wrist yaw": "Запястье: рыскание",
"Wrist roll": "Запястье: крен",
"Canadarm2 (degrees)": "Canadarm2 (градусы)",
"Resume sway": "Возобновить движение",
"Zoom to the ISS": "Приблизить к МКС",
"Now: in sunlight": "Сейчас: на свету",
"Now: in the Earth's shadow": "Сейчас: в тени Земли",
"STATION VIEW · {name}": "ВИД СО СТАНЦИИ · {name}",
"Previous station view": "Предыдущий вид со станции",
"Next station view": "Следующий вид со станции",
"OBSERVATION MODULE · ISS": "МОДУЛЬ НАБЛЮДЕНИЯ · МКС",
"European Space Agency (ESA)": "Европейское космическое агентство (ЕКА)",
"7 WINDOWS": "7 ИЛЛЮМИНАТОРОВ",
"LAUNCHED 8 FEB 2010 · STS-130": "ЗАПУЩЕН 8 ФЕВ 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · ПОРТ, ОБРАЩЁННЫЙ К ЗЕМЛЕ",
"LABORATORY MODULE · ISS": "ЛАБОРАТОРНЫЙ МОДУЛЬ · МКС",
"Japan Aerospace Exploration Agency (JAXA)": "Японское агентство аэрокосмических исследований (JAXA)",
"2 WINDOWS": "2 ИЛЛЮМИНАТОРА",
"LAUNCHED 31 MAY 2008 · STS-124": "ЗАПУЩЕН 31 МАЯ 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · ЛЕВЫЙ БОРТ",
"Return to the default view": "Вернуть вид по умолчанию",
"{label} · STATION VIEW": "{label} · ВИД СО СТАНЦИИ",
"ON AIR": "В ЭФИРЕ",
"Starting…": "Запуск…",
"Stream is offline": "Трансляция не ведётся",
"LIVE VIDEO": "ВИДЕО ОНЛАЙН",
"STREAM ATTACHED TO THE SUBJECT": "ТРАНСЛЯЦИЯ ВЫБРАННОГО ОБЪЕКТА",
"Live video": "Видео онлайн",
"Show Live Video": "Показать видео онлайн",
"This stream cannot play here": "Эту трансляцию нельзя воспроизвести здесь",
"Expand Live section": "Развернуть раздел «Эфир»",
"Collapse Live section": "Свернуть раздел «Эфир»",
"Expand Live": "Развернуть «Эфир»",
"Collapse Live": "Свернуть «Эфир»",
"Live streams for the selected object": "Прямые трансляции выбранного объекта",
"Stream": "Трансляция",
"Previous stream": "Предыдущая трансляция",
"Next stream": "Следующая трансляция",
"Try again": "Повторить",
"Exterior cameras": "Внешние камеры",
"Live video and space-to-ground audio": "Прямое видео и переговоры с Землёй",
"NASA video, via YouTube": "Видео NASA, через YouTube",
"Controls for the selected space station": "Управление выбранной космической станцией",
"Expand Station section": "Развернуть раздел «Станция»",
"Collapse Station section": "Свернуть раздел «Станция»",
"Expand Station": "Развернуть «Станцию»",
"Collapse Station": "Свернуть «Станцию»",
"Manual · telemetry paused": "Вручную · телеметрия приостановлена",
"Telemetry · updated {ago} ago": "Телеметрия · обновлено {ago} назад",
"No signal since {time} · computed values": "Нет сигнала с {time} · расчётные значения",
"No signal · computed values": "Нет сигнала · расчётные значения",
"Telemetry unavailable · last update {ago} ago · computed values": "Телеметрия недоступна · последнее обновление {ago} назад · расчётные значения",
"Telemetry unavailable · computed values": "Телеметрия недоступна · расчётные значения",
"Telemetry not enabled on this server · computed values": "Телеметрия не включена на этом сервере · расчётные значения",
"No public telemetry · computed values": "Открытой телеметрии нет · расчётные значения",
"Zoom to Tiangong": "Приблизить к «Тяньгун»",
"Tianhe arm (degrees)": "Манипулятор «Тяньхэ» (градусы)",
"Tianhe wings (degrees)": "Крылья «Тяньхэ» (градусы)",
"Lab wings (degrees)": "Крылья лабораторий (градусы)",
"Port wing": "Левое крыло",
"Starboard wing": "Правое крыло",
"Wentian forward · alpha": "«Вэньтянь», передняя · альфа",
"Wentian forward · beta": "«Вэньтянь», передняя · бета",
"Wentian aft · alpha": "«Вэньтянь», задняя · альфа",
"Wentian aft · beta": "«Вэньтянь», задняя · бета",
"Mengtian forward · alpha": "«Мэнтянь», передняя · альфа",
"Mengtian forward · beta": "«Мэнтянь», передняя · бета",
"Mengtian aft · alpha": "«Мэнтянь», задняя · альфа",
"Mengtian aft · beta": "«Мэнтянь», задняя · бета",
"Wentian arm (degrees)": "Манипулятор «Вэньтянь» (градусы)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Панели следят за Солнцем, антенна наводится на спутники-ретрансляторы, а манипуляторы покачиваются для наглядности. Расчёт: Китай не публикует телеметрию в реальном времени.",
"Telemetry reads while the model is on screen": "Телеметрия читается, пока модель на экране",
"Connecting to telemetry…": "Подключение к телеметрии…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации."
}
+111 -1
View File
@@ -4315,5 +4315,115 @@
"Bilawal on YouTube": "Bilawal på YouTube",
"The studio behind GEV": "Studion bakom GEV",
"Open source. Self-host, fork, add a layer.": "Öppen källkod. Kör själv, skapa en egen variant, lägg till ett lager.",
"ENTER GOD MODE": "STARTA GUDLÄGE"
"ENTER GOD MODE": "STARTA GUDLÄGE",
"Finding it…": "Söker…",
"No reading at this time": "Ingen avläsning vid den här tiden",
"Last reading · {age}": "Senaste avläsning · {age}",
"Find it": "Hitta",
"Underneath": "Nedanför",
"Open on YouTube": "Öppna på YouTube",
"Video plays from YouTube, which sees your IP address.": "Videon spelas upp från YouTube, som ser din IP-adress.",
"Automatic": "Automatiskt",
"Manual": "Manuellt",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Paneler och radiatorer följer solen, antennerna riktas mot relästationer i rymden och armarna rör sig som illustration. Beräknat, inte telemetri i realtid.",
"Overhead": "Ovanför",
"Ahead": "Framför",
"Behind": "Bakom",
"Port side": "Babord",
"Starboard side": "Styrbord",
"Night (shadow)": "Natt (skugga)",
"Sun position": "Solens läge",
"Follow the Sun": "Följ solen",
"Fast orbit (40 s)": "Snabbt varv (40 s)",
"Solar arrays": "Solpaneler",
"Demonstration: the real arrays stay extended.": "Demonstration: de verkliga panelerna förblir utfällda.",
"Retract": "Fäll in",
"Extend": "Fäll ut",
"Radiators": "Radiatorer",
"Demonstration: the real radiators can fold but stay extended.": "Demonstration: de verkliga radiatorerna kan vikas men förblir utfällda.",
"Dishes": "Antenner",
"Relay satellites": "Reläsatelliter",
"Up": "Uppåt",
"Forward": "Framåt",
"Sideways": "Åt sidan",
"Shoulder roll": "Axel, roll",
"Shoulder yaw": "Axel, gir",
"Shoulder pitch": "Axel, tipp",
"Elbow": "Armbåge",
"Wrist pitch": "Handled, tipp",
"Wrist yaw": "Handled, gir",
"Wrist roll": "Handled, roll",
"Canadarm2 (degrees)": "Canadarm2 (grader)",
"Resume sway": "Återuppta rörelsen",
"Zoom to the ISS": "Zooma in på ISS",
"Now: in sunlight": "Nu: i solljus",
"Now: in the Earth's shadow": "Nu: i jordens skugga",
"{label} · STATION VIEW": "{label} · STATIONSVY",
"STATION VIEW · {name}": "STATIONSVY · {name}",
"Previous station view": "Föregående stationsvy",
"Next station view": "Nästa stationsvy",
"OBSERVATION MODULE · ISS": "OBSERVATIONSMODUL · ISS",
"European Space Agency (ESA)": "Europeiska rymdorganisationen (ESA)",
"7 WINDOWS": "7 FÖNSTER",
"LAUNCHED 8 FEB 2010 · STS-130": "UPPSKJUTEN 8 FEB 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · DOCKNINGSPORT MOT JORDEN",
"LABORATORY MODULE · ISS": "LABORATORIEMODUL · ISS",
"Japan Aerospace Exploration Agency (JAXA)": "Japans rymdorganisation (JAXA)",
"2 WINDOWS": "2 FÖNSTER",
"LAUNCHED 31 MAY 2008 · STS-124": "UPPSKJUTEN 31 MAJ 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · BABORDSSIDAN",
"Return to the default view": "Återgå till standardvyn",
"ON AIR": "PÅ LUFTEN",
"Starting…": "Startar…",
"Stream is offline": "Strömmen är offline",
"LIVE VIDEO": "LIVEVIDEO",
"STREAM ATTACHED TO THE SUBJECT": "STRÖM KNUTEN TILL OBJEKTET",
"Live video": "Livevideo",
"Show Live Video": "Visa livevideo",
"This stream cannot play here": "Den här strömmen kan inte spelas upp här",
"Expand Live section": "Expandera Live-sektionen",
"Collapse Live section": "Fäll ihop Live-sektionen",
"Expand Live": "Expandera Live",
"Collapse Live": "Fäll ihop Live",
"Live streams for the selected object": "Liveströmmar för det valda objektet",
"Stream": "Ström",
"Previous stream": "Föregående ström",
"Next stream": "Nästa ström",
"Try again": "Försök igen",
"Exterior cameras": "Yttre kameror",
"Live video and space-to-ground audio": "Livevideo och ljud rymd–mark",
"NASA video, via YouTube": "NASA-video, via YouTube",
"Controls for the selected space station": "Reglage för den valda rymdstationen",
"Expand Station section": "Expandera Station-sektionen",
"Collapse Station section": "Fäll ihop Station-sektionen",
"Expand Station": "Expandera Station",
"Collapse Station": "Fäll ihop Station",
"Manual · telemetry paused": "Manuellt · telemetri pausad",
"Telemetry · updated {ago} ago": "Telemetri · uppdaterad för {ago} sedan",
"No signal since {time} · computed values": "Ingen signal sedan {time} · beräknade värden",
"No signal · computed values": "Ingen signal · beräknade värden",
"Telemetry unavailable · last update {ago} ago · computed values": "Telemetri otillgänglig · senast uppdaterad för {ago} sedan · beräknade värden",
"Telemetry unavailable · computed values": "Telemetri otillgänglig · beräknade värden",
"Telemetry not enabled on this server · computed values": "Telemetri inte aktiverad på den här servern · beräknade värden",
"No public telemetry · computed values": "Ingen offentlig telemetri · beräknade värden",
"Zoom to Tiangong": "Zooma in på Tiangong",
"Tianhe arm (degrees)": "Tianhe-armen (grader)",
"Tianhe wings (degrees)": "Tianhes vingar (grader)",
"Lab wings (degrees)": "Laboratoriernas vingar (grader)",
"Port wing": "Babordsvinge",
"Starboard wing": "Styrbordsvinge",
"Wentian forward · alpha": "Wentian fram · alfa",
"Wentian forward · beta": "Wentian fram · beta",
"Wentian aft · alpha": "Wentian bak · alfa",
"Wentian aft · beta": "Wentian bak · beta",
"Mengtian forward · alpha": "Mengtian fram · alfa",
"Mengtian forward · beta": "Mengtian fram · beta",
"Mengtian aft · alpha": "Mengtian bak · alfa",
"Mengtian aft · beta": "Mengtian bak · beta",
"Wentian arm (degrees)": "Wentian-armen (grader)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Panelerna följer solen, antennen riktas mot relästationer i rymden och armarna svänger i illustrativt syfte. Beräknat: Kina publicerar ingen live-telemetri.",
"Telemetry reads while the model is on screen": "Telemetri läses medan modellen syns på skärmen",
"Connecting to telemetry…": "Ansluter till telemetri…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Paneler, radiatorer och en antenn följer NASA:s telemetri i realtid. Den andra antennen står stilla och armarna rör sig som illustration."
}
+111 -1
View File
@@ -4527,5 +4527,115 @@
"Select a map item to see its details.": "Виберіть об’єкт на карті, щоб побачити подробиці.",
"Bilawal on {site}": "Білал на {site}",
"Bilawal's website": "Сайт Білала",
"BACK": "НАЗАД"
"BACK": "НАЗАД",
"Finding it…": "Пошук…",
"No reading at this time": "Немає даних на цей час",
"Last reading · {age}": "Останні дані · {age}",
"Find it": "Знайти",
"Underneath": "Знизу",
"Open on YouTube": "Відкрити на YouTube",
"Video plays from YouTube, which sees your IP address.": "Відео відтворюється з YouTube, який бачить вашу IP-адресу.",
"Automatic": "Автоматично",
"Manual": "Вручну",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "Панелі й радіатори стежать за Сонцем, антени наводяться на супутники-ретранслятори, а маніпулятори рухаються для ілюстрації. Розрахунок, а не телеметрія в реальному часі.",
"Overhead": "Згори",
"Ahead": "Спереду",
"Behind": "Позаду",
"Port side": "Лівий борт",
"Starboard side": "Правий борт",
"Night (shadow)": "Ніч (тінь)",
"Sun position": "Положення Сонця",
"Follow the Sun": "Стежити за Сонцем",
"Fast orbit (40 s)": "Швидкий виток (40 с)",
"Solar arrays": "Сонячні батареї",
"Demonstration: the real arrays stay extended.": "Демонстрація: справжні батареї залишаються розкритими.",
"Retract": "Скласти",
"Extend": "Розкрити",
"Radiators": "Радіатори",
"Demonstration: the real radiators can fold but stay extended.": "Демонстрація: справжні радіатори складаються, але залишаються розкритими.",
"Dishes": "Антени",
"Relay satellites": "Супутники-ретранслятори",
"Up": "Вгору",
"Forward": "Вперед",
"Sideways": "Убік",
"Shoulder roll": "Плече: крен",
"Shoulder yaw": "Плече: рискання",
"Shoulder pitch": "Плече: тангаж",
"Elbow": "Лікоть",
"Wrist pitch": "Зап'ястя: тангаж",
"Wrist yaw": "Зап'ястя: рискання",
"Wrist roll": "Зап'ястя: крен",
"Canadarm2 (degrees)": "Canadarm2 (градуси)",
"Resume sway": "Відновити рух",
"Zoom to the ISS": "Наблизити до МКС",
"Now: in sunlight": "Зараз: на світлі",
"Now: in the Earth's shadow": "Зараз: у тіні Землі",
"STATION VIEW · {name}": "ВИГЛЯД ЗІ СТАНЦІЇ · {name}",
"Previous station view": "Попередній вигляд зі станції",
"Next station view": "Наступний вигляд зі станції",
"OBSERVATION MODULE · ISS": "МОДУЛЬ СПОСТЕРЕЖЕННЯ · МКС",
"European Space Agency (ESA)": "Європейське космічне агентство (ЄКА)",
"7 WINDOWS": "7 ІЛЮМІНАТОРІВ",
"LAUNCHED 8 FEB 2010 · STS-130": "ЗАПУЩЕНО 8 ЛЮТ 2010 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "TRANQUILITY · ПОРТ, ЗВЕРНЕНИЙ ДО ЗЕМЛІ",
"LABORATORY MODULE · ISS": "ЛАБОРАТОРНИЙ МОДУЛЬ · МКС",
"Japan Aerospace Exploration Agency (JAXA)": "Японське агентство аерокосмічних досліджень (JAXA)",
"2 WINDOWS": "2 ІЛЮМІНАТОРИ",
"LAUNCHED 31 MAY 2008 · STS-124": "ЗАПУЩЕНО 31 ТРАВ 2008 · STS-124",
"HARMONY · PORT SIDE": "HARMONY · ЛІВИЙ БОРТ",
"Return to the default view": "Повернути типовий вигляд",
"{label} · STATION VIEW": "{label} · ВИГЛЯД ЗІ СТАНЦІЇ",
"ON AIR": "В ЕФІРІ",
"Starting…": "Запуск…",
"Stream is offline": "Трансляція не ведеться",
"LIVE VIDEO": "ВІДЕО ОНЛАЙН",
"STREAM ATTACHED TO THE SUBJECT": "ТРАНСЛЯЦІЯ ВИБРАНОГО ОБ’ЄКТА",
"Live video": "Відео онлайн",
"Show Live Video": "Показати відео онлайн",
"This stream cannot play here": "Цю трансляцію не можна відтворити тут",
"Expand Live section": "Розгорнути розділ «Ефір»",
"Collapse Live section": "Згорнути розділ «Ефір»",
"Expand Live": "Розгорнути «Ефір»",
"Collapse Live": "Згорнути «Ефір»",
"Live streams for the selected object": "Прямі трансляції вибраного об’єкта",
"Stream": "Трансляція",
"Previous stream": "Попередня трансляція",
"Next stream": "Наступна трансляція",
"Try again": "Повторити",
"Exterior cameras": "Зовнішні камери",
"Live video and space-to-ground audio": "Пряме відео та переговори із Землею",
"NASA video, via YouTube": "Відео NASA, через YouTube",
"Controls for the selected space station": "Керування вибраною космічною станцією",
"Expand Station section": "Розгорнути розділ «Станція»",
"Collapse Station section": "Згорнути розділ «Станція»",
"Expand Station": "Розгорнути «Станцію»",
"Collapse Station": "Згорнути «Станцію»",
"Manual · telemetry paused": "Вручну · телеметрію призупинено",
"Telemetry · updated {ago} ago": "Телеметрія · оновлено {ago} тому",
"No signal since {time} · computed values": "Немає сигналу з {time} · розрахункові значення",
"No signal · computed values": "Немає сигналу · розрахункові значення",
"Telemetry unavailable · last update {ago} ago · computed values": "Телеметрія недоступна · останнє оновлення {ago} тому · розрахункові значення",
"Telemetry unavailable · computed values": "Телеметрія недоступна · розрахункові значення",
"Telemetry not enabled on this server · computed values": "Телеметрію не ввімкнено на цьому сервері · розрахункові значення",
"No public telemetry · computed values": "Відкритої телеметрії немає · розрахункові значення",
"Zoom to Tiangong": "Наблизити до «Тяньгун»",
"Tianhe arm (degrees)": "Маніпулятор «Тяньхе» (градуси)",
"Tianhe wings (degrees)": "Крила «Тяньхе» (градуси)",
"Lab wings (degrees)": "Крила лабораторій (градуси)",
"Port wing": "Ліве крило",
"Starboard wing": "Праве крило",
"Wentian forward · alpha": "«Веньтянь», передня · альфа",
"Wentian forward · beta": "«Веньтянь», передня · бета",
"Wentian aft · alpha": "«Веньтянь», задня · альфа",
"Wentian aft · beta": "«Веньтянь», задня · бета",
"Mengtian forward · alpha": "«Ментянь», передня · альфа",
"Mengtian forward · beta": "«Ментянь», передня · бета",
"Mengtian aft · alpha": "«Ментянь», задня · альфа",
"Mengtian aft · beta": "«Ментянь», задня · бета",
"Wentian arm (degrees)": "Маніпулятор «Веньтянь» (градуси)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "Панелі стежать за Сонцем, антена наводиться на супутники-ретранслятори, а маніпулятори похитуються для наочності. Розрахунок: Китай не публікує телеметрію в реальному часі.",
"Telemetry reads while the model is on screen": "Телеметрія читається, поки модель на екрані",
"Connecting to telemetry…": "Підключення до телеметрії…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації."
}
+111 -1
View File
@@ -4209,5 +4209,115 @@
"Select a map item to see its details.": "选择地图上的项目以查看详情。",
"Bilawal on {site}": "Bilawal 的 {site} 主页",
"Bilawal's website": "Bilawal 的网站",
"BACK": "返回"
"BACK": "返回",
"Finding it…": "正在查找…",
"No reading at this time": "此时无数据",
"Last reading · {age}": "最后数据 · {age}",
"Find it": "查找",
"Underneath": "正下方",
"Open on YouTube": "在 YouTube 上打开",
"Video plays from YouTube, which sees your IP address.": "视频从 YouTube 播放,YouTube 会看到你的 IP 地址。",
"Automatic": "自动",
"Manual": "手动",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "太阳能板和散热器跟随太阳,天线指向中继卫星,机械臂仅作演示性摆动。均为计算结果,并非实时遥测。",
"Overhead": "正上方",
"Ahead": "前方",
"Behind": "后方",
"Port side": "左舷",
"Starboard side": "右舷",
"Night (shadow)": "夜间(阴影)",
"Sun position": "太阳位置",
"Follow the Sun": "跟随太阳",
"Fast orbit (40 s)": "快速绕行(40 秒)",
"Solar arrays": "太阳能板",
"Demonstration: the real arrays stay extended.": "演示:真实的太阳能板保持展开。",
"Retract": "收起",
"Extend": "展开",
"Radiators": "散热器",
"Demonstration: the real radiators can fold but stay extended.": "演示:真实的散热器可以折叠,但保持展开。",
"Dishes": "天线",
"Relay satellites": "中继卫星",
"Up": "向上",
"Forward": "向前",
"Sideways": "向侧面",
"Shoulder roll": "肩部滚转",
"Shoulder yaw": "肩部偏航",
"Shoulder pitch": "肩部俯仰",
"Elbow": "肘部",
"Wrist pitch": "腕部俯仰",
"Wrist yaw": "腕部偏航",
"Wrist roll": "腕部滚转",
"Canadarm2 (degrees)": "Canadarm2(度)",
"Resume sway": "恢复摆动",
"Zoom to the ISS": "拉近到国际空间站",
"Now: in sunlight": "当前:处于日照中",
"Now: in the Earth's shadow": "当前:处于地球阴影中",
"STATION VIEW · {name}": "空间站视图 · {name}",
"Previous station view": "上一个空间站视图",
"Next station view": "下一个空间站视图",
"OBSERVATION MODULE · ISS": "观测舱 · 国际空间站",
"European Space Agency (ESA)": "欧洲航天局(ESA)",
"7 WINDOWS": "7 扇舷窗",
"LAUNCHED 8 FEB 2010 · STS-130": "2010年2月8日发射 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "宁静号节点舱 · 对地端口",
"LABORATORY MODULE · ISS": "实验舱 · 国际空间站",
"Japan Aerospace Exploration Agency (JAXA)": "日本宇宙航空研究开发机构(JAXA)",
"2 WINDOWS": "2 扇舷窗",
"LAUNCHED 31 MAY 2008 · STS-124": "2008年5月31日发射 · STS-124",
"HARMONY · PORT SIDE": "和谐号节点舱 · 左舷",
"Return to the default view": "恢复默认视图",
"{label} · STATION VIEW": "{label} · 空间站视图",
"ON AIR": "直播中",
"Starting…": "正在启动…",
"Stream is offline": "直播已离线",
"LIVE VIDEO": "实时视频",
"STREAM ATTACHED TO THE SUBJECT": "与所选对象关联的直播",
"Live video": "实时视频",
"Show Live Video": "显示实时视频",
"This stream cannot play here": "此直播无法在此播放",
"Expand Live section": "展开直播区",
"Collapse Live section": "收起直播区",
"Expand Live": "展开直播",
"Collapse Live": "收起直播",
"Live streams for the selected object": "所选对象的直播",
"Stream": "直播",
"Previous stream": "上一个直播",
"Next stream": "下一个直播",
"Try again": "重试",
"Exterior cameras": "外部摄像头",
"Live video and space-to-ground audio": "实时视频与天地通话音频",
"NASA video, via YouTube": "NASA 视频,经由 YouTube",
"Controls for the selected space station": "所选空间站的控制",
"Expand Station section": "展开空间站区",
"Collapse Station section": "收起空间站区",
"Expand Station": "展开空间站",
"Collapse Station": "收起空间站",
"Manual · telemetry paused": "手动 · 遥测已暂停",
"Telemetry · updated {ago} ago": "遥测 · {ago}前更新",
"No signal since {time} · computed values": "自 {time} 起无信号 · 计算值",
"No signal · computed values": "无信号 · 计算值",
"Telemetry unavailable · last update {ago} ago · computed values": "遥测不可用 · 最后更新于{ago}前 · 计算值",
"Telemetry unavailable · computed values": "遥测不可用 · 计算值",
"Telemetry not enabled on this server · computed values": "此服务器未启用遥测 · 计算值",
"No public telemetry · computed values": "无公开遥测 · 计算值",
"Zoom to Tiangong": "拉近到天宫",
"Tianhe arm (degrees)": "天和机械臂(度)",
"Tianhe wings (degrees)": "天和翼板(度)",
"Lab wings (degrees)": "实验舱翼板(度)",
"Port wing": "左侧翼板",
"Starboard wing": "右侧翼板",
"Wentian forward · alpha": "问天前侧 · α",
"Wentian forward · beta": "问天前侧 · β",
"Wentian aft · alpha": "问天后侧 · α",
"Wentian aft · beta": "问天后侧 · β",
"Mengtian forward · alpha": "梦天前侧 · α",
"Mengtian forward · beta": "梦天前侧 · β",
"Mengtian aft · alpha": "梦天后侧 · α",
"Mengtian aft · beta": "梦天后侧 · β",
"Wentian arm (degrees)": "问天机械臂(度)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "太阳能板跟随太阳,天线指向中继卫星,机械臂仅作示意摆动。计算值:中国不公开实时遥测。",
"Telemetry reads while the model is on screen": "模型显示在屏幕上时读取遥测",
"Connecting to telemetry…": "正在连接遥测…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。"
}
+111 -1
View File
@@ -4209,5 +4209,115 @@
"Select a map item to see its details.": "選擇地圖上的項目以查看詳情。",
"Bilawal on {site}": "Bilawal 的 {site} 主頁",
"Bilawal's website": "Bilawal 的網站",
"BACK": "返回"
"BACK": "返回",
"Finding it…": "正在查找…",
"No reading at this time": "此時無數據",
"Last reading · {age}": "最後數據 · {age}",
"Find it": "查找",
"Underneath": "正下方",
"Open on YouTube": "在 YouTube 上打開",
"Video plays from YouTube, which sees your IP address.": "視頻從 YouTube 播放,YouTube 會看到你的 IP 地址。",
"Automatic": "自動",
"Manual": "手動",
"Arrays and radiators follow the Sun, the dishes aim at relay satellites and the arms sway for illustration. Computed, not live telemetry.": "太陽能板和散熱器跟隨太陽,天線指向中繼衛星,機械臂僅作演示性擺動。均為計算結果,並非實時遙測。",
"Overhead": "正上方",
"Ahead": "前方",
"Behind": "後方",
"Port side": "左舷",
"Starboard side": "右舷",
"Night (shadow)": "夜間(陰影)",
"Sun position": "太陽位置",
"Follow the Sun": "跟隨太陽",
"Fast orbit (40 s)": "快速繞行(40 秒)",
"Solar arrays": "太陽能板",
"Demonstration: the real arrays stay extended.": "演示:真實的太陽能板保持展開。",
"Retract": "收起",
"Extend": "展開",
"Radiators": "散熱器",
"Demonstration: the real radiators can fold but stay extended.": "演示:真實的散熱器可以摺疊,但保持展開。",
"Dishes": "天線",
"Relay satellites": "中繼衛星",
"Up": "向上",
"Forward": "向前",
"Sideways": "向側面",
"Shoulder roll": "肩部滾轉",
"Shoulder yaw": "肩部偏航",
"Shoulder pitch": "肩部俯仰",
"Elbow": "肘部",
"Wrist pitch": "腕部俯仰",
"Wrist yaw": "腕部偏航",
"Wrist roll": "腕部滾轉",
"Canadarm2 (degrees)": "Canadarm2(度)",
"Resume sway": "恢復擺動",
"Zoom to the ISS": "拉近到國際空間站",
"Now: in sunlight": "當前:處於日照中",
"Now: in the Earth's shadow": "當前:處於地球陰影中",
"STATION VIEW · {name}": "空間站視圖 · {name}",
"Previous station view": "上一個空間站視圖",
"Next station view": "下一個空間站視圖",
"OBSERVATION MODULE · ISS": "觀測艙 · 國際空間站",
"European Space Agency (ESA)": "歐洲航天局(ESA)",
"7 WINDOWS": "7 扇舷窗",
"LAUNCHED 8 FEB 2010 · STS-130": "2010年2月8日發射 · STS-130",
"TRANQUILITY · EARTH-FACING PORT": "寧靜號節點艙 · 對地端口",
"LABORATORY MODULE · ISS": "實驗艙 · 國際空間站",
"Japan Aerospace Exploration Agency (JAXA)": "日本宇宙航空研究開發機構(JAXA)",
"2 WINDOWS": "2 扇舷窗",
"LAUNCHED 31 MAY 2008 · STS-124": "2008年5月31日發射 · STS-124",
"HARMONY · PORT SIDE": "和諧號節點艙 · 左舷",
"Return to the default view": "恢復默認視圖",
"{label} · STATION VIEW": "{label} · 空間站視圖",
"ON AIR": "直播中",
"Starting…": "正在啟動…",
"Stream is offline": "直播已離線",
"LIVE VIDEO": "實時視頻",
"STREAM ATTACHED TO THE SUBJECT": "與所選對象關聯的直播",
"Live video": "實時視頻",
"Show Live Video": "顯示實時視頻",
"This stream cannot play here": "此直播無法在此播放",
"Expand Live section": "展開直播區",
"Collapse Live section": "收起直播區",
"Expand Live": "展開直播",
"Collapse Live": "收起直播",
"Live streams for the selected object": "所選對象的直播",
"Stream": "直播",
"Previous stream": "上一個直播",
"Next stream": "下一個直播",
"Try again": "重試",
"Exterior cameras": "外部攝像頭",
"Live video and space-to-ground audio": "實時視頻與天地通話音頻",
"NASA video, via YouTube": "NASA 視頻,經由 YouTube",
"Controls for the selected space station": "所選空間站的控制",
"Expand Station section": "展開空間站區",
"Collapse Station section": "收起空間站區",
"Expand Station": "展開空間站",
"Collapse Station": "收起空間站",
"Manual · telemetry paused": "手動 · 遙測已暫停",
"Telemetry · updated {ago} ago": "遙測 · {ago}前更新",
"No signal since {time} · computed values": "自 {time} 起無信號 · 計算值",
"No signal · computed values": "無信號 · 計算值",
"Telemetry unavailable · last update {ago} ago · computed values": "遙測不可用 · 最後更新於{ago}前 · 計算值",
"Telemetry unavailable · computed values": "遙測不可用 · 計算值",
"Telemetry not enabled on this server · computed values": "此服務器未啟用遙測 · 計算值",
"No public telemetry · computed values": "無公開遙測 · 計算值",
"Zoom to Tiangong": "拉近到天宮",
"Tianhe arm (degrees)": "天和機械臂(度)",
"Tianhe wings (degrees)": "天和翼板(度)",
"Lab wings (degrees)": "實驗艙翼板(度)",
"Port wing": "左側翼板",
"Starboard wing": "右側翼板",
"Wentian forward · alpha": "問天前側 · α",
"Wentian forward · beta": "問天前側 · β",
"Wentian aft · alpha": "問天後側 · α",
"Wentian aft · beta": "問天後側 · β",
"Mengtian forward · alpha": "夢天前側 · α",
"Mengtian forward · beta": "夢天前側 · β",
"Mengtian aft · alpha": "夢天後側 · α",
"Mengtian aft · beta": "夢天後側 · β",
"Wentian arm (degrees)": "問天機械臂(度)",
"Arrays follow the Sun, the antenna aims at relay satellites and the arms sway for illustration. Computed: China publishes no live telemetry.": "太陽能板跟隨太陽,天線指向中繼衛星,機械臂僅作示意擺動。計算值:中國不公開實時遙測。",
"Telemetry reads while the model is on screen": "模型顯示在屏幕上時讀取遙測",
"Connecting to telemetry…": "正在連接遙測…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。"
}
+17 -6
View File
@@ -295,7 +295,11 @@
"{n} mm",
"Route",
"3D",
"KT"
"KT",
"ON AIR",
"Stream",
"{seconds} s",
"Mode"
],
"es": [
"1 min/s",
@@ -489,7 +493,9 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"Manual",
"{seconds} s"
],
"fr": [
"1 min/s",
@@ -746,7 +752,8 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"{seconds} s"
],
"it": [
"1 min/s",
@@ -979,7 +986,8 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"{seconds} s"
],
"ja": [
"1090 MHz",
@@ -1257,7 +1265,9 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"Manual",
"{seconds} s"
],
"ru": [
"1900–1945",
@@ -1494,7 +1504,8 @@
"{n} min",
"{n} mm",
"3D",
"KT"
"KT",
"{seconds} s"
],
"uk": [
"1900–1945",
+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.
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff. Show more